Пример #1
0
func (n Endpoint) MarshalBencode() ([]byte, error) {
	var b [18]byte

	if n.IP == nil {
		return nil, nil
	}

	v4 := n.IP.To4()
	if v4 != nil {
		copy(b[:], v4)
		binary.BigEndian.PutUint16(b[4:6], uint16(n.Port))
		return bencode.EncodeBytes(b[0:6])
	}

	copy(b[0:16], n.IP.To16())
	binary.BigEndian.PutUint16(b[16:18], uint16(n.Port))
	return bencode.EncodeBytes(b[:])
}
Пример #2
0
func WriteResponse(conn denet.UDPConn, remoteAddr net.UDPAddr, q *Message, response interface{}) error {
	responseb, err := bencode.EncodeBytes(response)
	if err != nil {
		return err
	}

	msg := Message{
		TxID:      q.TxID,
		Type:      "r",
		Response_: responseb,
	}

	return Write(conn, remoteAddr, &msg)
}
Пример #3
0
func TestEndpoint(t *testing.T) {
	endpoints := []Endpoint{
		Endpoint{IP: net.ParseIP("1.2.3.4"), Port: 2345},
		Endpoint{IP: net.ParseIP("5.6.7.8"), Port: 8877},
	}

	b, err := bencode.EncodeBytes(endpoints)
	if err != nil {
		t.Fatalf("error: %v", err)
	}

	if fmt.Sprintf("%x", b) != "6c363a010203040929363a0506070822ad65" {
		t.Fatalf("mismatch: %x", b)
	}
}
Пример #4
0
// Send a query to a host.
func MakeQuery(method string, args interface{}) (*Message, error) {
	var txIDb [4]byte
	txIDi := newTxID()
	binary.LittleEndian.PutUint32(txIDb[:], txIDi)

	argsb, err := bencode.EncodeBytes(args)
	if err != nil {
		return nil, err
	}

	txID := string(txIDb[:])

	msg := Message{
		TxID:   txID,
		Type:   "q",
		Method: method,
		Args:   args,
		Args_:  argsb,
	}

	return &msg, nil
}
Пример #5
0
func (n krNodesIPv6) MarshalBencode() ([]byte, error) {
	b := bytes.Buffer{}

	var bb [38]byte

	for i := range n {
		v4 := n[i].Addr.IP.To4()
		if v4 != nil {
			return nil, fmt.Errorf("IPv4 address in IPv6 nodes list")
		}

		copy(bb[:], n[i].NodeID)
		copy(bb[20:], n[i].Addr.IP.To16())
		binary.BigEndian.PutUint16(bb[36:38], uint16(n[i].Addr.Port))

		_, err := b.Write(bb[:])
		if err != nil {
			return nil, err
		}
	}

	return bencode.EncodeBytes(b.Bytes())
}
Пример #6
0
func TestKRPC(t *testing.T) {
	for _, tt := range tests {
		msg, err := krpc.Decode([]byte(tt.B))
		if err != nil {
			t.Fatalf("cannot decode: %v", err)
		}

		if tt.Method != "" {
			err = msg.ResponseAsMethod(tt.Method)
			if err != nil {
				t.Fatalf("cannot decode response part: %v", err)
			}
		}

		b, err := bencode.EncodeBytes(msg)
		if err != nil {
			t.Fatalf("couldn't encode: %v", err)
		}

		msg2, err := krpc.Decode(b)
		if err != nil {
			t.Fatalf("cannot decode: %v: %v %v", err, string(b), tt.B)
		}

		if tt.Method != "" {
			err = msg2.ResponseAsMethod(tt.Method)
			if err != nil {
				t.Fatalf("cannot decode response part: %v", err)
			}
		}

		if !reflect.DeepEqual(msg, msg2) {
			t.Logf("not equal after reserialization: %#v != %#v", msg, msg2)
		}
	}
}