Exemple #1
0
// PushGetHeadersMsg sends a getblocks message for the provided block locator
// and stop hash.  It will ignore back-to-back duplicate requests.
func (p *peer) PushGetHeadersMsg(locator btcchain.BlockLocator) error {
	// Extract the begin hash from the block locator, if one was specified,
	// to use for filtering duplicate getblocks requests.
	// request.
	var beginHash *btcwire.ShaHash
	if len(locator) > 0 {
		beginHash = locator[0]
	}

	// Filter duplicate getblocks requests.
	if p.prevGetBlocksBegin != nil &&
		beginHash != nil &&
		beginHash.IsEqual(p.prevGetBlocksBegin) {

		peerLog.Tracef("PEER: Filtering duplicate [getblocks] with begin "+
			"hash %v", beginHash)
		return nil
	}

	// Construct the getheaders request and queue it to be sent.
	msg := btcwire.NewMsgGetHeaders()
	for _, hash := range locator {
		err := msg.AddBlockLocatorHash(hash)
		if err != nil {
			return err
		}
	}
	p.QueueMessage(msg, nil)

	// Update the previous getblocks request information for filtering
	// duplicates.
	p.prevGetBlocksBegin = beginHash
	return nil
}
Exemple #2
0
// TestGetHeaders tests the MsgGetHeader API.
func TestGetHeaders(t *testing.T) {
	pver := btcwire.ProtocolVersion

	// Block 99500 hash.
	hashStr := "000000000002e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0"
	locatorHash, err := btcwire.NewShaHashFromStr(hashStr)
	if err != nil {
		t.Errorf("NewShaHashFromStr: %v", err)
	}

	// Ensure the command is expected value.
	wantCmd := "getheaders"
	msg := btcwire.NewMsgGetHeaders()
	if cmd := msg.Command(); cmd != wantCmd {
		t.Errorf("NewMsgGetHeaders: wrong command - got %v want %v",
			cmd, wantCmd)
	}

	// Ensure max payload is expected value for latest protocol version.
	// Protocol version 4 bytes + num hashes (varInt) + max block locator
	// hashes + hash stop.
	wantPayload := uint32(16045)
	maxPayload := msg.MaxPayloadLength(pver)
	if maxPayload != wantPayload {
		t.Errorf("MaxPayloadLength: wrong max payload length for "+
			"protocol version %d - got %v, want %v", pver,
			maxPayload, wantPayload)
	}

	// Ensure block locator hashes are added properly.
	err = msg.AddBlockLocatorHash(locatorHash)
	if err != nil {
		t.Errorf("AddBlockLocatorHash: %v", err)
	}
	if msg.BlockLocatorHashes[0] != locatorHash {
		t.Errorf("AddBlockLocatorHash: wrong block locator added - "+
			"got %v, want %v",
			spew.Sprint(msg.BlockLocatorHashes[0]),
			spew.Sprint(locatorHash))
	}

	// Ensure adding more than the max allowed block locator hashes per
	// message returns an error.
	for i := 0; i < btcwire.MaxBlockLocatorsPerMsg; i++ {
		err = msg.AddBlockLocatorHash(locatorHash)
	}
	if err == nil {
		t.Errorf("AddBlockLocatorHash: expected error on too many " +
			"block locator hashes not received")
	}

	return
}
Exemple #3
0
// TestGetHeadersWire tests the MsgGetHeaders wire encode and decode for various
// numbers of block locator hashes and protocol versions.
func TestGetHeadersWire(t *testing.T) {
	// Set protocol inside getheaders message.
	pver := uint32(60002)

	// Block 99499 hash.
	hashStr := "2710f40c87ec93d010a6fd95f42c59a2cbacc60b18cf6b7957535"
	hashLocator, err := btcwire.NewShaHashFromStr(hashStr)
	if err != nil {
		t.Errorf("NewShaHashFromStr: %v", err)
	}

	// Block 99500 hash.
	hashStr = "2e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0"
	hashLocator2, err := btcwire.NewShaHashFromStr(hashStr)
	if err != nil {
		t.Errorf("NewShaHashFromStr: %v", err)
	}

	// Block 100000 hash.
	hashStr = "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
	hashStop, err := btcwire.NewShaHashFromStr(hashStr)
	if err != nil {
		t.Errorf("NewShaHashFromStr: %v", err)
	}

	// MsgGetHeaders message with no block locators or stop hash.
	NoLocators := btcwire.NewMsgGetHeaders()
	NoLocators.ProtocolVersion = pver
	NoLocatorsEncoded := []byte{
		0x62, 0xea, 0x00, 0x00, // Protocol version 60002
		0x00, // Varint for number of block locator hashes
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Hash stop
	}

	// MsgGetHeaders message with multiple block locators and a stop hash.
	MultiLocators := btcwire.NewMsgGetHeaders()
	MultiLocators.ProtocolVersion = pver
	MultiLocators.HashStop = *hashStop
	MultiLocators.AddBlockLocatorHash(hashLocator2)
	MultiLocators.AddBlockLocatorHash(hashLocator)
	MultiLocatorsEncoded := []byte{
		0x62, 0xea, 0x00, 0x00, // Protocol version 60002
		0x02, // Varint for number of block locator hashes
		0xe0, 0xde, 0x06, 0x44, 0x68, 0x13, 0x2c, 0x63,
		0xd2, 0x20, 0xcc, 0x69, 0x12, 0x83, 0xcb, 0x65,
		0xbc, 0xaa, 0xe4, 0x79, 0x94, 0xef, 0x9e, 0x7b,
		0xad, 0xe7, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // Block 99500 hash
		0x35, 0x75, 0x95, 0xb7, 0xf6, 0x8c, 0xb1, 0x60,
		0xcc, 0xba, 0x2c, 0x9a, 0xc5, 0x42, 0x5f, 0xd9,
		0x6f, 0x0a, 0x01, 0x3d, 0xc9, 0x7e, 0xc8, 0x40,
		0x0f, 0x71, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // Block 99499 hash
		0x06, 0xe5, 0x33, 0xfd, 0x1a, 0xda, 0x86, 0x39,
		0x1f, 0x3f, 0x6c, 0x34, 0x32, 0x04, 0xb0, 0xd2,
		0x78, 0xd4, 0xaa, 0xec, 0x1c, 0x0b, 0x20, 0xaa,
		0x27, 0xba, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, // Hash stop
	}

	tests := []struct {
		in   *btcwire.MsgGetHeaders // Message to encode
		out  *btcwire.MsgGetHeaders // Expected decoded message
		buf  []byte                 // Wire encoding
		pver uint32                 // Protocol version for wire encoding
	}{
		// Latest protocol version with no block locators.
		{
			NoLocators,
			NoLocators,
			NoLocatorsEncoded,
			btcwire.ProtocolVersion,
		},

		// Latest protocol version with multiple block locators.
		{
			MultiLocators,
			MultiLocators,
			MultiLocatorsEncoded,
			btcwire.ProtocolVersion,
		},

		// Protocol version BIP0035Version with no block locators.
		{
			NoLocators,
			NoLocators,
			NoLocatorsEncoded,
			btcwire.BIP0035Version,
		},

		// Protocol version BIP0035Version with multiple block locators.
		{
			MultiLocators,
			MultiLocators,
			MultiLocatorsEncoded,
			btcwire.BIP0035Version,
		},

		// Protocol version BIP0031Version with no block locators.
		{
			NoLocators,
			NoLocators,
			NoLocatorsEncoded,
			btcwire.BIP0031Version,
		},

		// Protocol version BIP0031Versionwith multiple block locators.
		{
			MultiLocators,
			MultiLocators,
			MultiLocatorsEncoded,
			btcwire.BIP0031Version,
		},

		// Protocol version NetAddressTimeVersion with no block locators.
		{
			NoLocators,
			NoLocators,
			NoLocatorsEncoded,
			btcwire.NetAddressTimeVersion,
		},

		// Protocol version NetAddressTimeVersion multiple block locators.
		{
			MultiLocators,
			MultiLocators,
			MultiLocatorsEncoded,
			btcwire.NetAddressTimeVersion,
		},

		// Protocol version MultipleAddressVersion with no block locators.
		{
			NoLocators,
			NoLocators,
			NoLocatorsEncoded,
			btcwire.MultipleAddressVersion,
		},

		// Protocol version MultipleAddressVersion multiple block locators.
		{
			MultiLocators,
			MultiLocators,
			MultiLocatorsEncoded,
			btcwire.MultipleAddressVersion,
		},
	}

	t.Logf("Running %d tests", len(tests))
	for i, test := range tests {
		// Encode the message to wire format.
		var buf bytes.Buffer
		err := test.in.BtcEncode(&buf, test.pver)
		if err != nil {
			t.Errorf("BtcEncode #%d error %v", i, err)
			continue
		}
		if !bytes.Equal(buf.Bytes(), test.buf) {
			t.Errorf("BtcEncode #%d\n got: %s want: %s", i,
				spew.Sdump(buf.Bytes()), spew.Sdump(test.buf))
			continue
		}

		// Decode the message from wire format.
		var msg btcwire.MsgGetHeaders
		rbuf := bytes.NewBuffer(test.buf)
		err = msg.BtcDecode(rbuf, test.pver)
		if err != nil {
			t.Errorf("BtcDecode #%d error %v", i, err)
			continue
		}
		if !reflect.DeepEqual(&msg, test.out) {
			t.Errorf("BtcDecode #%d\n got: %s want: %s", i,
				spew.Sdump(&msg), spew.Sdump(test.out))
			continue
		}
	}
}
// TestGetHeadersWireErrors performs negative tests against wire encode and
// decode of MsgGetHeaders to confirm error paths work correctly.
func TestGetHeadersWireErrors(t *testing.T) {
	// Set protocol inside getheaders message.  Use protocol version 60002
	// specifically here instead of the latest because the test data is
	// using bytes encoded with that protocol version.
	pver := uint32(60002)
	btcwireErr := &btcwire.MessageError{}

	// Block 99499 hash.
	hashStr := "2710f40c87ec93d010a6fd95f42c59a2cbacc60b18cf6b7957535"
	hashLocator, err := btcwire.NewShaHashFromStr(hashStr)
	if err != nil {
		t.Errorf("NewShaHashFromStr: %v", err)
	}

	// Block 99500 hash.
	hashStr = "2e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0"
	hashLocator2, err := btcwire.NewShaHashFromStr(hashStr)
	if err != nil {
		t.Errorf("NewShaHashFromStr: %v", err)
	}

	// Block 100000 hash.
	hashStr = "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
	hashStop, err := btcwire.NewShaHashFromStr(hashStr)
	if err != nil {
		t.Errorf("NewShaHashFromStr: %v", err)
	}

	// MsgGetHeaders message with multiple block locators and a stop hash.
	baseGetHeaders := btcwire.NewMsgGetHeaders()
	baseGetHeaders.ProtocolVersion = pver
	baseGetHeaders.HashStop = *hashStop
	baseGetHeaders.AddBlockLocatorHash(hashLocator2)
	baseGetHeaders.AddBlockLocatorHash(hashLocator)
	baseGetHeadersEncoded := []byte{
		0x62, 0xea, 0x00, 0x00, // Protocol version 60002
		0x02, // Varint for number of block locator hashes
		0xe0, 0xde, 0x06, 0x44, 0x68, 0x13, 0x2c, 0x63,
		0xd2, 0x20, 0xcc, 0x69, 0x12, 0x83, 0xcb, 0x65,
		0xbc, 0xaa, 0xe4, 0x79, 0x94, 0xef, 0x9e, 0x7b,
		0xad, 0xe7, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // Block 99500 hash
		0x35, 0x75, 0x95, 0xb7, 0xf6, 0x8c, 0xb1, 0x60,
		0xcc, 0xba, 0x2c, 0x9a, 0xc5, 0x42, 0x5f, 0xd9,
		0x6f, 0x0a, 0x01, 0x3d, 0xc9, 0x7e, 0xc8, 0x40,
		0x0f, 0x71, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, // Block 99499 hash
		0x06, 0xe5, 0x33, 0xfd, 0x1a, 0xda, 0x86, 0x39,
		0x1f, 0x3f, 0x6c, 0x34, 0x32, 0x04, 0xb0, 0xd2,
		0x78, 0xd4, 0xaa, 0xec, 0x1c, 0x0b, 0x20, 0xaa,
		0x27, 0xba, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, // Hash stop
	}

	// Message that forces an error by having more than the max allowed
	// block locator hashes.
	maxGetHeaders := btcwire.NewMsgGetHeaders()
	for i := 0; i < btcwire.MaxBlockLocatorsPerMsg; i++ {
		maxGetHeaders.AddBlockLocatorHash(&btcwire.GenesisHash)
	}
	maxGetHeaders.BlockLocatorHashes = append(maxGetHeaders.BlockLocatorHashes,
		&btcwire.GenesisHash)
	//maxGetHeaders.InvList = append(maxGetData.InvList, iv)
	maxGetHeadersEncoded := []byte{
		0x62, 0xea, 0x00, 0x00, // Protocol version 60002
		0xfd, 0xf5, 0x01, // Varint for number of block loc hashes (501)
	}

	tests := []struct {
		in       *btcwire.MsgGetHeaders // Value to encode
		buf      []byte                 // Wire encoding
		pver     uint32                 // Protocol version for wire encoding
		max      int                    // Max size of fixed buffer to induce errors
		writeErr error                  // Expected write error
		readErr  error                  // Expected read error
	}{
		// Force error in protocol version.
		{baseGetHeaders, baseGetHeadersEncoded, pver, 0, io.ErrShortWrite, io.EOF},
		// Force error in block locator hash count.
		{baseGetHeaders, baseGetHeadersEncoded, pver, 4, io.ErrShortWrite, io.EOF},
		// Force error in block locator hashes.
		{baseGetHeaders, baseGetHeadersEncoded, pver, 5, io.ErrShortWrite, io.EOF},
		// Force error in stop hash.
		{baseGetHeaders, baseGetHeadersEncoded, pver, 69, io.ErrShortWrite, io.EOF},
		// Force error with greater than max block locator hashes.
		{maxGetHeaders, maxGetHeadersEncoded, pver, 7, btcwireErr, btcwireErr},
	}

	t.Logf("Running %d tests", len(tests))
	for i, test := range tests {
		// Encode to wire format.
		w := newFixedWriter(test.max)
		err := test.in.BtcEncode(w, test.pver)
		if reflect.TypeOf(err) != reflect.TypeOf(test.writeErr) {
			t.Errorf("BtcEncode #%d wrong error got: %v, want: %v",
				i, err, test.writeErr)
			continue
		}

		// For errors which are not of type btcwire.MessageError, check
		// them for equality.
		if _, ok := err.(*btcwire.MessageError); !ok {
			if err != test.writeErr {
				t.Errorf("BtcEncode #%d wrong error got: %v, "+
					"want: %v", i, err, test.writeErr)
				continue
			}
		}

		// Decode from wire format.
		var msg btcwire.MsgGetHeaders
		r := newFixedReader(test.max, test.buf)
		err = msg.BtcDecode(r, test.pver)
		if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
			t.Errorf("BtcDecode #%d wrong error got: %v, want: %v",
				i, err, test.readErr)
			continue
		}

		// For errors which are not of type btcwire.MessageError, check
		// them for equality.
		if _, ok := err.(*btcwire.MessageError); !ok {
			if err != test.readErr {
				t.Errorf("BtcDecode #%d wrong error got: %v, "+
					"want: %v", i, err, test.readErr)
				continue
			}
		}
	}
}
Exemple #5
0
// TestMessage tests the Read/WriteMessage API.
func TestMessage(t *testing.T) {
	pver := btcwire.ProtocolVersion

	// Create the various types of messages to test.

	// MsgVersion.
	addrYou := &net.TCPAddr{IP: net.ParseIP("192.168.0.1"), Port: 8333}
	you, err := btcwire.NewNetAddress(addrYou, btcwire.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 := btcwire.NewNetAddress(addrMe, btcwire.SFNodeNetwork)
	if err != nil {
		t.Errorf("NewNetAddress: %v", err)
	}
	me.Timestamp = time.Time{} // Version message has zero value timestamp.
	msgVersion := btcwire.NewMsgVersion(me, you, 123123, "/test:0.0.1/", 0)

	msgVerack := btcwire.NewMsgVerAck()
	msgGetAddr := btcwire.NewMsgGetAddr()
	msgAddr := btcwire.NewMsgAddr()
	msgGetBlocks := btcwire.NewMsgGetBlocks(&btcwire.ShaHash{})
	msgBlock := &blockOne
	msgInv := btcwire.NewMsgInv()
	msgGetData := btcwire.NewMsgGetData()
	msgNotFound := btcwire.NewMsgNotFound()
	msgTx := btcwire.NewMsgTx()
	msgPing := btcwire.NewMsgPing(123123)
	msgPong := btcwire.NewMsgPong(123123)
	msgGetHeaders := btcwire.NewMsgGetHeaders()
	msgHeaders := btcwire.NewMsgHeaders()
	msgAlert := btcwire.NewMsgAlert("payload", "signature")
	msgMemPool := btcwire.NewMsgMemPool()

	tests := []struct {
		in     btcwire.Message    // Value to encode
		out    btcwire.Message    // Expected decoded value
		pver   uint32             // Protocol version for wire encoding
		btcnet btcwire.BitcoinNet // Network to use for wire encoding
	}{
		{msgVersion, msgVersion, pver, btcwire.MainNet},
		{msgVerack, msgVerack, pver, btcwire.MainNet},
		{msgGetAddr, msgGetAddr, pver, btcwire.MainNet},
		{msgAddr, msgAddr, pver, btcwire.MainNet},
		{msgGetBlocks, msgGetBlocks, pver, btcwire.MainNet},
		{msgBlock, msgBlock, pver, btcwire.MainNet},
		{msgInv, msgInv, pver, btcwire.MainNet},
		{msgGetData, msgGetData, pver, btcwire.MainNet},
		{msgNotFound, msgNotFound, pver, btcwire.MainNet},
		{msgTx, msgTx, pver, btcwire.MainNet},
		{msgPing, msgPing, pver, btcwire.MainNet},
		{msgPong, msgPong, pver, btcwire.MainNet},
		{msgGetHeaders, msgGetHeaders, pver, btcwire.MainNet},
		{msgHeaders, msgHeaders, pver, btcwire.MainNet},
		{msgAlert, msgAlert, pver, btcwire.MainNet},
		{msgMemPool, msgMemPool, pver, btcwire.MainNet},
	}

	t.Logf("Running %d tests", len(tests))
	for i, test := range tests {
		// Encode to wire format.
		var buf bytes.Buffer
		err := btcwire.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.NewBuffer(buf.Bytes())
		msg, _, err := btcwire.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 #6
0
// handleHeadersMsg is invoked when a peer receives a headers bitcoin
// message.
func (b *blockManager) handleHeadersMsg(bmsg *headersMsg) {
	msg := bmsg.headers

	nheaders := len(msg.Headers)
	if nheaders == 0 {
		bmgrLog.Infof("Received %v block headers: Fetching blocks",
			len(b.headerPool))
		b.fetchHeaderBlocks()
		return
	}
	var blockhash btcwire.ShaHash

	if b.latestCheckpoint == nil {
		b.latestCheckpoint = b.blockChain.LatestCheckpoint()
	}

	for hdridx := range msg.Headers {
		blockhash, _ = msg.Headers[hdridx].BlockSha()
		var headerst headerstr
		headerst.header = msg.Headers[hdridx]
		headerst.sha = blockhash
		prev, ok := b.headerPool[headerst.header.PrevBlock]
		if ok {
			if prev.next == nil {
				prev.next = &headerst
			} else {
				bmgrLog.Infof("two children of the same block ??? %v %v %v", prev.sha, prev.next.sha, blockhash)
			}
			headerst.height = prev.height + 1
		} else if headerst.header.PrevBlock.IsEqual(activeNetParams.genesisHash) {
			ok = true
			headerst.height = 1
			b.startBlock = &headerst.sha
		}
		if int64(headerst.height) == b.latestCheckpoint.Height {
			if headerst.sha.IsEqual(b.latestCheckpoint.Hash) {
				// we can trust this header first download
				// TODO flag this?
			} else {
				// XXX marker does not match, must throw
				// away headers !?!?!
				// XXX dont trust peer?
			}
		}
		if ok {
			b.headerPool[blockhash] = &headerst
			b.lastBlock = &blockhash
		} else {
			bmgrLog.Infof("found orphan block %v", blockhash)
			b.headerOrphan[headerst.header.PrevBlock] = &headerst
		}
	}

	// Construct the getheaders request and queue it to be sent.
	ghmsg := btcwire.NewMsgGetHeaders()
	err := ghmsg.AddBlockLocatorHash(&blockhash)
	if err != nil {
		bmgrLog.Infof("msgheaders bad addheaders", blockhash)
		return
	}

	b.syncPeer.QueueMessage(ghmsg, nil)
}