Exemple #1
0
// sendMessage is used internally to send a message, blocking for timeout
func (p *Peer) sendMessage(msg wire.Message) error {
	p.conn.SetWriteDeadline(time.Now().Add(timeoutSend))
	version := atomic.LoadUint32(&p.version)
	err := wire.WriteMessage(p.conn, msg, version, p.network)

	return err
}
Exemple #2
0
// TestMessage tests the Read/WriteMessage and Read/WriteMessageN API.
func TestMessage(t *testing.T) {
	pver := wire.ProtocolVersion

	// Create the various types of messages to test.

	// MsgVersion.
	addrYou := &net.TCPAddr{IP: net.ParseIP("192.168.0.1"), Port: 8333}
	you, err := wire.NewNetAddress(addrYou, wire.SFNodeNetwork)
	if err != nil {
		t.Errorf("NewNetAddress: %v", err)
	}
	you.Timestamp = time.Time{} // Version message has zero value timestamp.
	addrMe := &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8333}
	me, err := wire.NewNetAddress(addrMe, wire.SFNodeNetwork)
	if err != nil {
		t.Errorf("NewNetAddress: %v", err)
	}
	me.Timestamp = time.Time{} // Version message has zero value timestamp.
	msgVersion := wire.NewMsgVersion(me, you, 123123, 0)

	msgVerack := wire.NewMsgVerAck()
	msgGetAddr := wire.NewMsgGetAddr()
	msgAddr := wire.NewMsgAddr()
	msgGetBlocks := wire.NewMsgGetBlocks(&wire.ShaHash{})
	msgBlock := &blockOne
	msgInv := wire.NewMsgInv()
	msgGetData := wire.NewMsgGetData()
	msgNotFound := wire.NewMsgNotFound()
	msgTx := wire.NewMsgTx()
	msgPing := wire.NewMsgPing(123123)
	msgPong := wire.NewMsgPong(123123)
	msgGetHeaders := wire.NewMsgGetHeaders()
	msgHeaders := wire.NewMsgHeaders()
	msgAlert := wire.NewMsgAlert([]byte("payload"), []byte("signature"))
	msgMemPool := wire.NewMsgMemPool()
	msgFilterAdd := wire.NewMsgFilterAdd([]byte{0x01})
	msgFilterClear := wire.NewMsgFilterClear()
	msgFilterLoad := wire.NewMsgFilterLoad([]byte{0x01}, 10, 0, wire.BloomUpdateNone)
	bh := wire.NewBlockHeader(&wire.ShaHash{}, &wire.ShaHash{}, 0, 0)
	msgMerkleBlock := wire.NewMsgMerkleBlock(bh)
	msgReject := wire.NewMsgReject("block", wire.RejectDuplicate, "duplicate block")

	tests := []struct {
		in     wire.Message    // Value to encode
		out    wire.Message    // Expected decoded value
		pver   uint32          // Protocol version for wire encoding
		btcnet wire.BitcoinNet // Network to use for wire encoding
		bytes  int             // Expected num bytes read/written
	}{
		{msgVersion, msgVersion, pver, wire.MainNet, 125},
		{msgVerack, msgVerack, pver, wire.MainNet, 24},
		{msgGetAddr, msgGetAddr, pver, wire.MainNet, 24},
		{msgAddr, msgAddr, pver, wire.MainNet, 25},
		{msgGetBlocks, msgGetBlocks, pver, wire.MainNet, 61},
		{msgBlock, msgBlock, pver, wire.MainNet, 239},
		{msgInv, msgInv, pver, wire.MainNet, 25},
		{msgGetData, msgGetData, pver, wire.MainNet, 25},
		{msgNotFound, msgNotFound, pver, wire.MainNet, 25},
		{msgTx, msgTx, pver, wire.MainNet, 34},
		{msgPing, msgPing, pver, wire.MainNet, 32},
		{msgPong, msgPong, pver, wire.MainNet, 32},
		{msgGetHeaders, msgGetHeaders, pver, wire.MainNet, 61},
		{msgHeaders, msgHeaders, pver, wire.MainNet, 25},
		{msgAlert, msgAlert, pver, wire.MainNet, 42},
		{msgMemPool, msgMemPool, pver, wire.MainNet, 24},
		{msgFilterAdd, msgFilterAdd, pver, wire.MainNet, 26},
		{msgFilterClear, msgFilterClear, pver, wire.MainNet, 24},
		{msgFilterLoad, msgFilterLoad, pver, wire.MainNet, 35},
		{msgMerkleBlock, msgMerkleBlock, pver, wire.MainNet, 110},
		{msgReject, msgReject, pver, wire.MainNet, 79},
	}

	t.Logf("Running %d tests", len(tests))
	for i, test := range tests {
		// Encode to wire format.
		var buf bytes.Buffer
		nw, err := wire.WriteMessageN(&buf, test.in, test.pver, test.btcnet)
		if err != nil {
			t.Errorf("WriteMessage #%d error %v", i, err)
			continue
		}

		// Ensure the number of bytes written match the expected value.
		if nw != test.bytes {
			t.Errorf("WriteMessage #%d unexpected num bytes "+
				"written - got %d, want %d", i, nw, test.bytes)
		}

		// Decode from wire format.
		rbuf := bytes.NewReader(buf.Bytes())
		nr, msg, _, err := wire.ReadMessageN(rbuf, test.pver, test.btcnet)
		if err != nil {
			t.Errorf("ReadMessage #%d error %v, msg %v", i, err,
				spew.Sdump(msg))
			continue
		}
		if !reflect.DeepEqual(msg, test.out) {
			t.Errorf("ReadMessage #%d\n got: %v want: %v", i,
				spew.Sdump(msg), spew.Sdump(test.out))
			continue
		}

		// Ensure the number of bytes read match the expected value.
		if nr != test.bytes {
			t.Errorf("ReadMessage #%d unexpected num bytes read - "+
				"got %d, want %d", i, nr, test.bytes)
		}
	}

	// Do the same thing for Read/WriteMessage, but ignore the bytes since
	// they don't return them.
	t.Logf("Running %d tests", len(tests))
	for i, test := range tests {
		// Encode to wire format.
		var buf bytes.Buffer
		err := wire.WriteMessage(&buf, test.in, test.pver, test.btcnet)
		if err != nil {
			t.Errorf("WriteMessage #%d error %v", i, err)
			continue
		}

		// Decode from wire format.
		rbuf := bytes.NewReader(buf.Bytes())
		msg, _, err := wire.ReadMessage(rbuf, test.pver, test.btcnet)
		if err != nil {
			t.Errorf("ReadMessage #%d error %v, msg %v", i, err,
				spew.Sdump(msg))
			continue
		}
		if !reflect.DeepEqual(msg, test.out) {
			t.Errorf("ReadMessage #%d\n got: %v want: %v", i,
				spew.Sdump(msg), spew.Sdump(test.out))
			continue
		}
	}
}
Exemple #3
0
// crawlIP retrievs a slice of ip addresses from a client
func crawlIP(s *dnsseeder, r *result) ([]*wire.NetAddress, *crawlError) {

	conn, err := net.DialTimeout("tcp", r.node, time.Second*10)
	if err != nil {
		if config.debug {
			log.Printf("%s - debug - Could not connect to %s - %v\n", s.name, r.node, err)
		}
		return nil, &crawlError{"", err}
	}

	defer conn.Close()
	if config.debug {
		log.Printf("%s - debug - Connected to remote address: %s\n", s.name, r.node)
	}

	// set a deadline for all comms to be done by. After this all i/o will error
	conn.SetDeadline(time.Now().Add(time.Second * maxTo))

	// First command to remote end needs to be a version command
	// last parameter is lastblock
	msgver, err := wire.NewMsgVersionFromConn(conn, nounce, 0)
	if err != nil {
		return nil, &crawlError{"Create NewMsgVersionFromConn", err}
	}

	err = wire.WriteMessage(conn, msgver, s.pver, s.id)
	if err != nil {
		// Log and handle the error
		return nil, &crawlError{"Write Version Message", err}
	}

	// first message received should be version
	msg, _, err := wire.ReadMessage(conn, s.pver, s.id)
	if err != nil {
		// Log and handle the error
		return nil, &crawlError{"Read message after sending Version", err}
	}

	switch msg := msg.(type) {
	case *wire.MsgVersion:
		// The message is a pointer to a MsgVersion struct.
		if config.debug {
			log.Printf("%s - debug - %s - Remote version: %v\n", s.name, r.node, msg.ProtocolVersion)
		}
		// fill the node struct with the remote details
		r.version = msg.ProtocolVersion
		r.services = msg.Services
		r.lastBlock = msg.LastBlock
		r.strVersion = msg.UserAgent
	default:
		return nil, &crawlError{"Did not receive expected Version message from remote client", errors.New("")}
	}

	// send verack command
	msgverack := wire.NewMsgVerAck()

	err = wire.WriteMessage(conn, msgverack, s.pver, s.id)
	if err != nil {
		return nil, &crawlError{"writing message VerAck", err}
	}

	// second message received should be verack
	msg, _, err = wire.ReadMessage(conn, s.pver, s.id)
	if err != nil {
		return nil, &crawlError{"reading expected Ver Ack from remote client", err}
	}

	switch msg.(type) {
	case *wire.MsgVerAck:
		if config.debug {
			log.Printf("%s - debug - %s - received Version Ack\n", s.name, r.node)
		}
	default:
		return nil, &crawlError{"Did not receive expected Ver Ack message from remote client", errors.New("")}
	}

	// if we get this far and if the seeder is full then don't ask for addresses. This will reduce bandwith usage while still
	// confirming that we can connect to the remote node
	if len(s.theList) > s.maxSize {
		return nil, nil
	}
	// send getaddr command
	msgGetAddr := wire.NewMsgGetAddr()

	err = wire.WriteMessage(conn, msgGetAddr, s.pver, s.id)
	if err != nil {
		return nil, &crawlError{"writing Addr message to remote client", err}
	}

	c := 0
	dowhile := true
	for dowhile == true {

		// Using the Bitcoin lib for the some networks means it does not understand some
		// of the commands and will error. We can ignore these as we are only
		// interested in the addr message and its content.
		msgaddr, _, _ := wire.ReadMessage(conn, s.pver, s.id)
		if msgaddr != nil {
			switch msg := msgaddr.(type) {
			case *wire.MsgAddr:
				// received the addr message so return the result
				if config.debug {
					log.Printf("%s - debug - %s - received valid addr message\n", s.name, r.node)
				}
				dowhile = false
				return msg.AddrList, nil
			default:
				if config.debug {
					log.Printf("%s - debug - %s - ignoring message - %v\n", s.name, r.node, msg.Command())
				}
			}
		}
		// if we get more than 25 messages before the addr we asked for then give up on this client
		if c++; c >= 25 {
			dowhile = false
		}
	}

	// received too many messages before requested Addr
	return nil, &crawlError{"message loop - did not receive remote addresses in first 25 messages from remote client", errors.New("")}
}