wire: Consolidate tests into the wire pkg. (#728)

Putting the test code in the same package makes it easier for forks
since they don't have to change the import paths as much and it also
gets rid of the need for internal_test.go to bridge.

This same thing should probably be done for the majority of the code
base.
This commit is contained in:
Dave Collins 2016-08-08 11:42:54 -05:00 committed by GitHub
parent 6e644855f5
commit d406d9e52b
34 changed files with 1220 additions and 1440 deletions

View file

@ -12,7 +12,6 @@ import (
"net" "net"
"os" "os"
"testing" "testing"
"time"
) )
// genesisCoinbaseTx is the coinbase transaction for the genesis blocks for // genesisCoinbaseTx is the coinbase transaction for the genesis blocks for
@ -59,65 +58,6 @@ var genesisCoinbaseTx = MsgTx{
LockTime: 0, LockTime: 0,
} }
// blockOne is the first block in the mainnet block chain.
var blockOne = MsgBlock{
Header: BlockHeader{
Version: 1,
PrevBlock: ShaHash([HashSize]byte{ // Make go vet happy.
0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f,
0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
}),
MerkleRoot: ShaHash([HashSize]byte{ // Make go vet happy.
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
0xcd, 0xb6, 0x06, 0xe8, 0x57, 0x23, 0x3e, 0x0e,
}),
Timestamp: time.Unix(0x4966bc61, 0), // 2009-01-08 20:54:25 -0600 CST
Bits: 0x1d00ffff, // 486604799
Nonce: 0x9962e301, // 2573394689
},
Transactions: []*MsgTx{
{
Version: 1,
TxIn: []*TxIn{
{
PreviousOutPoint: OutPoint{
Hash: ShaHash{},
Index: 0xffffffff,
},
SignatureScript: []byte{
0x04, 0xff, 0xff, 0x00, 0x1d, 0x01, 0x04,
},
Sequence: 0xffffffff,
},
},
TxOut: []*TxOut{
{
Value: 0x12a05f200,
PkScript: []byte{
0x41, // OP_DATA_65
0x04, 0x96, 0xb5, 0x38, 0xe8, 0x53, 0x51, 0x9c,
0x72, 0x6a, 0x2c, 0x91, 0xe6, 0x1e, 0xc1, 0x16,
0x00, 0xae, 0x13, 0x90, 0x81, 0x3a, 0x62, 0x7c,
0x66, 0xfb, 0x8b, 0xe7, 0x94, 0x7b, 0xe6, 0x3c,
0x52, 0xda, 0x75, 0x89, 0x37, 0x95, 0x15, 0xd4,
0xe0, 0xa6, 0x04, 0xf8, 0x14, 0x17, 0x81, 0xe6,
0x22, 0x94, 0x72, 0x11, 0x66, 0xbf, 0x62, 0x1e,
0x73, 0xa8, 0x2c, 0xbf, 0x23, 0x42, 0xc8, 0x58,
0xee, // 65-byte signature
0xac, // OP_CHECKSIG
},
},
},
LockTime: 0,
},
},
}
// BenchmarkWriteVarInt1 performs a benchmark on how long it takes to write // BenchmarkWriteVarInt1 performs a benchmark on how long it takes to write
// a single byte variable length integer. // a single byte variable length integer.
func BenchmarkWriteVarInt1(b *testing.B) { func BenchmarkWriteVarInt1(b *testing.B) {

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -10,13 +10,12 @@ import (
"testing" "testing"
"time" "time"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestBlockHeader tests the BlockHeader API. // TestBlockHeader tests the BlockHeader API.
func TestBlockHeader(t *testing.T) { func TestBlockHeader(t *testing.T) {
nonce64, err := wire.RandomUint64() nonce64, err := RandomUint64()
if err != nil { if err != nil {
t.Errorf("RandomUint64: Error generating nonce: %v", err) t.Errorf("RandomUint64: Error generating nonce: %v", err)
} }
@ -25,7 +24,7 @@ func TestBlockHeader(t *testing.T) {
hash := mainNetGenesisHash hash := mainNetGenesisHash
merkleHash := mainNetGenesisMerkleRoot merkleHash := mainNetGenesisMerkleRoot
bits := uint32(0x1d00ffff) bits := uint32(0x1d00ffff)
bh := wire.NewBlockHeader(&hash, &merkleHash, bits, nonce) bh := NewBlockHeader(&hash, &merkleHash, bits, nonce)
// Ensure we get the same data back out. // Ensure we get the same data back out.
if !bh.PrevBlock.IsEqual(&hash) { if !bh.PrevBlock.IsEqual(&hash) {
@ -54,7 +53,7 @@ func TestBlockHeaderWire(t *testing.T) {
// baseBlockHdr is used in the various tests as a baseline BlockHeader. // baseBlockHdr is used in the various tests as a baseline BlockHeader.
bits := uint32(0x1d00ffff) bits := uint32(0x1d00ffff)
baseBlockHdr := &wire.BlockHeader{ baseBlockHdr := &BlockHeader{
Version: 1, Version: 1,
PrevBlock: mainNetGenesisHash, PrevBlock: mainNetGenesisHash,
MerkleRoot: mainNetGenesisMerkleRoot, MerkleRoot: mainNetGenesisMerkleRoot,
@ -80,17 +79,17 @@ func TestBlockHeaderWire(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.BlockHeader // Data to encode in *BlockHeader // Data to encode
out *wire.BlockHeader // Expected decoded data out *BlockHeader // Expected decoded data
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
baseBlockHdr, baseBlockHdr,
baseBlockHdr, baseBlockHdr,
baseBlockHdrEncoded, baseBlockHdrEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version. // Protocol version BIP0035Version.
@ -98,7 +97,7 @@ func TestBlockHeaderWire(t *testing.T) {
baseBlockHdr, baseBlockHdr,
baseBlockHdr, baseBlockHdr,
baseBlockHdrEncoded, baseBlockHdrEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version. // Protocol version BIP0031Version.
@ -106,7 +105,7 @@ func TestBlockHeaderWire(t *testing.T) {
baseBlockHdr, baseBlockHdr,
baseBlockHdr, baseBlockHdr,
baseBlockHdrEncoded, baseBlockHdrEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion. // Protocol version NetAddressTimeVersion.
@ -114,7 +113,7 @@ func TestBlockHeaderWire(t *testing.T) {
baseBlockHdr, baseBlockHdr,
baseBlockHdr, baseBlockHdr,
baseBlockHdrEncoded, baseBlockHdrEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion. // Protocol version MultipleAddressVersion.
@ -122,7 +121,7 @@ func TestBlockHeaderWire(t *testing.T) {
baseBlockHdr, baseBlockHdr,
baseBlockHdr, baseBlockHdr,
baseBlockHdrEncoded, baseBlockHdrEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -130,7 +129,7 @@ func TestBlockHeaderWire(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
var buf bytes.Buffer var buf bytes.Buffer
err := wire.TstWriteBlockHeader(&buf, test.pver, test.in) err := writeBlockHeader(&buf, test.pver, test.in)
if err != nil { if err != nil {
t.Errorf("writeBlockHeader #%d error %v", i, err) t.Errorf("writeBlockHeader #%d error %v", i, err)
continue continue
@ -154,9 +153,9 @@ func TestBlockHeaderWire(t *testing.T) {
} }
// Decode the block header from wire format. // Decode the block header from wire format.
var bh wire.BlockHeader var bh BlockHeader
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = wire.TstReadBlockHeader(rbuf, test.pver, &bh) err = readBlockHeader(rbuf, test.pver, &bh)
if err != nil { if err != nil {
t.Errorf("readBlockHeader #%d error %v", i, err) t.Errorf("readBlockHeader #%d error %v", i, err)
continue continue
@ -187,7 +186,7 @@ func TestBlockHeaderSerialize(t *testing.T) {
// baseBlockHdr is used in the various tests as a baseline BlockHeader. // baseBlockHdr is used in the various tests as a baseline BlockHeader.
bits := uint32(0x1d00ffff) bits := uint32(0x1d00ffff)
baseBlockHdr := &wire.BlockHeader{ baseBlockHdr := &BlockHeader{
Version: 1, Version: 1,
PrevBlock: mainNetGenesisHash, PrevBlock: mainNetGenesisHash,
MerkleRoot: mainNetGenesisMerkleRoot, MerkleRoot: mainNetGenesisMerkleRoot,
@ -213,9 +212,9 @@ func TestBlockHeaderSerialize(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.BlockHeader // Data to encode in *BlockHeader // Data to encode
out *wire.BlockHeader // Expected decoded data out *BlockHeader // Expected decoded data
buf []byte // Serialized data buf []byte // Serialized data
}{ }{
{ {
baseBlockHdr, baseBlockHdr,
@ -240,7 +239,7 @@ func TestBlockHeaderSerialize(t *testing.T) {
} }
// Deserialize the block header. // Deserialize the block header.
var bh wire.BlockHeader var bh BlockHeader
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = bh.Deserialize(rbuf) err = bh.Deserialize(rbuf)
if err != nil { if err != nil {

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -12,13 +12,12 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// mainNetGenesisHash is the hash of the first block in the block chain for the // mainNetGenesisHash is the hash of the first block in the block chain for the
// main network (genesis block). // main network (genesis block).
var mainNetGenesisHash = wire.ShaHash([wire.HashSize]byte{ // Make go vet happy. var mainNetGenesisHash = ShaHash([HashSize]byte{ // Make go vet happy.
0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72, 0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f, 0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f,
0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c, 0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
@ -27,7 +26,7 @@ var mainNetGenesisHash = wire.ShaHash([wire.HashSize]byte{ // Make go vet happy.
// mainNetGenesisMerkleRoot is the hash of the first transaction in the genesis // mainNetGenesisMerkleRoot is the hash of the first transaction in the genesis
// block for the main network. // block for the main network.
var mainNetGenesisMerkleRoot = wire.ShaHash([wire.HashSize]byte{ // Make go vet happy. var mainNetGenesisMerkleRoot = ShaHash([HashSize]byte{ // Make go vet happy.
0x3b, 0xa3, 0xed, 0xfd, 0x7a, 0x7b, 0x12, 0xb2, 0x3b, 0xa3, 0xed, 0xfd, 0x7a, 0x7b, 0x12, 0xb2,
0x7a, 0xc7, 0x2c, 0x3e, 0x67, 0x76, 0x8f, 0x61, 0x7a, 0xc7, 0x2c, 0x3e, 0x67, 0x76, 0x8f, 0x61,
0x7f, 0xc8, 0x1b, 0xc3, 0x88, 0x8a, 0x51, 0x32, 0x7f, 0xc8, 0x1b, 0xc3, 0x88, 0x8a, 0x51, 0x32,
@ -84,7 +83,7 @@ func TestElementWire(t *testing.T) {
[]byte{0x01, 0x02, 0x03, 0x04}, []byte{0x01, 0x02, 0x03, 0x04},
}, },
{ {
[wire.CommandSize]byte{ [CommandSize]byte{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x09, 0x0a, 0x0b, 0x0c,
}, },
@ -104,7 +103,7 @@ func TestElementWire(t *testing.T) {
}, },
}, },
{ {
(*wire.ShaHash)(&[wire.HashSize]byte{ // Make go vet happy. (*ShaHash)(&[HashSize]byte{ // Make go vet happy.
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
@ -118,15 +117,15 @@ func TestElementWire(t *testing.T) {
}, },
}, },
{ {
wire.ServiceFlag(wire.SFNodeNetwork), ServiceFlag(SFNodeNetwork),
[]byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
}, },
{ {
wire.InvType(wire.InvTypeTx), InvType(InvTypeTx),
[]byte{0x01, 0x00, 0x00, 0x00}, []byte{0x01, 0x00, 0x00, 0x00},
}, },
{ {
wire.BitcoinNet(wire.MainNet), BitcoinNet(MainNet),
[]byte{0xf9, 0xbe, 0xb4, 0xd9}, []byte{0xf9, 0xbe, 0xb4, 0xd9},
}, },
// Type not supported by the "fast" path and requires reflection. // Type not supported by the "fast" path and requires reflection.
@ -140,7 +139,7 @@ func TestElementWire(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Write to wire format. // Write to wire format.
var buf bytes.Buffer var buf bytes.Buffer
err := wire.TstWriteElement(&buf, test.in) err := writeElement(&buf, test.in)
if err != nil { if err != nil {
t.Errorf("writeElement #%d error %v", i, err) t.Errorf("writeElement #%d error %v", i, err)
continue continue
@ -157,7 +156,7 @@ func TestElementWire(t *testing.T) {
if reflect.ValueOf(test.in).Kind() != reflect.Ptr { if reflect.ValueOf(test.in).Kind() != reflect.Ptr {
val = reflect.New(reflect.TypeOf(test.in)).Interface() val = reflect.New(reflect.TypeOf(test.in)).Interface()
} }
err = wire.TstReadElement(rbuf, val) err = readElement(rbuf, val)
if err != nil { if err != nil {
t.Errorf("readElement #%d error %v", i, err) t.Errorf("readElement #%d error %v", i, err)
continue continue
@ -189,7 +188,7 @@ func TestElementWireErrors(t *testing.T) {
{true, 0, io.ErrShortWrite, io.EOF}, {true, 0, io.ErrShortWrite, io.EOF},
{[4]byte{0x01, 0x02, 0x03, 0x04}, 0, io.ErrShortWrite, io.EOF}, {[4]byte{0x01, 0x02, 0x03, 0x04}, 0, io.ErrShortWrite, io.EOF},
{ {
[wire.CommandSize]byte{ [CommandSize]byte{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x09, 0x0a, 0x0b, 0x0c,
}, },
@ -203,7 +202,7 @@ func TestElementWireErrors(t *testing.T) {
0, io.ErrShortWrite, io.EOF, 0, io.ErrShortWrite, io.EOF,
}, },
{ {
(*wire.ShaHash)(&[wire.HashSize]byte{ // Make go vet happy. (*ShaHash)(&[HashSize]byte{ // Make go vet happy.
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
@ -211,16 +210,16 @@ func TestElementWireErrors(t *testing.T) {
}), }),
0, io.ErrShortWrite, io.EOF, 0, io.ErrShortWrite, io.EOF,
}, },
{wire.ServiceFlag(wire.SFNodeNetwork), 0, io.ErrShortWrite, io.EOF}, {ServiceFlag(SFNodeNetwork), 0, io.ErrShortWrite, io.EOF},
{wire.InvType(wire.InvTypeTx), 0, io.ErrShortWrite, io.EOF}, {InvType(InvTypeTx), 0, io.ErrShortWrite, io.EOF},
{wire.BitcoinNet(wire.MainNet), 0, io.ErrShortWrite, io.EOF}, {BitcoinNet(MainNet), 0, io.ErrShortWrite, io.EOF},
} }
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
w := newFixedWriter(test.max) w := newFixedWriter(test.max)
err := wire.TstWriteElement(w, test.in) err := writeElement(w, test.in)
if err != test.writeErr { if err != test.writeErr {
t.Errorf("writeElement #%d wrong error got: %v, want: %v", t.Errorf("writeElement #%d wrong error got: %v, want: %v",
i, err, test.writeErr) i, err, test.writeErr)
@ -233,7 +232,7 @@ func TestElementWireErrors(t *testing.T) {
if reflect.ValueOf(test.in).Kind() != reflect.Ptr { if reflect.ValueOf(test.in).Kind() != reflect.Ptr {
val = reflect.New(reflect.TypeOf(test.in)).Interface() val = reflect.New(reflect.TypeOf(test.in)).Interface()
} }
err = wire.TstReadElement(r, val) err = readElement(r, val)
if err != test.readErr { if err != test.readErr {
t.Errorf("readElement #%d wrong error got: %v, want: %v", t.Errorf("readElement #%d wrong error got: %v, want: %v",
i, err, test.readErr) i, err, test.readErr)
@ -244,7 +243,7 @@ func TestElementWireErrors(t *testing.T) {
// TestVarIntWire tests wire encode and decode for variable length integers. // TestVarIntWire tests wire encode and decode for variable length integers.
func TestVarIntWire(t *testing.T) { func TestVarIntWire(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
tests := []struct { tests := []struct {
in uint64 // Value to encode in uint64 // Value to encode
@ -283,7 +282,7 @@ func TestVarIntWire(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
var buf bytes.Buffer var buf bytes.Buffer
err := wire.TstWriteVarInt(&buf, test.pver, test.in) err := WriteVarInt(&buf, test.pver, test.in)
if err != nil { if err != nil {
t.Errorf("WriteVarInt #%d error %v", i, err) t.Errorf("WriteVarInt #%d error %v", i, err)
continue continue
@ -296,7 +295,7 @@ func TestVarIntWire(t *testing.T) {
// Decode from wire format. // Decode from wire format.
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
val, err := wire.TstReadVarInt(rbuf, test.pver) val, err := ReadVarInt(rbuf, test.pver)
if err != nil { if err != nil {
t.Errorf("ReadVarInt #%d error %v", i, err) t.Errorf("ReadVarInt #%d error %v", i, err)
continue continue
@ -312,7 +311,7 @@ func TestVarIntWire(t *testing.T) {
// TestVarIntWireErrors performs negative tests against wire encode and decode // TestVarIntWireErrors performs negative tests against wire encode and decode
// of variable length integers to confirm error paths work correctly. // of variable length integers to confirm error paths work correctly.
func TestVarIntWireErrors(t *testing.T) { func TestVarIntWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
tests := []struct { tests := []struct {
in uint64 // Value to encode in uint64 // Value to encode
@ -336,7 +335,7 @@ func TestVarIntWireErrors(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
w := newFixedWriter(test.max) w := newFixedWriter(test.max)
err := wire.TstWriteVarInt(w, test.pver, test.in) err := WriteVarInt(w, test.pver, test.in)
if err != test.writeErr { if err != test.writeErr {
t.Errorf("WriteVarInt #%d wrong error got: %v, want: %v", t.Errorf("WriteVarInt #%d wrong error got: %v, want: %v",
i, err, test.writeErr) i, err, test.writeErr)
@ -345,7 +344,7 @@ func TestVarIntWireErrors(t *testing.T) {
// Decode from wire format. // Decode from wire format.
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
_, err = wire.TstReadVarInt(r, test.pver) _, err = ReadVarInt(r, test.pver)
if err != test.readErr { if err != test.readErr {
t.Errorf("ReadVarInt #%d wrong error got: %v, want: %v", t.Errorf("ReadVarInt #%d wrong error got: %v, want: %v",
i, err, test.readErr) i, err, test.readErr)
@ -357,7 +356,7 @@ func TestVarIntWireErrors(t *testing.T) {
// TestVarIntNonCanonical ensures variable length integers that are not encoded // TestVarIntNonCanonical ensures variable length integers that are not encoded
// canonically return the expected error. // canonically return the expected error.
func TestVarIntNonCanonical(t *testing.T) { func TestVarIntNonCanonical(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
tests := []struct { tests := []struct {
name string // Test name for easier identification name string // Test name for easier identification
@ -396,8 +395,8 @@ func TestVarIntNonCanonical(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Decode from wire format. // Decode from wire format.
rbuf := bytes.NewReader(test.in) rbuf := bytes.NewReader(test.in)
val, err := wire.TstReadVarInt(rbuf, test.pver) val, err := ReadVarInt(rbuf, test.pver)
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
t.Errorf("ReadVarInt #%d (%s) unexpected error %v", i, t.Errorf("ReadVarInt #%d (%s) unexpected error %v", i,
test.name, err) test.name, err)
continue continue
@ -436,7 +435,7 @@ func TestVarIntSerializeSize(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
serializedSize := wire.VarIntSerializeSize(test.val) serializedSize := VarIntSerializeSize(test.val)
if serializedSize != test.size { if serializedSize != test.size {
t.Errorf("VarIntSerializeSize #%d got: %d, want: %d", i, t.Errorf("VarIntSerializeSize #%d got: %d, want: %d", i,
serializedSize, test.size) serializedSize, test.size)
@ -447,7 +446,7 @@ func TestVarIntSerializeSize(t *testing.T) {
// TestVarStringWire tests wire encode and decode for variable length strings. // TestVarStringWire tests wire encode and decode for variable length strings.
func TestVarStringWire(t *testing.T) { func TestVarStringWire(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// str256 is a string that takes a 2-byte varint to encode. // str256 is a string that takes a 2-byte varint to encode.
str256 := strings.Repeat("test", 64) str256 := strings.Repeat("test", 64)
@ -471,7 +470,7 @@ func TestVarStringWire(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
var buf bytes.Buffer var buf bytes.Buffer
err := wire.WriteVarString(&buf, test.pver, test.in) err := WriteVarString(&buf, test.pver, test.in)
if err != nil { if err != nil {
t.Errorf("WriteVarString #%d error %v", i, err) t.Errorf("WriteVarString #%d error %v", i, err)
continue continue
@ -484,7 +483,7 @@ func TestVarStringWire(t *testing.T) {
// Decode from wire format. // Decode from wire format.
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
val, err := wire.ReadVarString(rbuf, test.pver) val, err := ReadVarString(rbuf, test.pver)
if err != nil { if err != nil {
t.Errorf("ReadVarString #%d error %v", i, err) t.Errorf("ReadVarString #%d error %v", i, err)
continue continue
@ -500,7 +499,7 @@ func TestVarStringWire(t *testing.T) {
// TestVarStringWireErrors performs negative tests against wire encode and // TestVarStringWireErrors performs negative tests against wire encode and
// decode of variable length strings to confirm error paths work correctly. // decode of variable length strings to confirm error paths work correctly.
func TestVarStringWireErrors(t *testing.T) { func TestVarStringWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// str256 is a string that takes a 2-byte varint to encode. // str256 is a string that takes a 2-byte varint to encode.
str256 := strings.Repeat("test", 64) str256 := strings.Repeat("test", 64)
@ -526,7 +525,7 @@ func TestVarStringWireErrors(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
w := newFixedWriter(test.max) w := newFixedWriter(test.max)
err := wire.WriteVarString(w, test.pver, test.in) err := WriteVarString(w, test.pver, test.in)
if err != test.writeErr { if err != test.writeErr {
t.Errorf("WriteVarString #%d wrong error got: %v, want: %v", t.Errorf("WriteVarString #%d wrong error got: %v, want: %v",
i, err, test.writeErr) i, err, test.writeErr)
@ -535,7 +534,7 @@ func TestVarStringWireErrors(t *testing.T) {
// Decode from wire format. // Decode from wire format.
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
_, err = wire.ReadVarString(r, test.pver) _, err = ReadVarString(r, test.pver)
if err != test.readErr { if err != test.readErr {
t.Errorf("ReadVarString #%d wrong error got: %v, want: %v", t.Errorf("ReadVarString #%d wrong error got: %v, want: %v",
i, err, test.readErr) i, err, test.readErr)
@ -549,7 +548,7 @@ func TestVarStringWireErrors(t *testing.T) {
// length are handled properly. This could otherwise potentially be used as an // length are handled properly. This could otherwise potentially be used as an
// attack vector. // attack vector.
func TestVarStringOverflowErrors(t *testing.T) { func TestVarStringOverflowErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
tests := []struct { tests := []struct {
buf []byte // Wire encoding buf []byte // Wire encoding
@ -557,16 +556,16 @@ func TestVarStringOverflowErrors(t *testing.T) {
err error // Expected error err error // Expected error
}{ }{
{[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
pver, &wire.MessageError{}}, pver, &MessageError{}},
{[]byte{0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, {[]byte{0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
pver, &wire.MessageError{}}, pver, &MessageError{}},
} }
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Decode from wire format. // Decode from wire format.
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
_, err := wire.ReadVarString(rbuf, test.pver) _, err := ReadVarString(rbuf, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) { if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
t.Errorf("ReadVarString #%d wrong error got: %v, "+ t.Errorf("ReadVarString #%d wrong error got: %v, "+
"want: %v", i, err, reflect.TypeOf(test.err)) "want: %v", i, err, reflect.TypeOf(test.err))
@ -578,7 +577,7 @@ func TestVarStringOverflowErrors(t *testing.T) {
// TestVarBytesWire tests wire encode and decode for variable length byte array. // TestVarBytesWire tests wire encode and decode for variable length byte array.
func TestVarBytesWire(t *testing.T) { func TestVarBytesWire(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// bytes256 is a byte array that takes a 2-byte varint to encode. // bytes256 is a byte array that takes a 2-byte varint to encode.
bytes256 := bytes.Repeat([]byte{0x01}, 256) bytes256 := bytes.Repeat([]byte{0x01}, 256)
@ -601,7 +600,7 @@ func TestVarBytesWire(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
var buf bytes.Buffer var buf bytes.Buffer
err := wire.TstWriteVarBytes(&buf, test.pver, test.in) err := WriteVarBytes(&buf, test.pver, test.in)
if err != nil { if err != nil {
t.Errorf("WriteVarBytes #%d error %v", i, err) t.Errorf("WriteVarBytes #%d error %v", i, err)
continue continue
@ -614,8 +613,8 @@ func TestVarBytesWire(t *testing.T) {
// Decode from wire format. // Decode from wire format.
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
val, err := wire.TstReadVarBytes(rbuf, test.pver, val, err := ReadVarBytes(rbuf, test.pver, MaxMessagePayload,
wire.MaxMessagePayload, "test payload") "test payload")
if err != nil { if err != nil {
t.Errorf("ReadVarBytes #%d error %v", i, err) t.Errorf("ReadVarBytes #%d error %v", i, err)
continue continue
@ -631,7 +630,7 @@ func TestVarBytesWire(t *testing.T) {
// TestVarBytesWireErrors performs negative tests against wire encode and // TestVarBytesWireErrors performs negative tests against wire encode and
// decode of variable length byte arrays to confirm error paths work correctly. // decode of variable length byte arrays to confirm error paths work correctly.
func TestVarBytesWireErrors(t *testing.T) { func TestVarBytesWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// bytes256 is a byte array that takes a 2-byte varint to encode. // bytes256 is a byte array that takes a 2-byte varint to encode.
bytes256 := bytes.Repeat([]byte{0x01}, 256) bytes256 := bytes.Repeat([]byte{0x01}, 256)
@ -657,7 +656,7 @@ func TestVarBytesWireErrors(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
w := newFixedWriter(test.max) w := newFixedWriter(test.max)
err := wire.TstWriteVarBytes(w, test.pver, test.in) err := WriteVarBytes(w, test.pver, test.in)
if err != test.writeErr { if err != test.writeErr {
t.Errorf("WriteVarBytes #%d wrong error got: %v, want: %v", t.Errorf("WriteVarBytes #%d wrong error got: %v, want: %v",
i, err, test.writeErr) i, err, test.writeErr)
@ -666,8 +665,8 @@ func TestVarBytesWireErrors(t *testing.T) {
// Decode from wire format. // Decode from wire format.
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
_, err = wire.TstReadVarBytes(r, test.pver, _, err = ReadVarBytes(r, test.pver, MaxMessagePayload,
wire.MaxMessagePayload, "test payload") "test payload")
if err != test.readErr { if err != test.readErr {
t.Errorf("ReadVarBytes #%d wrong error got: %v, want: %v", t.Errorf("ReadVarBytes #%d wrong error got: %v, want: %v",
i, err, test.readErr) i, err, test.readErr)
@ -681,7 +680,7 @@ func TestVarBytesWireErrors(t *testing.T) {
// length are handled properly. This could otherwise potentially be used as an // length are handled properly. This could otherwise potentially be used as an
// attack vector. // attack vector.
func TestVarBytesOverflowErrors(t *testing.T) { func TestVarBytesOverflowErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
tests := []struct { tests := []struct {
buf []byte // Wire encoding buf []byte // Wire encoding
@ -689,17 +688,17 @@ func TestVarBytesOverflowErrors(t *testing.T) {
err error // Expected error err error // Expected error
}{ }{
{[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
pver, &wire.MessageError{}}, pver, &MessageError{}},
{[]byte{0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, {[]byte{0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
pver, &wire.MessageError{}}, pver, &MessageError{}},
} }
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Decode from wire format. // Decode from wire format.
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
_, err := wire.TstReadVarBytes(rbuf, test.pver, _, err := ReadVarBytes(rbuf, test.pver, MaxMessagePayload,
wire.MaxMessagePayload, "test payload") "test payload")
if reflect.TypeOf(err) != reflect.TypeOf(test.err) { if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
t.Errorf("ReadVarBytes #%d wrong error got: %v, "+ t.Errorf("ReadVarBytes #%d wrong error got: %v, "+
"want: %v", i, err, reflect.TypeOf(test.err)) "want: %v", i, err, reflect.TypeOf(test.err))
@ -725,7 +724,7 @@ func TestRandomUint64(t *testing.T) {
numHits := 0 numHits := 0
for i := 0; i < tries; i++ { for i := 0; i < tries; i++ {
nonce, err := wire.RandomUint64() nonce, err := RandomUint64()
if err != nil { if err != nil {
t.Errorf("RandomUint64 iteration %d failed - err %v", t.Errorf("RandomUint64 iteration %d failed - err %v",
i, err) i, err)
@ -748,7 +747,7 @@ func TestRandomUint64(t *testing.T) {
func TestRandomUint64Errors(t *testing.T) { func TestRandomUint64Errors(t *testing.T) {
// Test short reads. // Test short reads.
fr := &fakeRandReader{n: 2, err: io.EOF} fr := &fakeRandReader{n: 2, err: io.EOF}
nonce, err := wire.TstRandomUint64(fr) nonce, err := randomUint64(fr)
if err != io.ErrUnexpectedEOF { if err != io.ErrUnexpectedEOF {
t.Errorf("Error not expected value of %v [%v]", t.Errorf("Error not expected value of %v [%v]",
io.ErrUnexpectedEOF, err) io.ErrUnexpectedEOF, err)

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"net" "net"

View file

@ -1,17 +1,13 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import "io"
"io"
"github.com/btcsuite/btcd/wire" // fakeMessage implements the Message interface and is used to force encode
) // errors in messages.
// fakeMessage implements the wire.Message interface and is used to force
// encode errors in messages.
type fakeMessage struct { type fakeMessage struct {
command string command string
payload []byte payload []byte
@ -19,18 +15,17 @@ type fakeMessage struct {
forceLenErr bool forceLenErr bool
} }
// BtcDecode doesn't do anything. It just satisfies the wire.Message // BtcDecode doesn't do anything. It just satisfies the Message interface.
// interface.
func (msg *fakeMessage) BtcDecode(r io.Reader, pver uint32) error { func (msg *fakeMessage) BtcDecode(r io.Reader, pver uint32) error {
return nil return nil
} }
// BtcEncode writes the payload field of the fake message or forces an error // BtcEncode writes the payload field of the fake message or forces an error
// if the forceEncodeErr flag of the fake message is set. It also satisfies the // if the forceEncodeErr flag of the fake message is set. It also satisfies the
// wire.Message interface. // Message interface.
func (msg *fakeMessage) BtcEncode(w io.Writer, pver uint32) error { func (msg *fakeMessage) BtcEncode(w io.Writer, pver uint32) error {
if msg.forceEncodeErr { if msg.forceEncodeErr {
err := &wire.MessageError{ err := &MessageError{
Func: "fakeMessage.BtcEncode", Func: "fakeMessage.BtcEncode",
Description: "intentional error", Description: "intentional error",
} }
@ -42,14 +37,14 @@ func (msg *fakeMessage) BtcEncode(w io.Writer, pver uint32) error {
} }
// Command returns the command field of the fake message and satisfies the // Command returns the command field of the fake message and satisfies the
// wire.Message interface. // Message interface.
func (msg *fakeMessage) Command() string { func (msg *fakeMessage) Command() string {
return msg.command return msg.command
} }
// MaxPayloadLength returns the length of the payload field of fake message // MaxPayloadLength returns the length of the payload field of fake message
// or a smaller value if the forceLenErr flag of the fake message is set. It // or a smaller value if the forceLenErr flag of the fake message is set. It
// satisfies the wire.Message interface. // satisfies the Message interface.
func (msg *fakeMessage) MaxPayloadLength(pver uint32) uint32 { func (msg *fakeMessage) MaxPayloadLength(pver uint32) uint32 {
lenp := uint32(len(msg.payload)) lenp := uint32(len(msg.payload))
if msg.forceLenErr { if msg.forceLenErr {

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"

View file

@ -1,118 +0,0 @@
// Copyright (c) 2013-2015 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
/*
This test file is part of the wire package rather than than the wire_test
package so it can bridge access to the internals to properly test cases which
are either not possible or can't reliably be tested via the public interface.
The functions are only exported while the tests are being run.
*/
package wire
import (
"io"
)
const (
// MaxTxPerBlock makes the internal maxTxPerBlock constant available to
// the test package.
MaxTxPerBlock = maxTxPerBlock
// MaxFlagsPerMerkleBlock makes the internal maxFlagsPerMerkleBlock
// constant available to the test package.
MaxFlagsPerMerkleBlock = maxFlagsPerMerkleBlock
// MaxCountSetCancel makes the internal maxCountSetCancel constant
// available to the test package.
MaxCountSetCancel = maxCountSetCancel
// MaxCountSetSubVer makes the internal maxCountSetSubVer constant
// available to the test package.
MaxCountSetSubVer = maxCountSetSubVer
)
// TstRandomUint64 makes the internal randomUint64 function available to the
// test package.
func TstRandomUint64(r io.Reader) (uint64, error) {
return randomUint64(r)
}
// TstReadElement makes the internal readElement function available to the
// test package.
func TstReadElement(r io.Reader, element interface{}) error {
return readElement(r, element)
}
// TstWriteElement makes the internal writeElement function available to the
// test package.
func TstWriteElement(w io.Writer, element interface{}) error {
return writeElement(w, element)
}
// TstReadVarInt makes the internal ReadVarInt function available to the
// test package.
func TstReadVarInt(r io.Reader, pver uint32) (uint64, error) {
return ReadVarInt(r, pver)
}
// TstWriteVarInt makes the internal WriteVarInt function available to the
// test package.
func TstWriteVarInt(w io.Writer, pver uint32, val uint64) error {
return WriteVarInt(w, pver, val)
}
// TstReadVarBytes makes the internal ReadVarBytes function available to the
// test package.
func TstReadVarBytes(r io.Reader, pver uint32, maxAllowed uint32, fieldName string) ([]byte, error) {
return ReadVarBytes(r, pver, maxAllowed, fieldName)
}
// TstWriteVarBytes makes the internal WriteVarBytes function available to the
// test package.
func TstWriteVarBytes(w io.Writer, pver uint32, bytes []byte) error {
return WriteVarBytes(w, pver, bytes)
}
// TstReadNetAddress makes the internal readNetAddress function available to
// the test package.
func TstReadNetAddress(r io.Reader, pver uint32, na *NetAddress, ts bool) error {
return readNetAddress(r, pver, na, ts)
}
// TstWriteNetAddress makes the internal writeNetAddress function available to
// the test package.
func TstWriteNetAddress(w io.Writer, pver uint32, na *NetAddress, ts bool) error {
return writeNetAddress(w, pver, na, ts)
}
// TstMaxNetAddressPayload makes the internal maxNetAddressPayload function
// available to the test package.
func TstMaxNetAddressPayload(pver uint32) uint32 {
return maxNetAddressPayload(pver)
}
// TstReadInvVect makes the internal readInvVect function available to the test
// package.
func TstReadInvVect(r io.Reader, pver uint32, iv *InvVect) error {
return readInvVect(r, pver, iv)
}
// TstWriteInvVect makes the internal writeInvVect function available to the
// test package.
func TstWriteInvVect(w io.Writer, pver uint32, iv *InvVect) error {
return writeInvVect(w, pver, iv)
}
// TstReadBlockHeader makes the internal readBlockHeader function available to
// the test package.
func TstReadBlockHeader(r io.Reader, pver uint32, bh *BlockHeader) error {
return readBlockHeader(r, pver, bh)
}
// TstWriteBlockHeader makes the internal writeBlockHeader function available to
// the test package.
func TstWriteBlockHeader(w io.Writer, pver uint32, bh *BlockHeader) error {
return writeBlockHeader(w, pver, bh)
}

View file

@ -1,27 +1,26 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestInvVectStringer tests the stringized output for inventory vector types. // TestInvVectStringer tests the stringized output for inventory vector types.
func TestInvTypeStringer(t *testing.T) { func TestInvTypeStringer(t *testing.T) {
tests := []struct { tests := []struct {
in wire.InvType in InvType
want string want string
}{ }{
{wire.InvTypeError, "ERROR"}, {InvTypeError, "ERROR"},
{wire.InvTypeTx, "MSG_TX"}, {InvTypeTx, "MSG_TX"},
{wire.InvTypeBlock, "MSG_BLOCK"}, {InvTypeBlock, "MSG_BLOCK"},
{0xffffffff, "Unknown InvType (4294967295)"}, {0xffffffff, "Unknown InvType (4294967295)"},
} }
@ -39,11 +38,11 @@ func TestInvTypeStringer(t *testing.T) {
// TestInvVect tests the InvVect API. // TestInvVect tests the InvVect API.
func TestInvVect(t *testing.T) { func TestInvVect(t *testing.T) {
ivType := wire.InvTypeBlock ivType := InvTypeBlock
hash := wire.ShaHash{} hash := ShaHash{}
// Ensure we get the same payload and signature back out. // Ensure we get the same payload and signature back out.
iv := wire.NewInvVect(ivType, &hash) iv := NewInvVect(ivType, &hash)
if iv.Type != ivType { if iv.Type != ivType {
t.Errorf("NewInvVect: wrong type - got %v, want %v", t.Errorf("NewInvVect: wrong type - got %v, want %v",
iv.Type, ivType) iv.Type, ivType)
@ -60,15 +59,15 @@ func TestInvVect(t *testing.T) {
func TestInvVectWire(t *testing.T) { func TestInvVectWire(t *testing.T) {
// Block 203707 hash. // Block 203707 hash.
hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc" hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc"
baseHash, err := wire.NewShaHashFromStr(hashStr) baseHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// errInvVect is an inventory vector with an error. // errInvVect is an inventory vector with an error.
errInvVect := wire.InvVect{ errInvVect := InvVect{
Type: wire.InvTypeError, Type: InvTypeError,
Hash: wire.ShaHash{}, Hash: ShaHash{},
} }
// errInvVectEncoded is the wire encoded bytes of errInvVect. // errInvVectEncoded is the wire encoded bytes of errInvVect.
@ -81,8 +80,8 @@ func TestInvVectWire(t *testing.T) {
} }
// txInvVect is an inventory vector representing a transaction. // txInvVect is an inventory vector representing a transaction.
txInvVect := wire.InvVect{ txInvVect := InvVect{
Type: wire.InvTypeTx, Type: InvTypeTx,
Hash: *baseHash, Hash: *baseHash,
} }
@ -96,8 +95,8 @@ func TestInvVectWire(t *testing.T) {
} }
// blockInvVect is an inventory vector representing a block. // blockInvVect is an inventory vector representing a block.
blockInvVect := wire.InvVect{ blockInvVect := InvVect{
Type: wire.InvTypeBlock, Type: InvTypeBlock,
Hash: *baseHash, Hash: *baseHash,
} }
@ -111,17 +110,17 @@ func TestInvVectWire(t *testing.T) {
} }
tests := []struct { tests := []struct {
in wire.InvVect // NetAddress to encode in InvVect // NetAddress to encode
out wire.InvVect // Expected decoded NetAddress out InvVect // Expected decoded NetAddress
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version error inventory vector. // Latest protocol version error inventory vector.
{ {
errInvVect, errInvVect,
errInvVect, errInvVect,
errInvVectEncoded, errInvVectEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Latest protocol version tx inventory vector. // Latest protocol version tx inventory vector.
@ -129,7 +128,7 @@ func TestInvVectWire(t *testing.T) {
txInvVect, txInvVect,
txInvVect, txInvVect,
txInvVectEncoded, txInvVectEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Latest protocol version block inventory vector. // Latest protocol version block inventory vector.
@ -137,7 +136,7 @@ func TestInvVectWire(t *testing.T) {
blockInvVect, blockInvVect,
blockInvVect, blockInvVect,
blockInvVectEncoded, blockInvVectEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version error inventory vector. // Protocol version BIP0035Version error inventory vector.
@ -145,7 +144,7 @@ func TestInvVectWire(t *testing.T) {
errInvVect, errInvVect,
errInvVect, errInvVect,
errInvVectEncoded, errInvVectEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0035Version tx inventory vector. // Protocol version BIP0035Version tx inventory vector.
@ -153,7 +152,7 @@ func TestInvVectWire(t *testing.T) {
txInvVect, txInvVect,
txInvVect, txInvVect,
txInvVectEncoded, txInvVectEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0035Version block inventory vector. // Protocol version BIP0035Version block inventory vector.
@ -161,7 +160,7 @@ func TestInvVectWire(t *testing.T) {
blockInvVect, blockInvVect,
blockInvVect, blockInvVect,
blockInvVectEncoded, blockInvVectEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version error inventory vector. // Protocol version BIP0031Version error inventory vector.
@ -169,7 +168,7 @@ func TestInvVectWire(t *testing.T) {
errInvVect, errInvVect,
errInvVect, errInvVect,
errInvVectEncoded, errInvVectEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version BIP0031Version tx inventory vector. // Protocol version BIP0031Version tx inventory vector.
@ -177,7 +176,7 @@ func TestInvVectWire(t *testing.T) {
txInvVect, txInvVect,
txInvVect, txInvVect,
txInvVectEncoded, txInvVectEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version BIP0031Version block inventory vector. // Protocol version BIP0031Version block inventory vector.
@ -185,7 +184,7 @@ func TestInvVectWire(t *testing.T) {
blockInvVect, blockInvVect,
blockInvVect, blockInvVect,
blockInvVectEncoded, blockInvVectEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion error inventory vector. // Protocol version NetAddressTimeVersion error inventory vector.
@ -193,7 +192,7 @@ func TestInvVectWire(t *testing.T) {
errInvVect, errInvVect,
errInvVect, errInvVect,
errInvVectEncoded, errInvVectEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version NetAddressTimeVersion tx inventory vector. // Protocol version NetAddressTimeVersion tx inventory vector.
@ -201,7 +200,7 @@ func TestInvVectWire(t *testing.T) {
txInvVect, txInvVect,
txInvVect, txInvVect,
txInvVectEncoded, txInvVectEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version NetAddressTimeVersion block inventory vector. // Protocol version NetAddressTimeVersion block inventory vector.
@ -209,7 +208,7 @@ func TestInvVectWire(t *testing.T) {
blockInvVect, blockInvVect,
blockInvVect, blockInvVect,
blockInvVectEncoded, blockInvVectEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion error inventory vector. // Protocol version MultipleAddressVersion error inventory vector.
@ -217,7 +216,7 @@ func TestInvVectWire(t *testing.T) {
errInvVect, errInvVect,
errInvVect, errInvVect,
errInvVectEncoded, errInvVectEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
// Protocol version MultipleAddressVersion tx inventory vector. // Protocol version MultipleAddressVersion tx inventory vector.
@ -225,7 +224,7 @@ func TestInvVectWire(t *testing.T) {
txInvVect, txInvVect,
txInvVect, txInvVect,
txInvVectEncoded, txInvVectEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
// Protocol version MultipleAddressVersion block inventory vector. // Protocol version MultipleAddressVersion block inventory vector.
@ -233,7 +232,7 @@ func TestInvVectWire(t *testing.T) {
blockInvVect, blockInvVect,
blockInvVect, blockInvVect,
blockInvVectEncoded, blockInvVectEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -241,7 +240,7 @@ func TestInvVectWire(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
var buf bytes.Buffer var buf bytes.Buffer
err := wire.TstWriteInvVect(&buf, test.pver, &test.in) err := writeInvVect(&buf, test.pver, &test.in)
if err != nil { if err != nil {
t.Errorf("writeInvVect #%d error %v", i, err) t.Errorf("writeInvVect #%d error %v", i, err)
continue continue
@ -253,9 +252,9 @@ func TestInvVectWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var iv wire.InvVect var iv InvVect
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = wire.TstReadInvVect(rbuf, test.pver, &iv) err = readInvVect(rbuf, test.pver, &iv)
if err != nil { if err != nil {
t.Errorf("readInvVect #%d error %v", i, err) t.Errorf("readInvVect #%d error %v", i, err)
continue continue

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -13,13 +13,12 @@ import (
"testing" "testing"
"time" "time"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// makeHeader is a convenience function to make a message header in the form of // makeHeader is a convenience function to make a message header in the form of
// a byte slice. It is used to force errors when reading messages. // a byte slice. It is used to force errors when reading messages.
func makeHeader(btcnet wire.BitcoinNet, command string, func makeHeader(btcnet BitcoinNet, command string,
payloadLen uint32, checksum uint32) []byte { payloadLen uint32, checksum uint32) []byte {
// The length of a bitcoin message header is 24 bytes. // The length of a bitcoin message header is 24 bytes.
@ -35,82 +34,82 @@ func makeHeader(btcnet wire.BitcoinNet, command string,
// TestMessage tests the Read/WriteMessage and Read/WriteMessageN API. // TestMessage tests the Read/WriteMessage and Read/WriteMessageN API.
func TestMessage(t *testing.T) { func TestMessage(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Create the various types of messages to test. // Create the various types of messages to test.
// MsgVersion. // MsgVersion.
addrYou := &net.TCPAddr{IP: net.ParseIP("192.168.0.1"), Port: 8333} addrYou := &net.TCPAddr{IP: net.ParseIP("192.168.0.1"), Port: 8333}
you, err := wire.NewNetAddress(addrYou, wire.SFNodeNetwork) you, err := NewNetAddress(addrYou, SFNodeNetwork)
if err != nil { if err != nil {
t.Errorf("NewNetAddress: %v", err) t.Errorf("NewNetAddress: %v", err)
} }
you.Timestamp = time.Time{} // Version message has zero value timestamp. you.Timestamp = time.Time{} // Version message has zero value timestamp.
addrMe := &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8333} addrMe := &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8333}
me, err := wire.NewNetAddress(addrMe, wire.SFNodeNetwork) me, err := NewNetAddress(addrMe, SFNodeNetwork)
if err != nil { if err != nil {
t.Errorf("NewNetAddress: %v", err) t.Errorf("NewNetAddress: %v", err)
} }
me.Timestamp = time.Time{} // Version message has zero value timestamp. me.Timestamp = time.Time{} // Version message has zero value timestamp.
msgVersion := wire.NewMsgVersion(me, you, 123123, 0) msgVersion := NewMsgVersion(me, you, 123123, 0)
msgVerack := wire.NewMsgVerAck() msgVerack := NewMsgVerAck()
msgGetAddr := wire.NewMsgGetAddr() msgGetAddr := NewMsgGetAddr()
msgAddr := wire.NewMsgAddr() msgAddr := NewMsgAddr()
msgGetBlocks := wire.NewMsgGetBlocks(&wire.ShaHash{}) msgGetBlocks := NewMsgGetBlocks(&ShaHash{})
msgBlock := &blockOne msgBlock := &blockOne
msgInv := wire.NewMsgInv() msgInv := NewMsgInv()
msgGetData := wire.NewMsgGetData() msgGetData := NewMsgGetData()
msgNotFound := wire.NewMsgNotFound() msgNotFound := NewMsgNotFound()
msgTx := wire.NewMsgTx() msgTx := NewMsgTx()
msgPing := wire.NewMsgPing(123123) msgPing := NewMsgPing(123123)
msgPong := wire.NewMsgPong(123123) msgPong := NewMsgPong(123123)
msgGetHeaders := wire.NewMsgGetHeaders() msgGetHeaders := NewMsgGetHeaders()
msgHeaders := wire.NewMsgHeaders() msgHeaders := NewMsgHeaders()
msgAlert := wire.NewMsgAlert([]byte("payload"), []byte("signature")) msgAlert := NewMsgAlert([]byte("payload"), []byte("signature"))
msgMemPool := wire.NewMsgMemPool() msgMemPool := NewMsgMemPool()
msgFilterAdd := wire.NewMsgFilterAdd([]byte{0x01}) msgFilterAdd := NewMsgFilterAdd([]byte{0x01})
msgFilterClear := wire.NewMsgFilterClear() msgFilterClear := NewMsgFilterClear()
msgFilterLoad := wire.NewMsgFilterLoad([]byte{0x01}, 10, 0, wire.BloomUpdateNone) msgFilterLoad := NewMsgFilterLoad([]byte{0x01}, 10, 0, BloomUpdateNone)
bh := wire.NewBlockHeader(&wire.ShaHash{}, &wire.ShaHash{}, 0, 0) bh := NewBlockHeader(&ShaHash{}, &ShaHash{}, 0, 0)
msgMerkleBlock := wire.NewMsgMerkleBlock(bh) msgMerkleBlock := NewMsgMerkleBlock(bh)
msgReject := wire.NewMsgReject("block", wire.RejectDuplicate, "duplicate block") msgReject := NewMsgReject("block", RejectDuplicate, "duplicate block")
tests := []struct { tests := []struct {
in wire.Message // Value to encode in Message // Value to encode
out wire.Message // Expected decoded value out Message // Expected decoded value
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
btcnet wire.BitcoinNet // Network to use for wire encoding btcnet BitcoinNet // Network to use for wire encoding
bytes int // Expected num bytes read/written bytes int // Expected num bytes read/written
}{ }{
{msgVersion, msgVersion, pver, wire.MainNet, 125}, {msgVersion, msgVersion, pver, MainNet, 125},
{msgVerack, msgVerack, pver, wire.MainNet, 24}, {msgVerack, msgVerack, pver, MainNet, 24},
{msgGetAddr, msgGetAddr, pver, wire.MainNet, 24}, {msgGetAddr, msgGetAddr, pver, MainNet, 24},
{msgAddr, msgAddr, pver, wire.MainNet, 25}, {msgAddr, msgAddr, pver, MainNet, 25},
{msgGetBlocks, msgGetBlocks, pver, wire.MainNet, 61}, {msgGetBlocks, msgGetBlocks, pver, MainNet, 61},
{msgBlock, msgBlock, pver, wire.MainNet, 239}, {msgBlock, msgBlock, pver, MainNet, 239},
{msgInv, msgInv, pver, wire.MainNet, 25}, {msgInv, msgInv, pver, MainNet, 25},
{msgGetData, msgGetData, pver, wire.MainNet, 25}, {msgGetData, msgGetData, pver, MainNet, 25},
{msgNotFound, msgNotFound, pver, wire.MainNet, 25}, {msgNotFound, msgNotFound, pver, MainNet, 25},
{msgTx, msgTx, pver, wire.MainNet, 34}, {msgTx, msgTx, pver, MainNet, 34},
{msgPing, msgPing, pver, wire.MainNet, 32}, {msgPing, msgPing, pver, MainNet, 32},
{msgPong, msgPong, pver, wire.MainNet, 32}, {msgPong, msgPong, pver, MainNet, 32},
{msgGetHeaders, msgGetHeaders, pver, wire.MainNet, 61}, {msgGetHeaders, msgGetHeaders, pver, MainNet, 61},
{msgHeaders, msgHeaders, pver, wire.MainNet, 25}, {msgHeaders, msgHeaders, pver, MainNet, 25},
{msgAlert, msgAlert, pver, wire.MainNet, 42}, {msgAlert, msgAlert, pver, MainNet, 42},
{msgMemPool, msgMemPool, pver, wire.MainNet, 24}, {msgMemPool, msgMemPool, pver, MainNet, 24},
{msgFilterAdd, msgFilterAdd, pver, wire.MainNet, 26}, {msgFilterAdd, msgFilterAdd, pver, MainNet, 26},
{msgFilterClear, msgFilterClear, pver, wire.MainNet, 24}, {msgFilterClear, msgFilterClear, pver, MainNet, 24},
{msgFilterLoad, msgFilterLoad, pver, wire.MainNet, 35}, {msgFilterLoad, msgFilterLoad, pver, MainNet, 35},
{msgMerkleBlock, msgMerkleBlock, pver, wire.MainNet, 110}, {msgMerkleBlock, msgMerkleBlock, pver, MainNet, 110},
{msgReject, msgReject, pver, wire.MainNet, 79}, {msgReject, msgReject, pver, MainNet, 79},
} }
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
var buf bytes.Buffer var buf bytes.Buffer
nw, err := wire.WriteMessageN(&buf, test.in, test.pver, test.btcnet) nw, err := WriteMessageN(&buf, test.in, test.pver, test.btcnet)
if err != nil { if err != nil {
t.Errorf("WriteMessage #%d error %v", i, err) t.Errorf("WriteMessage #%d error %v", i, err)
continue continue
@ -124,7 +123,7 @@ func TestMessage(t *testing.T) {
// Decode from wire format. // Decode from wire format.
rbuf := bytes.NewReader(buf.Bytes()) rbuf := bytes.NewReader(buf.Bytes())
nr, msg, _, err := wire.ReadMessageN(rbuf, test.pver, test.btcnet) nr, msg, _, err := ReadMessageN(rbuf, test.pver, test.btcnet)
if err != nil { if err != nil {
t.Errorf("ReadMessage #%d error %v, msg %v", i, err, t.Errorf("ReadMessage #%d error %v, msg %v", i, err,
spew.Sdump(msg)) spew.Sdump(msg))
@ -149,7 +148,7 @@ func TestMessage(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
var buf bytes.Buffer var buf bytes.Buffer
err := wire.WriteMessage(&buf, test.in, test.pver, test.btcnet) err := WriteMessage(&buf, test.in, test.pver, test.btcnet)
if err != nil { if err != nil {
t.Errorf("WriteMessage #%d error %v", i, err) t.Errorf("WriteMessage #%d error %v", i, err)
continue continue
@ -157,7 +156,7 @@ func TestMessage(t *testing.T) {
// Decode from wire format. // Decode from wire format.
rbuf := bytes.NewReader(buf.Bytes()) rbuf := bytes.NewReader(buf.Bytes())
msg, _, err := wire.ReadMessage(rbuf, test.pver, test.btcnet) msg, _, err := ReadMessage(rbuf, test.pver, test.btcnet)
if err != nil { if err != nil {
t.Errorf("ReadMessage #%d error %v, msg %v", i, err, t.Errorf("ReadMessage #%d error %v, msg %v", i, err,
spew.Sdump(msg)) spew.Sdump(msg))
@ -174,12 +173,12 @@ func TestMessage(t *testing.T) {
// TestReadMessageWireErrors performs negative tests against wire decoding into // TestReadMessageWireErrors performs negative tests against wire decoding into
// concrete messages to confirm error paths work correctly. // concrete messages to confirm error paths work correctly.
func TestReadMessageWireErrors(t *testing.T) { func TestReadMessageWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
btcnet := wire.MainNet btcnet := MainNet
// Ensure message errors are as expected with no function specified. // Ensure message errors are as expected with no function specified.
wantErr := "something bad happened" wantErr := "something bad happened"
testErr := wire.MessageError{Description: wantErr} testErr := MessageError{Description: wantErr}
if testErr.Error() != wantErr { if testErr.Error() != wantErr {
t.Errorf("MessageError: wrong error - got %v, want %v", t.Errorf("MessageError: wrong error - got %v, want %v",
testErr.Error(), wantErr) testErr.Error(), wantErr)
@ -187,18 +186,18 @@ func TestReadMessageWireErrors(t *testing.T) {
// Ensure message errors are as expected with a function specified. // Ensure message errors are as expected with a function specified.
wantFunc := "foo" wantFunc := "foo"
testErr = wire.MessageError{Func: wantFunc, Description: wantErr} testErr = MessageError{Func: wantFunc, Description: wantErr}
if testErr.Error() != wantFunc+": "+wantErr { if testErr.Error() != wantFunc+": "+wantErr {
t.Errorf("MessageError: wrong error - got %v, want %v", t.Errorf("MessageError: wrong error - got %v, want %v",
testErr.Error(), wantErr) testErr.Error(), wantErr)
} }
// Wire encoded bytes for main and testnet3 networks magic identifiers. // Wire encoded bytes for main and testnet3 networks magic identifiers.
testNet3Bytes := makeHeader(wire.TestNet3, "", 0, 0) testNet3Bytes := makeHeader(TestNet3, "", 0, 0)
// Wire encoded bytes for a message that exceeds max overall message // Wire encoded bytes for a message that exceeds max overall message
// length. // length.
mpl := uint32(wire.MaxMessagePayload) mpl := uint32(MaxMessagePayload)
exceedMaxPayloadBytes := makeHeader(btcnet, "getaddr", mpl+1, 0) exceedMaxPayloadBytes := makeHeader(btcnet, "getaddr", mpl+1, 0)
// Wire encoded bytes for a command which is invalid utf-8. // Wire encoded bytes for a command which is invalid utf-8.
@ -233,12 +232,12 @@ func TestReadMessageWireErrors(t *testing.T) {
discardBytes := makeHeader(btcnet, "bogus", 15*1024, 0) discardBytes := makeHeader(btcnet, "bogus", 15*1024, 0)
tests := []struct { tests := []struct {
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
btcnet wire.BitcoinNet // Bitcoin network for wire encoding btcnet BitcoinNet // Bitcoin network for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
readErr error // Expected read error readErr error // Expected read error
bytes int // Expected num bytes read bytes int // Expected num bytes read
}{ }{
// Latest protocol version with intentional read errors. // Latest protocol version with intentional read errors.
@ -258,7 +257,7 @@ func TestReadMessageWireErrors(t *testing.T) {
pver, pver,
btcnet, btcnet,
len(testNet3Bytes), len(testNet3Bytes),
&wire.MessageError{}, &MessageError{},
24, 24,
}, },
@ -268,7 +267,7 @@ func TestReadMessageWireErrors(t *testing.T) {
pver, pver,
btcnet, btcnet,
len(exceedMaxPayloadBytes), len(exceedMaxPayloadBytes),
&wire.MessageError{}, &MessageError{},
24, 24,
}, },
@ -278,7 +277,7 @@ func TestReadMessageWireErrors(t *testing.T) {
pver, pver,
btcnet, btcnet,
len(badCommandBytes), len(badCommandBytes),
&wire.MessageError{}, &MessageError{},
24, 24,
}, },
@ -288,7 +287,7 @@ func TestReadMessageWireErrors(t *testing.T) {
pver, pver,
btcnet, btcnet,
len(unsupportedCommandBytes), len(unsupportedCommandBytes),
&wire.MessageError{}, &MessageError{},
24, 24,
}, },
@ -298,7 +297,7 @@ func TestReadMessageWireErrors(t *testing.T) {
pver, pver,
btcnet, btcnet,
len(exceedTypePayloadBytes), len(exceedTypePayloadBytes),
&wire.MessageError{}, &MessageError{},
24, 24,
}, },
@ -318,7 +317,7 @@ func TestReadMessageWireErrors(t *testing.T) {
pver, pver,
btcnet, btcnet,
len(badChecksumBytes), len(badChecksumBytes),
&wire.MessageError{}, &MessageError{},
26, 26,
}, },
@ -338,7 +337,7 @@ func TestReadMessageWireErrors(t *testing.T) {
pver, pver,
btcnet, btcnet,
len(discardBytes), len(discardBytes),
&wire.MessageError{}, &MessageError{},
24, 24,
}, },
} }
@ -347,7 +346,7 @@ func TestReadMessageWireErrors(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Decode from wire format. // Decode from wire format.
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
nr, _, _, err := wire.ReadMessageN(r, test.pver, test.btcnet) nr, _, _, err := ReadMessageN(r, test.pver, test.btcnet)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
t.Errorf("ReadMessage #%d wrong error got: %v <%T>, "+ t.Errorf("ReadMessage #%d wrong error got: %v <%T>, "+
"want: %T", i, err, err, test.readErr) "want: %T", i, err, err, test.readErr)
@ -360,9 +359,9 @@ func TestReadMessageWireErrors(t *testing.T) {
"got %d, want %d", i, nr, test.bytes) "got %d, want %d", i, nr, test.bytes)
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("ReadMessage #%d wrong error got: %v <%T>, "+ t.Errorf("ReadMessage #%d wrong error got: %v <%T>, "+
"want: %v <%T>", i, err, err, "want: %v <%T>", i, err, err,
@ -376,9 +375,9 @@ func TestReadMessageWireErrors(t *testing.T) {
// TestWriteMessageWireErrors performs negative tests against wire encoding from // TestWriteMessageWireErrors performs negative tests against wire encoding from
// concrete messages to confirm error paths work correctly. // concrete messages to confirm error paths work correctly.
func TestWriteMessageWireErrors(t *testing.T) { func TestWriteMessageWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
btcnet := wire.MainNet btcnet := MainNet
wireErr := &wire.MessageError{} wireErr := &MessageError{}
// Fake message with a command that is too long. // Fake message with a command that is too long.
badCommandMsg := &fakeMessage{command: "somethingtoolong"} badCommandMsg := &fakeMessage{command: "somethingtoolong"}
@ -387,7 +386,7 @@ func TestWriteMessageWireErrors(t *testing.T) {
encodeErrMsg := &fakeMessage{forceEncodeErr: true} encodeErrMsg := &fakeMessage{forceEncodeErr: true}
// Fake message that has payload which exceeds max overall message size. // Fake message that has payload which exceeds max overall message size.
exceedOverallPayload := make([]byte, wire.MaxMessagePayload+1) exceedOverallPayload := make([]byte, MaxMessagePayload+1)
exceedOverallPayloadErrMsg := &fakeMessage{payload: exceedOverallPayload} exceedOverallPayloadErrMsg := &fakeMessage{payload: exceedOverallPayload}
// Fake message that has payload which exceeds max allowed per message. // Fake message that has payload which exceeds max allowed per message.
@ -400,12 +399,12 @@ func TestWriteMessageWireErrors(t *testing.T) {
bogusMsg := &fakeMessage{command: "bogus", payload: bogusPayload} bogusMsg := &fakeMessage{command: "bogus", payload: bogusPayload}
tests := []struct { tests := []struct {
msg wire.Message // Message to encode msg Message // Message to encode
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
btcnet wire.BitcoinNet // Bitcoin network for wire encoding btcnet BitcoinNet // Bitcoin network for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
err error // Expected error err error // Expected error
bytes int // Expected num bytes written bytes int // Expected num bytes written
}{ }{
// Command too long. // Command too long.
{badCommandMsg, pver, btcnet, 0, wireErr, 0}, {badCommandMsg, pver, btcnet, 0, wireErr, 0},
@ -425,7 +424,7 @@ func TestWriteMessageWireErrors(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Encode wire format. // Encode wire format.
w := newFixedWriter(test.max) w := newFixedWriter(test.max)
nw, err := wire.WriteMessageN(w, test.msg, test.pver, test.btcnet) nw, err := WriteMessageN(w, test.msg, test.pver, test.btcnet)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) { if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
t.Errorf("WriteMessage #%d wrong error got: %v <%T>, "+ t.Errorf("WriteMessage #%d wrong error got: %v <%T>, "+
"want: %T", i, err, err, test.err) "want: %T", i, err, err, test.err)
@ -438,9 +437,9 @@ func TestWriteMessageWireErrors(t *testing.T) {
"written - got %d, want %d", i, nw, test.bytes) "written - got %d, want %d", i, nw, test.bytes)
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.err { if err != test.err {
t.Errorf("ReadMessage #%d wrong error got: %v <%T>, "+ t.Errorf("ReadMessage #%d wrong error got: %v <%T>, "+
"want: %v <%T>", i, err, err, "want: %v <%T>", i, err, err,

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -12,17 +12,16 @@ import (
"testing" "testing"
"time" "time"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestAddr tests the MsgAddr API. // TestAddr tests the MsgAddr API.
func TestAddr(t *testing.T) { func TestAddr(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "addr" wantCmd := "addr"
msg := wire.NewMsgAddr() msg := NewMsgAddr()
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgAddr: wrong command - got %v want %v", t.Errorf("NewMsgAddr: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -40,7 +39,7 @@ func TestAddr(t *testing.T) {
// Ensure NetAddresses are added properly. // Ensure NetAddresses are added properly.
tcpAddr := &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8333} tcpAddr := &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8333}
na, err := wire.NewNetAddress(tcpAddr, wire.SFNodeNetwork) na, err := NewNetAddress(tcpAddr, SFNodeNetwork)
if err != nil { if err != nil {
t.Errorf("NewNetAddress: %v", err) t.Errorf("NewNetAddress: %v", err)
} }
@ -63,7 +62,7 @@ func TestAddr(t *testing.T) {
// Ensure adding more than the max allowed addresses per message returns // Ensure adding more than the max allowed addresses per message returns
// error. // error.
for i := 0; i < wire.MaxAddrPerMsg+1; i++ { for i := 0; i < MaxAddrPerMsg+1; i++ {
err = msg.AddAddress(na) err = msg.AddAddress(na)
} }
if err == nil { if err == nil {
@ -79,7 +78,7 @@ func TestAddr(t *testing.T) {
// Ensure max payload is expected value for protocol versions before // Ensure max payload is expected value for protocol versions before
// timestamp was added to NetAddress. // timestamp was added to NetAddress.
// Num addresses (varInt) + max allowed addresses. // Num addresses (varInt) + max allowed addresses.
pver = wire.NetAddressTimeVersion - 1 pver = NetAddressTimeVersion - 1
wantPayload = uint32(26009) wantPayload = uint32(26009)
maxPayload = msg.MaxPayloadLength(pver) maxPayload = msg.MaxPayloadLength(pver)
if maxPayload != wantPayload { if maxPayload != wantPayload {
@ -91,7 +90,7 @@ func TestAddr(t *testing.T) {
// Ensure max payload is expected value for protocol versions before // Ensure max payload is expected value for protocol versions before
// multiple addresses were allowed. // multiple addresses were allowed.
// Num addresses (varInt) + a single net addresses. // Num addresses (varInt) + a single net addresses.
pver = wire.MultipleAddressVersion - 1 pver = MultipleAddressVersion - 1
wantPayload = uint32(35) wantPayload = uint32(35)
maxPayload = msg.MaxPayloadLength(pver) maxPayload = msg.MaxPayloadLength(pver)
if maxPayload != wantPayload { if maxPayload != wantPayload {
@ -107,27 +106,27 @@ func TestAddr(t *testing.T) {
// of addreses and protocol versions. // of addreses and protocol versions.
func TestAddrWire(t *testing.T) { func TestAddrWire(t *testing.T) {
// A couple of NetAddresses to use for testing. // A couple of NetAddresses to use for testing.
na := &wire.NetAddress{ na := &NetAddress{
Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
IP: net.ParseIP("127.0.0.1"), IP: net.ParseIP("127.0.0.1"),
Port: 8333, Port: 8333,
} }
na2 := &wire.NetAddress{ na2 := &NetAddress{
Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
IP: net.ParseIP("192.168.0.1"), IP: net.ParseIP("192.168.0.1"),
Port: 8334, Port: 8334,
} }
// Empty address message. // Empty address message.
noAddr := wire.NewMsgAddr() noAddr := NewMsgAddr()
noAddrEncoded := []byte{ noAddrEncoded := []byte{
0x00, // Varint for number of addresses 0x00, // Varint for number of addresses
} }
// Address message with multiple addresses. // Address message with multiple addresses.
multiAddr := wire.NewMsgAddr() multiAddr := NewMsgAddr()
multiAddr.AddAddresses(na, na2) multiAddr.AddAddresses(na, na2)
multiAddrEncoded := []byte{ multiAddrEncoded := []byte{
0x02, // Varint for number of addresses 0x02, // Varint for number of addresses
@ -145,17 +144,17 @@ func TestAddrWire(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgAddr // Message to encode in *MsgAddr // Message to encode
out *wire.MsgAddr // Expected decoded message out *MsgAddr // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version with no addresses. // Latest protocol version with no addresses.
{ {
noAddr, noAddr,
noAddr, noAddr,
noAddrEncoded, noAddrEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Latest protocol version with multiple addresses. // Latest protocol version with multiple addresses.
@ -163,7 +162,7 @@ func TestAddrWire(t *testing.T) {
multiAddr, multiAddr,
multiAddr, multiAddr,
multiAddrEncoded, multiAddrEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version MultipleAddressVersion-1 with no addresses. // Protocol version MultipleAddressVersion-1 with no addresses.
@ -171,7 +170,7 @@ func TestAddrWire(t *testing.T) {
noAddr, noAddr,
noAddr, noAddr,
noAddrEncoded, noAddrEncoded,
wire.MultipleAddressVersion - 1, MultipleAddressVersion - 1,
}, },
} }
@ -191,7 +190,7 @@ func TestAddrWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgAddr var msg MsgAddr
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -209,26 +208,26 @@ func TestAddrWire(t *testing.T) {
// TestAddrWireErrors performs negative tests against wire encode and decode // TestAddrWireErrors performs negative tests against wire encode and decode
// of MsgAddr to confirm error paths work correctly. // of MsgAddr to confirm error paths work correctly.
func TestAddrWireErrors(t *testing.T) { func TestAddrWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
pverMA := wire.MultipleAddressVersion pverMA := MultipleAddressVersion
wireErr := &wire.MessageError{} wireErr := &MessageError{}
// A couple of NetAddresses to use for testing. // A couple of NetAddresses to use for testing.
na := &wire.NetAddress{ na := &NetAddress{
Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
IP: net.ParseIP("127.0.0.1"), IP: net.ParseIP("127.0.0.1"),
Port: 8333, Port: 8333,
} }
na2 := &wire.NetAddress{ na2 := &NetAddress{
Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
IP: net.ParseIP("192.168.0.1"), IP: net.ParseIP("192.168.0.1"),
Port: 8334, Port: 8334,
} }
// Address message with multiple addresses. // Address message with multiple addresses.
baseAddr := wire.NewMsgAddr() baseAddr := NewMsgAddr()
baseAddr.AddAddresses(na, na2) baseAddr.AddAddresses(na, na2)
baseAddrEncoded := []byte{ baseAddrEncoded := []byte{
0x02, // Varint for number of addresses 0x02, // Varint for number of addresses
@ -247,8 +246,8 @@ func TestAddrWireErrors(t *testing.T) {
// Message that forces an error by having more than the max allowed // Message that forces an error by having more than the max allowed
// addresses. // addresses.
maxAddr := wire.NewMsgAddr() maxAddr := NewMsgAddr()
for i := 0; i < wire.MaxAddrPerMsg; i++ { for i := 0; i < MaxAddrPerMsg; i++ {
maxAddr.AddAddress(na) maxAddr.AddAddress(na)
} }
maxAddr.AddrList = append(maxAddr.AddrList, na) maxAddr.AddrList = append(maxAddr.AddrList, na)
@ -257,12 +256,12 @@ func TestAddrWireErrors(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgAddr // Value to encode in *MsgAddr // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Latest protocol version with intentional read/write errors. // Latest protocol version with intentional read/write errors.
// Force error in addresses count // Force error in addresses count
@ -287,9 +286,9 @@ func TestAddrWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -298,7 +297,7 @@ func TestAddrWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgAddr var msg MsgAddr
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -307,9 +306,9 @@ func TestAddrWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -10,18 +10,17 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestMsgAlert tests the MsgAlert API. // TestMsgAlert tests the MsgAlert API.
func TestMsgAlert(t *testing.T) { func TestMsgAlert(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
serializedpayload := []byte("some message") serializedpayload := []byte("some message")
signature := []byte("some sig") signature := []byte("some sig")
// Ensure we get the same payload and signature back out. // Ensure we get the same payload and signature back out.
msg := wire.NewMsgAlert(serializedpayload, signature) msg := NewMsgAlert(serializedpayload, signature)
if !reflect.DeepEqual(msg.SerializedPayload, serializedpayload) { if !reflect.DeepEqual(msg.SerializedPayload, serializedpayload) {
t.Errorf("NewMsgAlert: wrong serializedpayload - got %v, want %v", t.Errorf("NewMsgAlert: wrong serializedpayload - got %v, want %v",
msg.SerializedPayload, serializedpayload) msg.SerializedPayload, serializedpayload)
@ -64,7 +63,7 @@ func TestMsgAlert(t *testing.T) {
// Test BtcEncode with Payload != nil // Test BtcEncode with Payload != nil
// note: Payload is an empty Alert but not nil // note: Payload is an empty Alert but not nil
msg.Payload = new(wire.Alert) msg.Payload = new(Alert)
buf = *new(bytes.Buffer) buf = *new(bytes.Buffer)
err = msg.BtcEncode(&buf, pver) err = msg.BtcEncode(&buf, pver)
if err != nil { if err != nil {
@ -85,7 +84,7 @@ func TestMsgAlert(t *testing.T) {
// TestMsgAlertWire tests the MsgAlert wire encode and decode for various protocol // TestMsgAlertWire tests the MsgAlert wire encode and decode for various protocol
// versions. // versions.
func TestMsgAlertWire(t *testing.T) { func TestMsgAlertWire(t *testing.T) {
baseMsgAlert := wire.NewMsgAlert([]byte("some payload"), []byte("somesig")) baseMsgAlert := NewMsgAlert([]byte("some payload"), []byte("somesig"))
baseMsgAlertEncoded := []byte{ baseMsgAlertEncoded := []byte{
0x0c, // Varint for payload length 0x0c, // Varint for payload length
0x73, 0x6f, 0x6d, 0x65, 0x20, 0x70, 0x61, 0x79, 0x73, 0x6f, 0x6d, 0x65, 0x20, 0x70, 0x61, 0x79,
@ -95,17 +94,17 @@ func TestMsgAlertWire(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgAlert // Message to encode in *MsgAlert // Message to encode
out *wire.MsgAlert // Expected decoded message out *MsgAlert // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
baseMsgAlert, baseMsgAlert,
baseMsgAlert, baseMsgAlert,
baseMsgAlertEncoded, baseMsgAlertEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version. // Protocol version BIP0035Version.
@ -113,7 +112,7 @@ func TestMsgAlertWire(t *testing.T) {
baseMsgAlert, baseMsgAlert,
baseMsgAlert, baseMsgAlert,
baseMsgAlertEncoded, baseMsgAlertEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version. // Protocol version BIP0031Version.
@ -121,7 +120,7 @@ func TestMsgAlertWire(t *testing.T) {
baseMsgAlert, baseMsgAlert,
baseMsgAlert, baseMsgAlert,
baseMsgAlertEncoded, baseMsgAlertEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion. // Protocol version NetAddressTimeVersion.
@ -129,7 +128,7 @@ func TestMsgAlertWire(t *testing.T) {
baseMsgAlert, baseMsgAlert,
baseMsgAlert, baseMsgAlert,
baseMsgAlertEncoded, baseMsgAlertEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion. // Protocol version MultipleAddressVersion.
@ -137,7 +136,7 @@ func TestMsgAlertWire(t *testing.T) {
baseMsgAlert, baseMsgAlert,
baseMsgAlert, baseMsgAlert,
baseMsgAlertEncoded, baseMsgAlertEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -157,7 +156,7 @@ func TestMsgAlertWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgAlert var msg MsgAlert
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -175,9 +174,9 @@ func TestMsgAlertWire(t *testing.T) {
// TestMsgAlertWireErrors performs negative tests against wire encode and decode // TestMsgAlertWireErrors performs negative tests against wire encode and decode
// of MsgAlert to confirm error paths work correctly. // of MsgAlert to confirm error paths work correctly.
func TestMsgAlertWireErrors(t *testing.T) { func TestMsgAlertWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
baseMsgAlert := wire.NewMsgAlert([]byte("some payload"), []byte("somesig")) baseMsgAlert := NewMsgAlert([]byte("some payload"), []byte("somesig"))
baseMsgAlertEncoded := []byte{ baseMsgAlertEncoded := []byte{
0x0c, // Varint for payload length 0x0c, // Varint for payload length
0x73, 0x6f, 0x6d, 0x65, 0x20, 0x70, 0x61, 0x79, 0x73, 0x6f, 0x6d, 0x65, 0x20, 0x70, 0x61, 0x79,
@ -187,12 +186,12 @@ func TestMsgAlertWireErrors(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgAlert // Value to encode in *MsgAlert // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Force error in payload length. // Force error in payload length.
{baseMsgAlert, baseMsgAlertEncoded, pver, 0, io.ErrShortWrite, io.EOF}, {baseMsgAlert, baseMsgAlertEncoded, pver, 0, io.ErrShortWrite, io.EOF},
@ -215,9 +214,9 @@ func TestMsgAlertWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -226,7 +225,7 @@ func TestMsgAlertWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgAlert var msg MsgAlert
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -235,9 +234,9 @@ func TestMsgAlertWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)
@ -250,38 +249,38 @@ func TestMsgAlertWireErrors(t *testing.T) {
baseMsgAlert.SerializedPayload = []byte{} baseMsgAlert.SerializedPayload = []byte{}
w := new(bytes.Buffer) w := new(bytes.Buffer)
err := baseMsgAlert.BtcEncode(w, pver) err := baseMsgAlert.BtcEncode(w, pver)
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
t.Errorf("MsgAlert.BtcEncode wrong error got: %T, want: %T", t.Errorf("MsgAlert.BtcEncode wrong error got: %T, want: %T",
err, wire.MessageError{}) err, MessageError{})
} }
// Test Payload Serialize error // Test Payload Serialize error
// overflow the max number of elements in SetCancel // overflow the max number of elements in SetCancel
baseMsgAlert.Payload = new(wire.Alert) baseMsgAlert.Payload = new(Alert)
baseMsgAlert.Payload.SetCancel = make([]int32, wire.MaxCountSetCancel+1) baseMsgAlert.Payload.SetCancel = make([]int32, maxCountSetCancel+1)
buf := *new(bytes.Buffer) buf := *new(bytes.Buffer)
err = baseMsgAlert.BtcEncode(&buf, pver) err = baseMsgAlert.BtcEncode(&buf, pver)
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
t.Errorf("MsgAlert.BtcEncode wrong error got: %T, want: %T", t.Errorf("MsgAlert.BtcEncode wrong error got: %T, want: %T",
err, wire.MessageError{}) err, MessageError{})
} }
// overflow the max number of elements in SetSubVer // overflow the max number of elements in SetSubVer
baseMsgAlert.Payload = new(wire.Alert) baseMsgAlert.Payload = new(Alert)
baseMsgAlert.Payload.SetSubVer = make([]string, wire.MaxCountSetSubVer+1) baseMsgAlert.Payload.SetSubVer = make([]string, maxCountSetSubVer+1)
buf = *new(bytes.Buffer) buf = *new(bytes.Buffer)
err = baseMsgAlert.BtcEncode(&buf, pver) err = baseMsgAlert.BtcEncode(&buf, pver)
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
t.Errorf("MsgAlert.BtcEncode wrong error got: %T, want: %T", t.Errorf("MsgAlert.BtcEncode wrong error got: %T, want: %T",
err, wire.MessageError{}) err, MessageError{})
} }
} }
// TestAlert tests serialization and deserialization // TestAlert tests serialization and deserialization
// of the payload to Alert // of the payload to Alert
func TestAlert(t *testing.T) { func TestAlert(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
alert := wire.NewAlert( alert := NewAlert(
1, 1337093712, 1368628812, 1015, 1, 1337093712, 1368628812, 1015,
1013, []int32{1014}, 0, 40599, []string{"/Satoshi:0.7.2/"}, 5000, "", 1013, []int32{1014}, 0, 40599, []string{"/Satoshi:0.7.2/"}, 5000, "",
"URGENT: upgrade required, see http://bitcoin.org/dos for details", "URGENT: upgrade required, see http://bitcoin.org/dos for details",
@ -292,7 +291,7 @@ func TestAlert(t *testing.T) {
t.Error(err.Error()) t.Error(err.Error())
} }
serializedpayload := w.Bytes() serializedpayload := w.Bytes()
newAlert, err := wire.NewAlertFromPayload(serializedpayload, pver) newAlert, err := NewAlertFromPayload(serializedpayload, pver)
if err != nil { if err != nil {
t.Error(err.Error()) t.Error(err.Error())
} }
@ -366,9 +365,9 @@ func TestAlert(t *testing.T) {
// TestAlertErrors performs negative tests against payload serialization, // TestAlertErrors performs negative tests against payload serialization,
// deserialization of Alert to confirm error paths work correctly. // deserialization of Alert to confirm error paths work correctly.
func TestAlertErrors(t *testing.T) { func TestAlertErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
baseAlert := wire.NewAlert( baseAlert := NewAlert(
1, 1337093712, 1368628812, 1015, 1, 1337093712, 1368628812, 1015,
1013, []int32{1014}, 0, 40599, []string{"/Satoshi:0.7.2/"}, 5000, "", 1013, []int32{1014}, 0, 40599, []string{"/Satoshi:0.7.2/"}, 5000, "",
"URGENT", "URGENT",
@ -381,12 +380,12 @@ func TestAlertErrors(t *testing.T) {
0x55, 0x52, 0x47, 0x45, 0x4e, 0x54, 0x00, //|URGENT.| 0x55, 0x52, 0x47, 0x45, 0x4e, 0x54, 0x00, //|URGENT.|
} }
tests := []struct { tests := []struct {
in *wire.Alert // Value to encode in *Alert // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Force error in Version // Force error in Version
{baseAlert, baseAlertEncoded, pver, 0, io.ErrShortWrite, io.EOF}, {baseAlert, baseAlertEncoded, pver, 0, io.ErrShortWrite, io.EOF},
@ -420,7 +419,7 @@ func TestAlertErrors(t *testing.T) {
continue continue
} }
var alert wire.Alert var alert Alert
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = alert.Deserialize(r, test.pver) err = alert.Deserialize(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -440,12 +439,12 @@ func TestAlertErrors(t *testing.T) {
0x73, 0x68, 0x69, 0x3a, 0x30, 0x2e, 0x37, 0x2e, 0x32, 0x2f, 0x88, 0x13, 0x00, 0x00, 0x00, 0x06, //|shi:0.7.2/......| 0x73, 0x68, 0x69, 0x3a, 0x30, 0x2e, 0x37, 0x2e, 0x32, 0x2f, 0x88, 0x13, 0x00, 0x00, 0x00, 0x06, //|shi:0.7.2/......|
0x55, 0x52, 0x47, 0x45, 0x4e, 0x54, 0x00, //|URGENT.| 0x55, 0x52, 0x47, 0x45, 0x4e, 0x54, 0x00, //|URGENT.|
} }
var alert wire.Alert var alert Alert
r := bytes.NewReader(badAlertEncoded) r := bytes.NewReader(badAlertEncoded)
err := alert.Deserialize(r, pver) err := alert.Deserialize(r, pver)
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
t.Errorf("Alert.Deserialize wrong error got: %T, want: %T", t.Errorf("Alert.Deserialize wrong error got: %T, want: %T",
err, wire.MessageError{}) err, MessageError{})
} }
// overflow the max number of elements in SetSubVer // overflow the max number of elements in SetSubVer
@ -460,8 +459,8 @@ func TestAlertErrors(t *testing.T) {
} }
r = bytes.NewReader(badAlertEncoded) r = bytes.NewReader(badAlertEncoded)
err = alert.Deserialize(r, pver) err = alert.Deserialize(r, pver)
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
t.Errorf("Alert.Deserialize wrong error got: %T, want: %T", t.Errorf("Alert.Deserialize wrong error got: %T, want: %T",
err, wire.MessageError{}) err, MessageError{})
} }
} }

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -11,24 +11,23 @@ import (
"testing" "testing"
"time" "time"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestBlock tests the MsgBlock API. // TestBlock tests the MsgBlock API.
func TestBlock(t *testing.T) { func TestBlock(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Block 1 header. // Block 1 header.
prevHash := &blockOne.Header.PrevBlock prevHash := &blockOne.Header.PrevBlock
merkleHash := &blockOne.Header.MerkleRoot merkleHash := &blockOne.Header.MerkleRoot
bits := blockOne.Header.Bits bits := blockOne.Header.Bits
nonce := blockOne.Header.Nonce nonce := blockOne.Header.Nonce
bh := wire.NewBlockHeader(prevHash, merkleHash, bits, nonce) bh := NewBlockHeader(prevHash, merkleHash, bits, nonce)
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "block" wantCmd := "block"
msg := wire.NewMsgBlock(bh) msg := NewMsgBlock(bh)
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgBlock: wrong command - got %v want %v", t.Errorf("NewMsgBlock: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -74,13 +73,13 @@ func TestBlock(t *testing.T) {
func TestBlockTxShas(t *testing.T) { func TestBlockTxShas(t *testing.T) {
// Block 1, transaction 1 hash. // Block 1, transaction 1 hash.
hashStr := "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098" hashStr := "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098"
wantHash, err := wire.NewShaHashFromStr(hashStr) wantHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
return return
} }
wantShas := []wire.ShaHash{*wantHash} wantShas := []ShaHash{*wantHash}
shas, err := blockOne.TxShas() shas, err := blockOne.TxShas()
if err != nil { if err != nil {
t.Errorf("TxShas: %v", err) t.Errorf("TxShas: %v", err)
@ -95,7 +94,7 @@ func TestBlockTxShas(t *testing.T) {
func TestBlockSha(t *testing.T) { func TestBlockSha(t *testing.T) {
// Block 1 hash. // Block 1 hash.
hashStr := "839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048" hashStr := "839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"
wantHash, err := wire.NewShaHashFromStr(hashStr) wantHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
@ -112,11 +111,11 @@ func TestBlockSha(t *testing.T) {
// of transaction inputs and outputs and protocol versions. // of transaction inputs and outputs and protocol versions.
func TestBlockWire(t *testing.T) { func TestBlockWire(t *testing.T) {
tests := []struct { tests := []struct {
in *wire.MsgBlock // Message to encode in *MsgBlock // Message to encode
out *wire.MsgBlock // Expected decoded message out *MsgBlock // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
txLocs []wire.TxLoc // Expected transaction locations txLocs []TxLoc // Expected transaction locations
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
@ -124,7 +123,7 @@ func TestBlockWire(t *testing.T) {
&blockOne, &blockOne,
blockOneBytes, blockOneBytes,
blockOneTxLocs, blockOneTxLocs,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version. // Protocol version BIP0035Version.
@ -133,7 +132,7 @@ func TestBlockWire(t *testing.T) {
&blockOne, &blockOne,
blockOneBytes, blockOneBytes,
blockOneTxLocs, blockOneTxLocs,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version. // Protocol version BIP0031Version.
@ -142,7 +141,7 @@ func TestBlockWire(t *testing.T) {
&blockOne, &blockOne,
blockOneBytes, blockOneBytes,
blockOneTxLocs, blockOneTxLocs,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion. // Protocol version NetAddressTimeVersion.
@ -151,7 +150,7 @@ func TestBlockWire(t *testing.T) {
&blockOne, &blockOne,
blockOneBytes, blockOneBytes,
blockOneTxLocs, blockOneTxLocs,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion. // Protocol version MultipleAddressVersion.
@ -160,7 +159,7 @@ func TestBlockWire(t *testing.T) {
&blockOne, &blockOne,
blockOneBytes, blockOneBytes,
blockOneTxLocs, blockOneTxLocs,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -180,7 +179,7 @@ func TestBlockWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgBlock var msg MsgBlock
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -204,12 +203,12 @@ func TestBlockWireErrors(t *testing.T) {
pver := uint32(60002) pver := uint32(60002)
tests := []struct { tests := []struct {
in *wire.MsgBlock // Value to encode in *MsgBlock // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Force error in version. // Force error in version.
{&blockOne, blockOneBytes, pver, 0, io.ErrShortWrite, io.EOF}, {&blockOne, blockOneBytes, pver, 0, io.ErrShortWrite, io.EOF},
@ -241,7 +240,7 @@ func TestBlockWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgBlock var msg MsgBlock
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if err != test.readErr { if err != test.readErr {
@ -255,10 +254,10 @@ func TestBlockWireErrors(t *testing.T) {
// TestBlockSerialize tests MsgBlock serialize and deserialize. // TestBlockSerialize tests MsgBlock serialize and deserialize.
func TestBlockSerialize(t *testing.T) { func TestBlockSerialize(t *testing.T) {
tests := []struct { tests := []struct {
in *wire.MsgBlock // Message to encode in *MsgBlock // Message to encode
out *wire.MsgBlock // Expected decoded message out *MsgBlock // Expected decoded message
buf []byte // Serialized data buf []byte // Serialized data
txLocs []wire.TxLoc // Expected transaction locations txLocs []TxLoc // Expected transaction locations
}{ }{
{ {
&blockOne, &blockOne,
@ -284,7 +283,7 @@ func TestBlockSerialize(t *testing.T) {
} }
// Deserialize the block. // Deserialize the block.
var block wire.MsgBlock var block MsgBlock
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = block.Deserialize(rbuf) err = block.Deserialize(rbuf)
if err != nil { if err != nil {
@ -299,7 +298,7 @@ func TestBlockSerialize(t *testing.T) {
// Deserialize the block while gathering transaction location // Deserialize the block while gathering transaction location
// information. // information.
var txLocBlock wire.MsgBlock var txLocBlock MsgBlock
br := bytes.NewBuffer(test.buf) br := bytes.NewBuffer(test.buf)
txLocs, err := txLocBlock.DeserializeTxLoc(br) txLocs, err := txLocBlock.DeserializeTxLoc(br)
if err != nil { if err != nil {
@ -323,11 +322,11 @@ func TestBlockSerialize(t *testing.T) {
// decode of MsgBlock to confirm error paths work correctly. // decode of MsgBlock to confirm error paths work correctly.
func TestBlockSerializeErrors(t *testing.T) { func TestBlockSerializeErrors(t *testing.T) {
tests := []struct { tests := []struct {
in *wire.MsgBlock // Value to encode in *MsgBlock // Value to encode
buf []byte // Serialized data buf []byte // Serialized data
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Force error in version. // Force error in version.
{&blockOne, blockOneBytes, 0, io.ErrShortWrite, io.EOF}, {&blockOne, blockOneBytes, 0, io.ErrShortWrite, io.EOF},
@ -359,7 +358,7 @@ func TestBlockSerializeErrors(t *testing.T) {
} }
// Deserialize the block. // Deserialize the block.
var block wire.MsgBlock var block MsgBlock
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = block.Deserialize(r) err = block.Deserialize(r)
if err != test.readErr { if err != test.readErr {
@ -368,7 +367,7 @@ func TestBlockSerializeErrors(t *testing.T) {
continue continue
} }
var txLocBlock wire.MsgBlock var txLocBlock MsgBlock
br := bytes.NewBuffer(test.buf[0:test.max]) br := bytes.NewBuffer(test.buf[0:test.max])
_, err = txLocBlock.DeserializeTxLoc(br) _, err = txLocBlock.DeserializeTxLoc(br)
if err != test.readErr { if err != test.readErr {
@ -411,14 +410,14 @@ func TestBlockOverflowErrors(t *testing.T) {
0x01, 0xe3, 0x62, 0x99, // Nonce 0x01, 0xe3, 0x62, 0x99, // Nonce
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, // TxnCount 0xff, // TxnCount
}, pver, &wire.MessageError{}, }, pver, &MessageError{},
}, },
} }
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Decode from wire format. // Decode from wire format.
var msg wire.MsgBlock var msg MsgBlock
r := bytes.NewReader(test.buf) r := bytes.NewReader(test.buf)
err := msg.BtcDecode(r, test.pver) err := msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) { if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
@ -451,11 +450,11 @@ func TestBlockOverflowErrors(t *testing.T) {
// various blocks is accurate. // various blocks is accurate.
func TestBlockSerializeSize(t *testing.T) { func TestBlockSerializeSize(t *testing.T) {
// Block with no transactions. // Block with no transactions.
noTxBlock := wire.NewMsgBlock(&blockOne.Header) noTxBlock := NewMsgBlock(&blockOne.Header)
tests := []struct { tests := []struct {
in *wire.MsgBlock // Block to encode in *MsgBlock // Block to encode
size int // Expected serialized size size int // Expected serialized size
}{ }{
// Block with no transactions. // Block with no transactions.
{noTxBlock, 81}, {noTxBlock, 81},
@ -475,16 +474,17 @@ func TestBlockSerializeSize(t *testing.T) {
} }
} }
var blockOne = wire.MsgBlock{ // blockOne is the first block in the mainnet block chain.
Header: wire.BlockHeader{ var blockOne = MsgBlock{
Header: BlockHeader{
Version: 1, Version: 1,
PrevBlock: wire.ShaHash([wire.HashSize]byte{ // Make go vet happy. PrevBlock: ShaHash([HashSize]byte{ // Make go vet happy.
0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72, 0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f, 0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f,
0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c, 0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
}), }),
MerkleRoot: wire.ShaHash([wire.HashSize]byte{ // Make go vet happy. MerkleRoot: ShaHash([HashSize]byte{ // Make go vet happy.
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44, 0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67, 0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1, 0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
@ -495,13 +495,13 @@ var blockOne = wire.MsgBlock{
Bits: 0x1d00ffff, // 486604799 Bits: 0x1d00ffff, // 486604799
Nonce: 0x9962e301, // 2573394689 Nonce: 0x9962e301, // 2573394689
}, },
Transactions: []*wire.MsgTx{ Transactions: []*MsgTx{
{ {
Version: 1, Version: 1,
TxIn: []*wire.TxIn{ TxIn: []*TxIn{
{ {
PreviousOutPoint: wire.OutPoint{ PreviousOutPoint: OutPoint{
Hash: wire.ShaHash{}, Hash: ShaHash{},
Index: 0xffffffff, Index: 0xffffffff,
}, },
SignatureScript: []byte{ SignatureScript: []byte{
@ -510,7 +510,7 @@ var blockOne = wire.MsgBlock{
Sequence: 0xffffffff, Sequence: 0xffffffff,
}, },
}, },
TxOut: []*wire.TxOut{ TxOut: []*TxOut{
{ {
Value: 0x12a05f200, Value: 0x12a05f200,
PkScript: []byte{ PkScript: []byte{
@ -576,6 +576,6 @@ var blockOneBytes = []byte{
} }
// Transaction location information for block one transactions. // Transaction location information for block one transactions.
var blockOneTxLocs = []wire.TxLoc{ var blockOneTxLocs = []TxLoc{
{TxStart: 81, TxLen: 134}, {TxStart: 81, TxLen: 134},
} }

View file

@ -1,25 +1,23 @@
// Copyright (c) 2014-2015 The btcsuite developers // Copyright (c) 2014-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
"io" "io"
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
) )
// TestFilterAddLatest tests the MsgFilterAdd API against the latest protocol // TestFilterAddLatest tests the MsgFilterAdd API against the latest protocol
// version. // version.
func TestFilterAddLatest(t *testing.T) { func TestFilterAddLatest(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
data := []byte{0x01, 0x02} data := []byte{0x01, 0x02}
msg := wire.NewMsgFilterAdd(data) msg := NewMsgFilterAdd(data)
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "filteradd" wantCmd := "filteradd"
@ -45,7 +43,7 @@ func TestFilterAddLatest(t *testing.T) {
} }
// Test decode with latest protocol version. // Test decode with latest protocol version.
var readmsg wire.MsgFilterAdd var readmsg MsgFilterAdd
err = readmsg.BtcDecode(&buf, pver) err = readmsg.BtcDecode(&buf, pver)
if err != nil { if err != nil {
t.Errorf("decode of MsgFilterAdd failed [%v] err <%v>", buf, err) t.Errorf("decode of MsgFilterAdd failed [%v] err <%v>", buf, err)
@ -58,21 +56,21 @@ func TestFilterAddLatest(t *testing.T) {
// latest protocol version and decoding with BIP0031Version. // latest protocol version and decoding with BIP0031Version.
func TestFilterAddCrossProtocol(t *testing.T) { func TestFilterAddCrossProtocol(t *testing.T) {
data := []byte{0x01, 0x02} data := []byte{0x01, 0x02}
msg := wire.NewMsgFilterAdd(data) msg := NewMsgFilterAdd(data)
if !bytes.Equal(msg.Data, data) { if !bytes.Equal(msg.Data, data) {
t.Errorf("should get same data back out") t.Errorf("should get same data back out")
} }
// Encode with latest protocol version. // Encode with latest protocol version.
var buf bytes.Buffer var buf bytes.Buffer
err := msg.BtcEncode(&buf, wire.ProtocolVersion) err := msg.BtcEncode(&buf, ProtocolVersion)
if err != nil { if err != nil {
t.Errorf("encode of MsgFilterAdd failed %v err <%v>", msg, err) t.Errorf("encode of MsgFilterAdd failed %v err <%v>", msg, err)
} }
// Decode with old protocol version. // Decode with old protocol version.
var readmsg wire.MsgFilterAdd var readmsg MsgFilterAdd
err = readmsg.BtcDecode(&buf, wire.BIP0031Version) err = readmsg.BtcDecode(&buf, BIP0031Version)
if err == nil { if err == nil {
t.Errorf("decode of MsgFilterAdd succeeded when it shouldn't "+ t.Errorf("decode of MsgFilterAdd succeeded when it shouldn't "+
"have %v", msg) "have %v", msg)
@ -89,11 +87,11 @@ func TestFilterAddCrossProtocol(t *testing.T) {
// TestFilterAddMaxDataSize tests the MsgFilterAdd API maximum data size. // TestFilterAddMaxDataSize tests the MsgFilterAdd API maximum data size.
func TestFilterAddMaxDataSize(t *testing.T) { func TestFilterAddMaxDataSize(t *testing.T) {
data := bytes.Repeat([]byte{0xff}, 521) data := bytes.Repeat([]byte{0xff}, 521)
msg := wire.NewMsgFilterAdd(data) msg := NewMsgFilterAdd(data)
// Encode with latest protocol version. // Encode with latest protocol version.
var buf bytes.Buffer var buf bytes.Buffer
err := msg.BtcEncode(&buf, wire.ProtocolVersion) err := msg.BtcEncode(&buf, ProtocolVersion)
if err == nil { if err == nil {
t.Errorf("encode of MsgFilterAdd succeeded when it shouldn't "+ t.Errorf("encode of MsgFilterAdd succeeded when it shouldn't "+
"have %v", msg) "have %v", msg)
@ -101,7 +99,7 @@ func TestFilterAddMaxDataSize(t *testing.T) {
// Decode with latest protocol version. // Decode with latest protocol version.
readbuf := bytes.NewReader(data) readbuf := bytes.NewReader(data)
err = msg.BtcDecode(readbuf, wire.ProtocolVersion) err = msg.BtcDecode(readbuf, ProtocolVersion)
if err == nil { if err == nil {
t.Errorf("decode of MsgFilterAdd succeeded when it shouldn't "+ t.Errorf("decode of MsgFilterAdd succeeded when it shouldn't "+
"have %v", msg) "have %v", msg)
@ -111,21 +109,21 @@ func TestFilterAddMaxDataSize(t *testing.T) {
// TestFilterAddWireErrors performs negative tests against wire encode and decode // TestFilterAddWireErrors performs negative tests against wire encode and decode
// of MsgFilterAdd to confirm error paths work correctly. // of MsgFilterAdd to confirm error paths work correctly.
func TestFilterAddWireErrors(t *testing.T) { func TestFilterAddWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
pverNoFilterAdd := wire.BIP0037Version - 1 pverNoFilterAdd := BIP0037Version - 1
wireErr := &wire.MessageError{} wireErr := &MessageError{}
baseData := []byte{0x01, 0x02, 0x03, 0x04} baseData := []byte{0x01, 0x02, 0x03, 0x04}
baseFilterAdd := wire.NewMsgFilterAdd(baseData) baseFilterAdd := NewMsgFilterAdd(baseData)
baseFilterAddEncoded := append([]byte{0x04}, baseData...) baseFilterAddEncoded := append([]byte{0x04}, baseData...)
tests := []struct { tests := []struct {
in *wire.MsgFilterAdd // Value to encode in *MsgFilterAdd // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Latest protocol version with intentional read/write errors. // Latest protocol version with intentional read/write errors.
// Force error in data size. // Force error in data size.
@ -156,9 +154,9 @@ func TestFilterAddWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -167,7 +165,7 @@ func TestFilterAddWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgFilterAdd var msg MsgFilterAdd
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -176,9 +174,9 @@ func TestFilterAddWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View file

@ -1,24 +1,23 @@
// Copyright (c) 2014-2015 The btcsuite developers // Copyright (c) 2014-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestFilterCLearLatest tests the MsgFilterClear API against the latest // TestFilterCLearLatest tests the MsgFilterClear API against the latest
// protocol version. // protocol version.
func TestFilterClearLatest(t *testing.T) { func TestFilterClearLatest(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
msg := wire.NewMsgFilterClear() msg := NewMsgFilterClear()
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "filterclear" wantCmd := "filterclear"
@ -42,18 +41,18 @@ func TestFilterClearLatest(t *testing.T) {
// TestFilterClearCrossProtocol tests the MsgFilterClear API when encoding with // TestFilterClearCrossProtocol tests the MsgFilterClear API when encoding with
// the latest protocol version and decoding with BIP0031Version. // the latest protocol version and decoding with BIP0031Version.
func TestFilterClearCrossProtocol(t *testing.T) { func TestFilterClearCrossProtocol(t *testing.T) {
msg := wire.NewMsgFilterClear() msg := NewMsgFilterClear()
// Encode with latest protocol version. // Encode with latest protocol version.
var buf bytes.Buffer var buf bytes.Buffer
err := msg.BtcEncode(&buf, wire.ProtocolVersion) err := msg.BtcEncode(&buf, ProtocolVersion)
if err != nil { if err != nil {
t.Errorf("encode of MsgFilterClear failed %v err <%v>", msg, err) t.Errorf("encode of MsgFilterClear failed %v err <%v>", msg, err)
} }
// Decode with old protocol version. // Decode with old protocol version.
var readmsg wire.MsgFilterClear var readmsg MsgFilterClear
err = readmsg.BtcDecode(&buf, wire.BIP0031Version) err = readmsg.BtcDecode(&buf, BIP0031Version)
if err == nil { if err == nil {
t.Errorf("decode of MsgFilterClear succeeded when it "+ t.Errorf("decode of MsgFilterClear succeeded when it "+
"shouldn't have %v", msg) "shouldn't have %v", msg)
@ -63,21 +62,21 @@ func TestFilterClearCrossProtocol(t *testing.T) {
// TestFilterClearWire tests the MsgFilterClear wire encode and decode for // TestFilterClearWire tests the MsgFilterClear wire encode and decode for
// various protocol versions. // various protocol versions.
func TestFilterClearWire(t *testing.T) { func TestFilterClearWire(t *testing.T) {
msgFilterClear := wire.NewMsgFilterClear() msgFilterClear := NewMsgFilterClear()
msgFilterClearEncoded := []byte{} msgFilterClearEncoded := []byte{}
tests := []struct { tests := []struct {
in *wire.MsgFilterClear // Message to encode in *MsgFilterClear // Message to encode
out *wire.MsgFilterClear // Expected decoded message out *MsgFilterClear // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
msgFilterClear, msgFilterClear,
msgFilterClear, msgFilterClear,
msgFilterClearEncoded, msgFilterClearEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0037Version + 1. // Protocol version BIP0037Version + 1.
@ -85,7 +84,7 @@ func TestFilterClearWire(t *testing.T) {
msgFilterClear, msgFilterClear,
msgFilterClear, msgFilterClear,
msgFilterClearEncoded, msgFilterClearEncoded,
wire.BIP0037Version + 1, BIP0037Version + 1,
}, },
// Protocol version BIP0037Version. // Protocol version BIP0037Version.
@ -93,7 +92,7 @@ func TestFilterClearWire(t *testing.T) {
msgFilterClear, msgFilterClear,
msgFilterClear, msgFilterClear,
msgFilterClearEncoded, msgFilterClearEncoded,
wire.BIP0037Version, BIP0037Version,
}, },
} }
@ -113,7 +112,7 @@ func TestFilterClearWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgFilterClear var msg MsgFilterClear
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -131,19 +130,19 @@ func TestFilterClearWire(t *testing.T) {
// TestFilterClearWireErrors performs negative tests against wire encode and // TestFilterClearWireErrors performs negative tests against wire encode and
// decode of MsgFilterClear to confirm error paths work correctly. // decode of MsgFilterClear to confirm error paths work correctly.
func TestFilterClearWireErrors(t *testing.T) { func TestFilterClearWireErrors(t *testing.T) {
pverNoFilterClear := wire.BIP0037Version - 1 pverNoFilterClear := BIP0037Version - 1
wireErr := &wire.MessageError{} wireErr := &MessageError{}
baseFilterClear := wire.NewMsgFilterClear() baseFilterClear := NewMsgFilterClear()
baseFilterClearEncoded := []byte{} baseFilterClearEncoded := []byte{}
tests := []struct { tests := []struct {
in *wire.MsgFilterClear // Value to encode in *MsgFilterClear // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Force error due to unsupported protocol version. // Force error due to unsupported protocol version.
{ {
@ -163,9 +162,9 @@ func TestFilterClearWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -174,7 +173,7 @@ func TestFilterClearWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgFilterClear var msg MsgFilterClear
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -183,9 +182,9 @@ func TestFilterClearWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View file

@ -1,25 +1,23 @@
// Copyright (c) 2014 The btcsuite developers // Copyright (c) 2014-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
"io" "io"
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
) )
// TestFilterCLearLatest tests the MsgFilterLoad API against the latest protocol // TestFilterCLearLatest tests the MsgFilterLoad API against the latest protocol
// version. // version.
func TestFilterLoadLatest(t *testing.T) { func TestFilterLoadLatest(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
data := []byte{0x01, 0x02} data := []byte{0x01, 0x02}
msg := wire.NewMsgFilterLoad(data, 10, 0, 0) msg := NewMsgFilterLoad(data, 10, 0, 0)
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "filterload" wantCmd := "filterload"
@ -45,7 +43,7 @@ func TestFilterLoadLatest(t *testing.T) {
} }
// Test decode with latest protocol version. // Test decode with latest protocol version.
readmsg := wire.MsgFilterLoad{} readmsg := MsgFilterLoad{}
err = readmsg.BtcDecode(&buf, pver) err = readmsg.BtcDecode(&buf, pver)
if err != nil { if err != nil {
t.Errorf("decode of MsgFilterLoad failed [%v] err <%v>", buf, err) t.Errorf("decode of MsgFilterLoad failed [%v] err <%v>", buf, err)
@ -58,19 +56,19 @@ func TestFilterLoadLatest(t *testing.T) {
// the latest protocol version and decoding with BIP0031Version. // the latest protocol version and decoding with BIP0031Version.
func TestFilterLoadCrossProtocol(t *testing.T) { func TestFilterLoadCrossProtocol(t *testing.T) {
data := []byte{0x01, 0x02} data := []byte{0x01, 0x02}
msg := wire.NewMsgFilterLoad(data, 10, 0, 0) msg := NewMsgFilterLoad(data, 10, 0, 0)
// Encode with latest protocol version. // Encode with latest protocol version.
var buf bytes.Buffer var buf bytes.Buffer
err := msg.BtcEncode(&buf, wire.ProtocolVersion) err := msg.BtcEncode(&buf, ProtocolVersion)
if err != nil { if err != nil {
t.Errorf("encode of NewMsgFilterLoad failed %v err <%v>", msg, t.Errorf("encode of NewMsgFilterLoad failed %v err <%v>", msg,
err) err)
} }
// Decode with old protocol version. // Decode with old protocol version.
var readmsg wire.MsgFilterLoad var readmsg MsgFilterLoad
err = readmsg.BtcDecode(&buf, wire.BIP0031Version) err = readmsg.BtcDecode(&buf, BIP0031Version)
if err == nil { if err == nil {
t.Errorf("decode of MsgFilterLoad succeeded when it shouldn't have %v", t.Errorf("decode of MsgFilterLoad succeeded when it shouldn't have %v",
msg) msg)
@ -80,11 +78,11 @@ func TestFilterLoadCrossProtocol(t *testing.T) {
// TestFilterLoadMaxFilterSize tests the MsgFilterLoad API maximum filter size. // TestFilterLoadMaxFilterSize tests the MsgFilterLoad API maximum filter size.
func TestFilterLoadMaxFilterSize(t *testing.T) { func TestFilterLoadMaxFilterSize(t *testing.T) {
data := bytes.Repeat([]byte{0xff}, 36001) data := bytes.Repeat([]byte{0xff}, 36001)
msg := wire.NewMsgFilterLoad(data, 10, 0, 0) msg := NewMsgFilterLoad(data, 10, 0, 0)
// Encode with latest protocol version. // Encode with latest protocol version.
var buf bytes.Buffer var buf bytes.Buffer
err := msg.BtcEncode(&buf, wire.ProtocolVersion) err := msg.BtcEncode(&buf, ProtocolVersion)
if err == nil { if err == nil {
t.Errorf("encode of MsgFilterLoad succeeded when it shouldn't "+ t.Errorf("encode of MsgFilterLoad succeeded when it shouldn't "+
"have %v", msg) "have %v", msg)
@ -92,7 +90,7 @@ func TestFilterLoadMaxFilterSize(t *testing.T) {
// Decode with latest protocol version. // Decode with latest protocol version.
readbuf := bytes.NewReader(data) readbuf := bytes.NewReader(data)
err = msg.BtcDecode(readbuf, wire.ProtocolVersion) err = msg.BtcDecode(readbuf, ProtocolVersion)
if err == nil { if err == nil {
t.Errorf("decode of MsgFilterLoad succeeded when it shouldn't "+ t.Errorf("decode of MsgFilterLoad succeeded when it shouldn't "+
"have %v", msg) "have %v", msg)
@ -102,11 +100,11 @@ func TestFilterLoadMaxFilterSize(t *testing.T) {
// TestFilterLoadMaxHashFuncsSize tests the MsgFilterLoad API maximum hash functions. // TestFilterLoadMaxHashFuncsSize tests the MsgFilterLoad API maximum hash functions.
func TestFilterLoadMaxHashFuncsSize(t *testing.T) { func TestFilterLoadMaxHashFuncsSize(t *testing.T) {
data := bytes.Repeat([]byte{0xff}, 10) data := bytes.Repeat([]byte{0xff}, 10)
msg := wire.NewMsgFilterLoad(data, 61, 0, 0) msg := NewMsgFilterLoad(data, 61, 0, 0)
// Encode with latest protocol version. // Encode with latest protocol version.
var buf bytes.Buffer var buf bytes.Buffer
err := msg.BtcEncode(&buf, wire.ProtocolVersion) err := msg.BtcEncode(&buf, ProtocolVersion)
if err == nil { if err == nil {
t.Errorf("encode of MsgFilterLoad succeeded when it shouldn't have %v", t.Errorf("encode of MsgFilterLoad succeeded when it shouldn't have %v",
msg) msg)
@ -121,7 +119,7 @@ func TestFilterLoadMaxHashFuncsSize(t *testing.T) {
} }
// Decode with latest protocol version. // Decode with latest protocol version.
readbuf := bytes.NewReader(newBuf) readbuf := bytes.NewReader(newBuf)
err = msg.BtcDecode(readbuf, wire.ProtocolVersion) err = msg.BtcDecode(readbuf, ProtocolVersion)
if err == nil { if err == nil {
t.Errorf("decode of MsgFilterLoad succeeded when it shouldn't have %v", t.Errorf("decode of MsgFilterLoad succeeded when it shouldn't have %v",
msg) msg)
@ -131,13 +129,12 @@ func TestFilterLoadMaxHashFuncsSize(t *testing.T) {
// TestFilterLoadWireErrors performs negative tests against wire encode and decode // TestFilterLoadWireErrors performs negative tests against wire encode and decode
// of MsgFilterLoad to confirm error paths work correctly. // of MsgFilterLoad to confirm error paths work correctly.
func TestFilterLoadWireErrors(t *testing.T) { func TestFilterLoadWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
pverNoFilterLoad := wire.BIP0037Version - 1 pverNoFilterLoad := BIP0037Version - 1
wireErr := &wire.MessageError{} wireErr := &MessageError{}
baseFilter := []byte{0x01, 0x02, 0x03, 0x04} baseFilter := []byte{0x01, 0x02, 0x03, 0x04}
baseFilterLoad := wire.NewMsgFilterLoad(baseFilter, 10, 0, baseFilterLoad := NewMsgFilterLoad(baseFilter, 10, 0, BloomUpdateNone)
wire.BloomUpdateNone)
baseFilterLoadEncoded := append([]byte{0x04}, baseFilter...) baseFilterLoadEncoded := append([]byte{0x04}, baseFilter...)
baseFilterLoadEncoded = append(baseFilterLoadEncoded, baseFilterLoadEncoded = append(baseFilterLoadEncoded,
0x00, 0x00, 0x00, 0x0a, // HashFuncs 0x00, 0x00, 0x00, 0x0a, // HashFuncs
@ -145,12 +142,12 @@ func TestFilterLoadWireErrors(t *testing.T) {
0x00) // Flags 0x00) // Flags
tests := []struct { tests := []struct {
in *wire.MsgFilterLoad // Value to encode in *MsgFilterLoad // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Latest protocol version with intentional read/write errors. // Latest protocol version with intentional read/write errors.
// Force error in filter size. // Force error in filter size.
@ -196,9 +193,9 @@ func TestFilterLoadWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -207,7 +204,7 @@ func TestFilterLoadWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgFilterLoad var msg MsgFilterLoad
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -216,9 +213,9 @@ func TestFilterLoadWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View file

@ -1,25 +1,24 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestGetAddr tests the MsgGetAddr API. // TestGetAddr tests the MsgGetAddr API.
func TestGetAddr(t *testing.T) { func TestGetAddr(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "getaddr" wantCmd := "getaddr"
msg := wire.NewMsgGetAddr() msg := NewMsgGetAddr()
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgGetAddr: wrong command - got %v want %v", t.Errorf("NewMsgGetAddr: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -41,21 +40,21 @@ func TestGetAddr(t *testing.T) {
// TestGetAddrWire tests the MsgGetAddr wire encode and decode for various // TestGetAddrWire tests the MsgGetAddr wire encode and decode for various
// protocol versions. // protocol versions.
func TestGetAddrWire(t *testing.T) { func TestGetAddrWire(t *testing.T) {
msgGetAddr := wire.NewMsgGetAddr() msgGetAddr := NewMsgGetAddr()
msgGetAddrEncoded := []byte{} msgGetAddrEncoded := []byte{}
tests := []struct { tests := []struct {
in *wire.MsgGetAddr // Message to encode in *MsgGetAddr // Message to encode
out *wire.MsgGetAddr // Expected decoded message out *MsgGetAddr // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
msgGetAddr, msgGetAddr,
msgGetAddr, msgGetAddr,
msgGetAddrEncoded, msgGetAddrEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version. // Protocol version BIP0035Version.
@ -63,7 +62,7 @@ func TestGetAddrWire(t *testing.T) {
msgGetAddr, msgGetAddr,
msgGetAddr, msgGetAddr,
msgGetAddrEncoded, msgGetAddrEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version. // Protocol version BIP0031Version.
@ -71,7 +70,7 @@ func TestGetAddrWire(t *testing.T) {
msgGetAddr, msgGetAddr,
msgGetAddr, msgGetAddr,
msgGetAddrEncoded, msgGetAddrEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion. // Protocol version NetAddressTimeVersion.
@ -79,7 +78,7 @@ func TestGetAddrWire(t *testing.T) {
msgGetAddr, msgGetAddr,
msgGetAddr, msgGetAddr,
msgGetAddrEncoded, msgGetAddrEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion. // Protocol version MultipleAddressVersion.
@ -87,7 +86,7 @@ func TestGetAddrWire(t *testing.T) {
msgGetAddr, msgGetAddr,
msgGetAddr, msgGetAddr,
msgGetAddrEncoded, msgGetAddrEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -107,7 +106,7 @@ func TestGetAddrWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgGetAddr var msg MsgGetAddr
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -10,30 +10,29 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestGetBlocks tests the MsgGetBlocks API. // TestGetBlocks tests the MsgGetBlocks API.
func TestGetBlocks(t *testing.T) { func TestGetBlocks(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Block 99500 hash. // Block 99500 hash.
hashStr := "000000000002e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0" hashStr := "000000000002e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0"
locatorHash, err := wire.NewShaHashFromStr(hashStr) locatorHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Block 100000 hash. // Block 100000 hash.
hashStr = "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506" hashStr = "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
hashStop, err := wire.NewShaHashFromStr(hashStr) hashStop, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Ensure we get the same data back out. // Ensure we get the same data back out.
msg := wire.NewMsgGetBlocks(hashStop) msg := NewMsgGetBlocks(hashStop)
if !msg.HashStop.IsEqual(hashStop) { if !msg.HashStop.IsEqual(hashStop) {
t.Errorf("NewMsgGetBlocks: wrong stop hash - got %v, want %v", t.Errorf("NewMsgGetBlocks: wrong stop hash - got %v, want %v",
msg.HashStop, hashStop) msg.HashStop, hashStop)
@ -71,7 +70,7 @@ func TestGetBlocks(t *testing.T) {
// Ensure adding more than the max allowed block locator hashes per // Ensure adding more than the max allowed block locator hashes per
// message returns an error. // message returns an error.
for i := 0; i < wire.MaxBlockLocatorsPerMsg; i++ { for i := 0; i < MaxBlockLocatorsPerMsg; i++ {
err = msg.AddBlockLocatorHash(locatorHash) err = msg.AddBlockLocatorHash(locatorHash)
} }
if err == nil { if err == nil {
@ -90,27 +89,27 @@ func TestGetBlocksWire(t *testing.T) {
// Block 99499 hash. // Block 99499 hash.
hashStr := "2710f40c87ec93d010a6fd95f42c59a2cbacc60b18cf6b7957535" hashStr := "2710f40c87ec93d010a6fd95f42c59a2cbacc60b18cf6b7957535"
hashLocator, err := wire.NewShaHashFromStr(hashStr) hashLocator, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Block 99500 hash. // Block 99500 hash.
hashStr = "2e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0" hashStr = "2e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0"
hashLocator2, err := wire.NewShaHashFromStr(hashStr) hashLocator2, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Block 100000 hash. // Block 100000 hash.
hashStr = "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506" hashStr = "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
hashStop, err := wire.NewShaHashFromStr(hashStr) hashStop, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// MsgGetBlocks message with no block locators or stop hash. // MsgGetBlocks message with no block locators or stop hash.
noLocators := wire.NewMsgGetBlocks(&wire.ShaHash{}) noLocators := NewMsgGetBlocks(&ShaHash{})
noLocators.ProtocolVersion = pver noLocators.ProtocolVersion = pver
noLocatorsEncoded := []byte{ noLocatorsEncoded := []byte{
0x62, 0xea, 0x00, 0x00, // Protocol version 60002 0x62, 0xea, 0x00, 0x00, // Protocol version 60002
@ -122,7 +121,7 @@ func TestGetBlocksWire(t *testing.T) {
} }
// MsgGetBlocks message with multiple block locators and a stop hash. // MsgGetBlocks message with multiple block locators and a stop hash.
multiLocators := wire.NewMsgGetBlocks(hashStop) multiLocators := NewMsgGetBlocks(hashStop)
multiLocators.AddBlockLocatorHash(hashLocator2) multiLocators.AddBlockLocatorHash(hashLocator2)
multiLocators.AddBlockLocatorHash(hashLocator) multiLocators.AddBlockLocatorHash(hashLocator)
multiLocators.ProtocolVersion = pver multiLocators.ProtocolVersion = pver
@ -144,17 +143,17 @@ func TestGetBlocksWire(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgGetBlocks // Message to encode in *MsgGetBlocks // Message to encode
out *wire.MsgGetBlocks // Expected decoded message out *MsgGetBlocks // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version with no block locators. // Latest protocol version with no block locators.
{ {
noLocators, noLocators,
noLocators, noLocators,
noLocatorsEncoded, noLocatorsEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Latest protocol version with multiple block locators. // Latest protocol version with multiple block locators.
@ -162,7 +161,7 @@ func TestGetBlocksWire(t *testing.T) {
multiLocators, multiLocators,
multiLocators, multiLocators,
multiLocatorsEncoded, multiLocatorsEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version with no block locators. // Protocol version BIP0035Version with no block locators.
@ -170,7 +169,7 @@ func TestGetBlocksWire(t *testing.T) {
noLocators, noLocators,
noLocators, noLocators,
noLocatorsEncoded, noLocatorsEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0035Version with multiple block locators. // Protocol version BIP0035Version with multiple block locators.
@ -178,7 +177,7 @@ func TestGetBlocksWire(t *testing.T) {
multiLocators, multiLocators,
multiLocators, multiLocators,
multiLocatorsEncoded, multiLocatorsEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version with no block locators. // Protocol version BIP0031Version with no block locators.
@ -186,7 +185,7 @@ func TestGetBlocksWire(t *testing.T) {
noLocators, noLocators,
noLocators, noLocators,
noLocatorsEncoded, noLocatorsEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version BIP0031Versionwith multiple block locators. // Protocol version BIP0031Versionwith multiple block locators.
@ -194,7 +193,7 @@ func TestGetBlocksWire(t *testing.T) {
multiLocators, multiLocators,
multiLocators, multiLocators,
multiLocatorsEncoded, multiLocatorsEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion with no block locators. // Protocol version NetAddressTimeVersion with no block locators.
@ -202,7 +201,7 @@ func TestGetBlocksWire(t *testing.T) {
noLocators, noLocators,
noLocators, noLocators,
noLocatorsEncoded, noLocatorsEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version NetAddressTimeVersion multiple block locators. // Protocol version NetAddressTimeVersion multiple block locators.
@ -210,7 +209,7 @@ func TestGetBlocksWire(t *testing.T) {
multiLocators, multiLocators,
multiLocators, multiLocators,
multiLocatorsEncoded, multiLocatorsEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion with no block locators. // Protocol version MultipleAddressVersion with no block locators.
@ -218,7 +217,7 @@ func TestGetBlocksWire(t *testing.T) {
noLocators, noLocators,
noLocators, noLocators,
noLocatorsEncoded, noLocatorsEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
// Protocol version MultipleAddressVersion multiple block locators. // Protocol version MultipleAddressVersion multiple block locators.
@ -226,7 +225,7 @@ func TestGetBlocksWire(t *testing.T) {
multiLocators, multiLocators,
multiLocators, multiLocators,
multiLocatorsEncoded, multiLocatorsEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -246,7 +245,7 @@ func TestGetBlocksWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgGetBlocks var msg MsgGetBlocks
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -268,31 +267,31 @@ func TestGetBlocksWireErrors(t *testing.T) {
// specifically here instead of the latest because the test data is // specifically here instead of the latest because the test data is
// using bytes encoded with that protocol version. // using bytes encoded with that protocol version.
pver := uint32(60002) pver := uint32(60002)
wireErr := &wire.MessageError{} wireErr := &MessageError{}
// Block 99499 hash. // Block 99499 hash.
hashStr := "2710f40c87ec93d010a6fd95f42c59a2cbacc60b18cf6b7957535" hashStr := "2710f40c87ec93d010a6fd95f42c59a2cbacc60b18cf6b7957535"
hashLocator, err := wire.NewShaHashFromStr(hashStr) hashLocator, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Block 99500 hash. // Block 99500 hash.
hashStr = "2e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0" hashStr = "2e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0"
hashLocator2, err := wire.NewShaHashFromStr(hashStr) hashLocator2, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Block 100000 hash. // Block 100000 hash.
hashStr = "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506" hashStr = "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
hashStop, err := wire.NewShaHashFromStr(hashStr) hashStop, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// MsgGetBlocks message with multiple block locators and a stop hash. // MsgGetBlocks message with multiple block locators and a stop hash.
baseGetBlocks := wire.NewMsgGetBlocks(hashStop) baseGetBlocks := NewMsgGetBlocks(hashStop)
baseGetBlocks.ProtocolVersion = pver baseGetBlocks.ProtocolVersion = pver
baseGetBlocks.AddBlockLocatorHash(hashLocator2) baseGetBlocks.AddBlockLocatorHash(hashLocator2)
baseGetBlocks.AddBlockLocatorHash(hashLocator) baseGetBlocks.AddBlockLocatorHash(hashLocator)
@ -315,8 +314,8 @@ func TestGetBlocksWireErrors(t *testing.T) {
// Message that forces an error by having more than the max allowed // Message that forces an error by having more than the max allowed
// block locator hashes. // block locator hashes.
maxGetBlocks := wire.NewMsgGetBlocks(hashStop) maxGetBlocks := NewMsgGetBlocks(hashStop)
for i := 0; i < wire.MaxBlockLocatorsPerMsg; i++ { for i := 0; i < MaxBlockLocatorsPerMsg; i++ {
maxGetBlocks.AddBlockLocatorHash(&mainNetGenesisHash) maxGetBlocks.AddBlockLocatorHash(&mainNetGenesisHash)
} }
maxGetBlocks.BlockLocatorHashes = append(maxGetBlocks.BlockLocatorHashes, maxGetBlocks.BlockLocatorHashes = append(maxGetBlocks.BlockLocatorHashes,
@ -327,12 +326,12 @@ func TestGetBlocksWireErrors(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgGetBlocks // Value to encode in *MsgGetBlocks // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Force error in protocol version. // Force error in protocol version.
{baseGetBlocks, baseGetBlocksEncoded, pver, 0, io.ErrShortWrite, io.EOF}, {baseGetBlocks, baseGetBlocksEncoded, pver, 0, io.ErrShortWrite, io.EOF},
@ -357,9 +356,9 @@ func TestGetBlocksWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -368,7 +367,7 @@ func TestGetBlocksWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgGetBlocks var msg MsgGetBlocks
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -377,9 +376,9 @@ func TestGetBlocksWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -10,17 +10,16 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestGetData tests the MsgGetData API. // TestGetData tests the MsgGetData API.
func TestGetData(t *testing.T) { func TestGetData(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "getdata" wantCmd := "getdata"
msg := wire.NewMsgGetData() msg := NewMsgGetData()
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgGetData: wrong command - got %v want %v", t.Errorf("NewMsgGetData: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -37,8 +36,8 @@ func TestGetData(t *testing.T) {
} }
// Ensure inventory vectors are added properly. // Ensure inventory vectors are added properly.
hash := wire.ShaHash{} hash := ShaHash{}
iv := wire.NewInvVect(wire.InvTypeBlock, &hash) iv := NewInvVect(InvTypeBlock, &hash)
err := msg.AddInvVect(iv) err := msg.AddInvVect(iv)
if err != nil { if err != nil {
t.Errorf("AddInvVect: %v", err) t.Errorf("AddInvVect: %v", err)
@ -50,7 +49,7 @@ func TestGetData(t *testing.T) {
// Ensure adding more than the max allowed inventory vectors per // Ensure adding more than the max allowed inventory vectors per
// message returns an error. // message returns an error.
for i := 0; i < wire.MaxInvPerMsg; i++ { for i := 0; i < MaxInvPerMsg; i++ {
err = msg.AddInvVect(iv) err = msg.AddInvVect(iv)
} }
if err == nil { if err == nil {
@ -60,8 +59,8 @@ func TestGetData(t *testing.T) {
// Ensure creating the message with a size hint larger than the max // Ensure creating the message with a size hint larger than the max
// works as expected. // works as expected.
msg = wire.NewMsgGetDataSizeHint(wire.MaxInvPerMsg + 1) msg = NewMsgGetDataSizeHint(MaxInvPerMsg + 1)
wantCap := wire.MaxInvPerMsg wantCap := MaxInvPerMsg
if cap(msg.InvList) != wantCap { if cap(msg.InvList) != wantCap {
t.Errorf("NewMsgGetDataSizeHint: wrong cap for size hint - "+ t.Errorf("NewMsgGetDataSizeHint: wrong cap for size hint - "+
"got %v, want %v", cap(msg.InvList), wantCap) "got %v, want %v", cap(msg.InvList), wantCap)
@ -75,29 +74,29 @@ func TestGetData(t *testing.T) {
func TestGetDataWire(t *testing.T) { func TestGetDataWire(t *testing.T) {
// Block 203707 hash. // Block 203707 hash.
hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc" hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc"
blockHash, err := wire.NewShaHashFromStr(hashStr) blockHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Transation 1 of Block 203707 hash. // Transation 1 of Block 203707 hash.
hashStr = "d28a3dc7392bf00a9855ee93dd9a81eff82a2c4fe57fbd42cfe71b487accfaf0" hashStr = "d28a3dc7392bf00a9855ee93dd9a81eff82a2c4fe57fbd42cfe71b487accfaf0"
txHash, err := wire.NewShaHashFromStr(hashStr) txHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
iv := wire.NewInvVect(wire.InvTypeBlock, blockHash) iv := NewInvVect(InvTypeBlock, blockHash)
iv2 := wire.NewInvVect(wire.InvTypeTx, txHash) iv2 := NewInvVect(InvTypeTx, txHash)
// Empty MsgGetData message. // Empty MsgGetData message.
NoInv := wire.NewMsgGetData() NoInv := NewMsgGetData()
NoInvEncoded := []byte{ NoInvEncoded := []byte{
0x00, // Varint for number of inventory vectors 0x00, // Varint for number of inventory vectors
} }
// MsgGetData message with multiple inventory vectors. // MsgGetData message with multiple inventory vectors.
MultiInv := wire.NewMsgGetData() MultiInv := NewMsgGetData()
MultiInv.AddInvVect(iv) MultiInv.AddInvVect(iv)
MultiInv.AddInvVect(iv2) MultiInv.AddInvVect(iv2)
MultiInvEncoded := []byte{ MultiInvEncoded := []byte{
@ -115,17 +114,17 @@ func TestGetDataWire(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgGetData // Message to encode in *MsgGetData // Message to encode
out *wire.MsgGetData // Expected decoded message out *MsgGetData // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version with no inv vectors. // Latest protocol version with no inv vectors.
{ {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Latest protocol version with multiple inv vectors. // Latest protocol version with multiple inv vectors.
@ -133,7 +132,7 @@ func TestGetDataWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version no inv vectors. // Protocol version BIP0035Version no inv vectors.
@ -141,7 +140,7 @@ func TestGetDataWire(t *testing.T) {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0035Version with multiple inv vectors. // Protocol version BIP0035Version with multiple inv vectors.
@ -149,7 +148,7 @@ func TestGetDataWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version no inv vectors. // Protocol version BIP0031Version no inv vectors.
@ -157,7 +156,7 @@ func TestGetDataWire(t *testing.T) {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version BIP0031Version with multiple inv vectors. // Protocol version BIP0031Version with multiple inv vectors.
@ -165,7 +164,7 @@ func TestGetDataWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion no inv vectors. // Protocol version NetAddressTimeVersion no inv vectors.
@ -173,7 +172,7 @@ func TestGetDataWire(t *testing.T) {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version NetAddressTimeVersion with multiple inv vectors. // Protocol version NetAddressTimeVersion with multiple inv vectors.
@ -181,7 +180,7 @@ func TestGetDataWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion no inv vectors. // Protocol version MultipleAddressVersion no inv vectors.
@ -189,7 +188,7 @@ func TestGetDataWire(t *testing.T) {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
// Protocol version MultipleAddressVersion with multiple inv vectors. // Protocol version MultipleAddressVersion with multiple inv vectors.
@ -197,7 +196,7 @@ func TestGetDataWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -217,7 +216,7 @@ func TestGetDataWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgGetData var msg MsgGetData
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -235,20 +234,20 @@ func TestGetDataWire(t *testing.T) {
// TestGetDataWireErrors performs negative tests against wire encode and decode // TestGetDataWireErrors performs negative tests against wire encode and decode
// of MsgGetData to confirm error paths work correctly. // of MsgGetData to confirm error paths work correctly.
func TestGetDataWireErrors(t *testing.T) { func TestGetDataWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
wireErr := &wire.MessageError{} wireErr := &MessageError{}
// Block 203707 hash. // Block 203707 hash.
hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc" hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc"
blockHash, err := wire.NewShaHashFromStr(hashStr) blockHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
iv := wire.NewInvVect(wire.InvTypeBlock, blockHash) iv := NewInvVect(InvTypeBlock, blockHash)
// Base message used to induce errors. // Base message used to induce errors.
baseGetData := wire.NewMsgGetData() baseGetData := NewMsgGetData()
baseGetData.AddInvVect(iv) baseGetData.AddInvVect(iv)
baseGetDataEncoded := []byte{ baseGetDataEncoded := []byte{
0x02, // Varint for number of inv vectors 0x02, // Varint for number of inv vectors
@ -261,8 +260,8 @@ func TestGetDataWireErrors(t *testing.T) {
// Message that forces an error by having more than the max allowed inv // Message that forces an error by having more than the max allowed inv
// vectors. // vectors.
maxGetData := wire.NewMsgGetData() maxGetData := NewMsgGetData()
for i := 0; i < wire.MaxInvPerMsg; i++ { for i := 0; i < MaxInvPerMsg; i++ {
maxGetData.AddInvVect(iv) maxGetData.AddInvVect(iv)
} }
maxGetData.InvList = append(maxGetData.InvList, iv) maxGetData.InvList = append(maxGetData.InvList, iv)
@ -271,12 +270,12 @@ func TestGetDataWireErrors(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgGetData // Value to encode in *MsgGetData // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Latest protocol version with intentional read/write errors. // Latest protocol version with intentional read/write errors.
// Force error in inventory vector count // Force error in inventory vector count
@ -298,9 +297,9 @@ func TestGetDataWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -309,7 +308,7 @@ func TestGetDataWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgGetData var msg MsgGetData
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -318,9 +317,9 @@ func TestGetDataWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -10,24 +10,23 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestGetHeaders tests the MsgGetHeader API. // TestGetHeaders tests the MsgGetHeader API.
func TestGetHeaders(t *testing.T) { func TestGetHeaders(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Block 99500 hash. // Block 99500 hash.
hashStr := "000000000002e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0" hashStr := "000000000002e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0"
locatorHash, err := wire.NewShaHashFromStr(hashStr) locatorHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "getheaders" wantCmd := "getheaders"
msg := wire.NewMsgGetHeaders() msg := NewMsgGetHeaders()
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgGetHeaders: wrong command - got %v want %v", t.Errorf("NewMsgGetHeaders: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -58,7 +57,7 @@ func TestGetHeaders(t *testing.T) {
// Ensure adding more than the max allowed block locator hashes per // Ensure adding more than the max allowed block locator hashes per
// message returns an error. // message returns an error.
for i := 0; i < wire.MaxBlockLocatorsPerMsg; i++ { for i := 0; i < MaxBlockLocatorsPerMsg; i++ {
err = msg.AddBlockLocatorHash(locatorHash) err = msg.AddBlockLocatorHash(locatorHash)
} }
if err == nil { if err == nil {
@ -79,27 +78,27 @@ func TestGetHeadersWire(t *testing.T) {
// Block 99499 hash. // Block 99499 hash.
hashStr := "2710f40c87ec93d010a6fd95f42c59a2cbacc60b18cf6b7957535" hashStr := "2710f40c87ec93d010a6fd95f42c59a2cbacc60b18cf6b7957535"
hashLocator, err := wire.NewShaHashFromStr(hashStr) hashLocator, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Block 99500 hash. // Block 99500 hash.
hashStr = "2e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0" hashStr = "2e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0"
hashLocator2, err := wire.NewShaHashFromStr(hashStr) hashLocator2, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Block 100000 hash. // Block 100000 hash.
hashStr = "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506" hashStr = "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
hashStop, err := wire.NewShaHashFromStr(hashStr) hashStop, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// MsgGetHeaders message with no block locators or stop hash. // MsgGetHeaders message with no block locators or stop hash.
noLocators := wire.NewMsgGetHeaders() noLocators := NewMsgGetHeaders()
noLocators.ProtocolVersion = pver noLocators.ProtocolVersion = pver
noLocatorsEncoded := []byte{ noLocatorsEncoded := []byte{
0x62, 0xea, 0x00, 0x00, // Protocol version 60002 0x62, 0xea, 0x00, 0x00, // Protocol version 60002
@ -111,7 +110,7 @@ func TestGetHeadersWire(t *testing.T) {
} }
// MsgGetHeaders message with multiple block locators and a stop hash. // MsgGetHeaders message with multiple block locators and a stop hash.
multiLocators := wire.NewMsgGetHeaders() multiLocators := NewMsgGetHeaders()
multiLocators.ProtocolVersion = pver multiLocators.ProtocolVersion = pver
multiLocators.HashStop = *hashStop multiLocators.HashStop = *hashStop
multiLocators.AddBlockLocatorHash(hashLocator2) multiLocators.AddBlockLocatorHash(hashLocator2)
@ -134,17 +133,17 @@ func TestGetHeadersWire(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgGetHeaders // Message to encode in *MsgGetHeaders // Message to encode
out *wire.MsgGetHeaders // Expected decoded message out *MsgGetHeaders // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version with no block locators. // Latest protocol version with no block locators.
{ {
noLocators, noLocators,
noLocators, noLocators,
noLocatorsEncoded, noLocatorsEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Latest protocol version with multiple block locators. // Latest protocol version with multiple block locators.
@ -152,7 +151,7 @@ func TestGetHeadersWire(t *testing.T) {
multiLocators, multiLocators,
multiLocators, multiLocators,
multiLocatorsEncoded, multiLocatorsEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version with no block locators. // Protocol version BIP0035Version with no block locators.
@ -160,7 +159,7 @@ func TestGetHeadersWire(t *testing.T) {
noLocators, noLocators,
noLocators, noLocators,
noLocatorsEncoded, noLocatorsEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0035Version with multiple block locators. // Protocol version BIP0035Version with multiple block locators.
@ -168,7 +167,7 @@ func TestGetHeadersWire(t *testing.T) {
multiLocators, multiLocators,
multiLocators, multiLocators,
multiLocatorsEncoded, multiLocatorsEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version with no block locators. // Protocol version BIP0031Version with no block locators.
@ -176,7 +175,7 @@ func TestGetHeadersWire(t *testing.T) {
noLocators, noLocators,
noLocators, noLocators,
noLocatorsEncoded, noLocatorsEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version BIP0031Versionwith multiple block locators. // Protocol version BIP0031Versionwith multiple block locators.
@ -184,7 +183,7 @@ func TestGetHeadersWire(t *testing.T) {
multiLocators, multiLocators,
multiLocators, multiLocators,
multiLocatorsEncoded, multiLocatorsEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion with no block locators. // Protocol version NetAddressTimeVersion with no block locators.
@ -192,7 +191,7 @@ func TestGetHeadersWire(t *testing.T) {
noLocators, noLocators,
noLocators, noLocators,
noLocatorsEncoded, noLocatorsEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version NetAddressTimeVersion multiple block locators. // Protocol version NetAddressTimeVersion multiple block locators.
@ -200,7 +199,7 @@ func TestGetHeadersWire(t *testing.T) {
multiLocators, multiLocators,
multiLocators, multiLocators,
multiLocatorsEncoded, multiLocatorsEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion with no block locators. // Protocol version MultipleAddressVersion with no block locators.
@ -208,7 +207,7 @@ func TestGetHeadersWire(t *testing.T) {
noLocators, noLocators,
noLocators, noLocators,
noLocatorsEncoded, noLocatorsEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
// Protocol version MultipleAddressVersion multiple block locators. // Protocol version MultipleAddressVersion multiple block locators.
@ -216,7 +215,7 @@ func TestGetHeadersWire(t *testing.T) {
multiLocators, multiLocators,
multiLocators, multiLocators,
multiLocatorsEncoded, multiLocatorsEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -236,7 +235,7 @@ func TestGetHeadersWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgGetHeaders var msg MsgGetHeaders
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -258,31 +257,31 @@ func TestGetHeadersWireErrors(t *testing.T) {
// specifically here instead of the latest because the test data is // specifically here instead of the latest because the test data is
// using bytes encoded with that protocol version. // using bytes encoded with that protocol version.
pver := uint32(60002) pver := uint32(60002)
wireErr := &wire.MessageError{} wireErr := &MessageError{}
// Block 99499 hash. // Block 99499 hash.
hashStr := "2710f40c87ec93d010a6fd95f42c59a2cbacc60b18cf6b7957535" hashStr := "2710f40c87ec93d010a6fd95f42c59a2cbacc60b18cf6b7957535"
hashLocator, err := wire.NewShaHashFromStr(hashStr) hashLocator, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Block 99500 hash. // Block 99500 hash.
hashStr = "2e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0" hashStr = "2e7ad7b9eef9479e4aabc65cb831269cc20d2632c13684406dee0"
hashLocator2, err := wire.NewShaHashFromStr(hashStr) hashLocator2, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Block 100000 hash. // Block 100000 hash.
hashStr = "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506" hashStr = "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
hashStop, err := wire.NewShaHashFromStr(hashStr) hashStop, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// MsgGetHeaders message with multiple block locators and a stop hash. // MsgGetHeaders message with multiple block locators and a stop hash.
baseGetHeaders := wire.NewMsgGetHeaders() baseGetHeaders := NewMsgGetHeaders()
baseGetHeaders.ProtocolVersion = pver baseGetHeaders.ProtocolVersion = pver
baseGetHeaders.HashStop = *hashStop baseGetHeaders.HashStop = *hashStop
baseGetHeaders.AddBlockLocatorHash(hashLocator2) baseGetHeaders.AddBlockLocatorHash(hashLocator2)
@ -306,8 +305,8 @@ func TestGetHeadersWireErrors(t *testing.T) {
// Message that forces an error by having more than the max allowed // Message that forces an error by having more than the max allowed
// block locator hashes. // block locator hashes.
maxGetHeaders := wire.NewMsgGetHeaders() maxGetHeaders := NewMsgGetHeaders()
for i := 0; i < wire.MaxBlockLocatorsPerMsg; i++ { for i := 0; i < MaxBlockLocatorsPerMsg; i++ {
maxGetHeaders.AddBlockLocatorHash(&mainNetGenesisHash) maxGetHeaders.AddBlockLocatorHash(&mainNetGenesisHash)
} }
maxGetHeaders.BlockLocatorHashes = append(maxGetHeaders.BlockLocatorHashes, maxGetHeaders.BlockLocatorHashes = append(maxGetHeaders.BlockLocatorHashes,
@ -318,12 +317,12 @@ func TestGetHeadersWireErrors(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgGetHeaders // Value to encode in *MsgGetHeaders // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Force error in protocol version. // Force error in protocol version.
{baseGetHeaders, baseGetHeadersEncoded, pver, 0, io.ErrShortWrite, io.EOF}, {baseGetHeaders, baseGetHeadersEncoded, pver, 0, io.ErrShortWrite, io.EOF},
@ -348,9 +347,9 @@ func TestGetHeadersWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -359,7 +358,7 @@ func TestGetHeadersWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgGetHeaders var msg MsgGetHeaders
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -368,9 +367,9 @@ func TestGetHeadersWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -10,7 +10,6 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
@ -20,7 +19,7 @@ func TestHeaders(t *testing.T) {
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "headers" wantCmd := "headers"
msg := wire.NewMsgHeaders() msg := NewMsgHeaders()
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgHeaders: wrong command - got %v want %v", t.Errorf("NewMsgHeaders: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -49,10 +48,10 @@ func TestHeaders(t *testing.T) {
// Ensure adding more than the max allowed headers per message returns // Ensure adding more than the max allowed headers per message returns
// error. // error.
var err error var err error
for i := 0; i < wire.MaxBlockHeadersPerMsg+1; i++ { for i := 0; i < MaxBlockHeadersPerMsg+1; i++ {
err = msg.AddBlockHeader(bh) err = msg.AddBlockHeader(bh)
} }
if reflect.TypeOf(err) != reflect.TypeOf(&wire.MessageError{}) { if reflect.TypeOf(err) != reflect.TypeOf(&MessageError{}) {
t.Errorf("AddBlockHeader: expected error on too many headers " + t.Errorf("AddBlockHeader: expected error on too many headers " +
"not received") "not received")
} }
@ -67,18 +66,18 @@ func TestHeadersWire(t *testing.T) {
merkleHash := blockOne.Header.MerkleRoot merkleHash := blockOne.Header.MerkleRoot
bits := uint32(0x1d00ffff) bits := uint32(0x1d00ffff)
nonce := uint32(0x9962e301) nonce := uint32(0x9962e301)
bh := wire.NewBlockHeader(&hash, &merkleHash, bits, nonce) bh := NewBlockHeader(&hash, &merkleHash, bits, nonce)
bh.Version = blockOne.Header.Version bh.Version = blockOne.Header.Version
bh.Timestamp = blockOne.Header.Timestamp bh.Timestamp = blockOne.Header.Timestamp
// Empty headers message. // Empty headers message.
noHeaders := wire.NewMsgHeaders() noHeaders := NewMsgHeaders()
noHeadersEncoded := []byte{ noHeadersEncoded := []byte{
0x00, // Varint for number of headers 0x00, // Varint for number of headers
} }
// Headers message with one header. // Headers message with one header.
oneHeader := wire.NewMsgHeaders() oneHeader := NewMsgHeaders()
oneHeader.AddBlockHeader(bh) oneHeader.AddBlockHeader(bh)
oneHeaderEncoded := []byte{ oneHeaderEncoded := []byte{
0x01, // VarInt for number of headers. 0x01, // VarInt for number of headers.
@ -98,17 +97,17 @@ func TestHeadersWire(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgHeaders // Message to encode in *MsgHeaders // Message to encode
out *wire.MsgHeaders // Expected decoded message out *MsgHeaders // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version with no headers. // Latest protocol version with no headers.
{ {
noHeaders, noHeaders,
noHeaders, noHeaders,
noHeadersEncoded, noHeadersEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Latest protocol version with one header. // Latest protocol version with one header.
@ -116,7 +115,7 @@ func TestHeadersWire(t *testing.T) {
oneHeader, oneHeader,
oneHeader, oneHeader,
oneHeaderEncoded, oneHeaderEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version with no headers. // Protocol version BIP0035Version with no headers.
@ -124,7 +123,7 @@ func TestHeadersWire(t *testing.T) {
noHeaders, noHeaders,
noHeaders, noHeaders,
noHeadersEncoded, noHeadersEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0035Version with one header. // Protocol version BIP0035Version with one header.
@ -132,7 +131,7 @@ func TestHeadersWire(t *testing.T) {
oneHeader, oneHeader,
oneHeader, oneHeader,
oneHeaderEncoded, oneHeaderEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version with no headers. // Protocol version BIP0031Version with no headers.
@ -140,7 +139,7 @@ func TestHeadersWire(t *testing.T) {
noHeaders, noHeaders,
noHeaders, noHeaders,
noHeadersEncoded, noHeadersEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version BIP0031Version with one header. // Protocol version BIP0031Version with one header.
@ -148,14 +147,14 @@ func TestHeadersWire(t *testing.T) {
oneHeader, oneHeader,
oneHeader, oneHeader,
oneHeaderEncoded, oneHeaderEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion with no headers. // Protocol version NetAddressTimeVersion with no headers.
{ {
noHeaders, noHeaders,
noHeaders, noHeaders,
noHeadersEncoded, noHeadersEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version NetAddressTimeVersion with one header. // Protocol version NetAddressTimeVersion with one header.
@ -163,7 +162,7 @@ func TestHeadersWire(t *testing.T) {
oneHeader, oneHeader,
oneHeader, oneHeader,
oneHeaderEncoded, oneHeaderEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion with no headers. // Protocol version MultipleAddressVersion with no headers.
@ -171,7 +170,7 @@ func TestHeadersWire(t *testing.T) {
noHeaders, noHeaders,
noHeaders, noHeaders,
noHeadersEncoded, noHeadersEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
// Protocol version MultipleAddressVersion with one header. // Protocol version MultipleAddressVersion with one header.
@ -179,7 +178,7 @@ func TestHeadersWire(t *testing.T) {
oneHeader, oneHeader,
oneHeader, oneHeader,
oneHeaderEncoded, oneHeaderEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -199,7 +198,7 @@ func TestHeadersWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgHeaders var msg MsgHeaders
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -217,19 +216,19 @@ func TestHeadersWire(t *testing.T) {
// TestHeadersWireErrors performs negative tests against wire encode and decode // TestHeadersWireErrors performs negative tests against wire encode and decode
// of MsgHeaders to confirm error paths work correctly. // of MsgHeaders to confirm error paths work correctly.
func TestHeadersWireErrors(t *testing.T) { func TestHeadersWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
wireErr := &wire.MessageError{} wireErr := &MessageError{}
hash := mainNetGenesisHash hash := mainNetGenesisHash
merkleHash := blockOne.Header.MerkleRoot merkleHash := blockOne.Header.MerkleRoot
bits := uint32(0x1d00ffff) bits := uint32(0x1d00ffff)
nonce := uint32(0x9962e301) nonce := uint32(0x9962e301)
bh := wire.NewBlockHeader(&hash, &merkleHash, bits, nonce) bh := NewBlockHeader(&hash, &merkleHash, bits, nonce)
bh.Version = blockOne.Header.Version bh.Version = blockOne.Header.Version
bh.Timestamp = blockOne.Header.Timestamp bh.Timestamp = blockOne.Header.Timestamp
// Headers message with one header. // Headers message with one header.
oneHeader := wire.NewMsgHeaders() oneHeader := NewMsgHeaders()
oneHeader.AddBlockHeader(bh) oneHeader.AddBlockHeader(bh)
oneHeaderEncoded := []byte{ oneHeaderEncoded := []byte{
0x01, // VarInt for number of headers. 0x01, // VarInt for number of headers.
@ -250,8 +249,8 @@ func TestHeadersWireErrors(t *testing.T) {
// Message that forces an error by having more than the max allowed // Message that forces an error by having more than the max allowed
// headers. // headers.
maxHeaders := wire.NewMsgHeaders() maxHeaders := NewMsgHeaders()
for i := 0; i < wire.MaxBlockHeadersPerMsg; i++ { for i := 0; i < MaxBlockHeadersPerMsg; i++ {
maxHeaders.AddBlockHeader(bh) maxHeaders.AddBlockHeader(bh)
} }
maxHeaders.Headers = append(maxHeaders.Headers, bh) maxHeaders.Headers = append(maxHeaders.Headers, bh)
@ -261,11 +260,11 @@ func TestHeadersWireErrors(t *testing.T) {
// Intentionally invalid block header that has a transaction count used // Intentionally invalid block header that has a transaction count used
// to force errors. // to force errors.
bhTrans := wire.NewBlockHeader(&hash, &merkleHash, bits, nonce) bhTrans := NewBlockHeader(&hash, &merkleHash, bits, nonce)
bhTrans.Version = blockOne.Header.Version bhTrans.Version = blockOne.Header.Version
bhTrans.Timestamp = blockOne.Header.Timestamp bhTrans.Timestamp = blockOne.Header.Timestamp
transHeader := wire.NewMsgHeaders() transHeader := NewMsgHeaders()
transHeader.AddBlockHeader(bhTrans) transHeader.AddBlockHeader(bhTrans)
transHeaderEncoded := []byte{ transHeaderEncoded := []byte{
0x01, // VarInt for number of headers. 0x01, // VarInt for number of headers.
@ -285,12 +284,12 @@ func TestHeadersWireErrors(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgHeaders // Value to encode in *MsgHeaders // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Latest protocol version with intentional read/write errors. // Latest protocol version with intentional read/write errors.
// Force error in header count. // Force error in header count.
@ -316,9 +315,9 @@ func TestHeadersWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -327,7 +326,7 @@ func TestHeadersWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgHeaders var msg MsgHeaders
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -336,9 +335,9 @@ func TestHeadersWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -10,17 +10,16 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestInv tests the MsgInv API. // TestInv tests the MsgInv API.
func TestInv(t *testing.T) { func TestInv(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "inv" wantCmd := "inv"
msg := wire.NewMsgInv() msg := NewMsgInv()
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgInv: wrong command - got %v want %v", t.Errorf("NewMsgInv: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -37,8 +36,8 @@ func TestInv(t *testing.T) {
} }
// Ensure inventory vectors are added properly. // Ensure inventory vectors are added properly.
hash := wire.ShaHash{} hash := ShaHash{}
iv := wire.NewInvVect(wire.InvTypeBlock, &hash) iv := NewInvVect(InvTypeBlock, &hash)
err := msg.AddInvVect(iv) err := msg.AddInvVect(iv)
if err != nil { if err != nil {
t.Errorf("AddInvVect: %v", err) t.Errorf("AddInvVect: %v", err)
@ -50,7 +49,7 @@ func TestInv(t *testing.T) {
// Ensure adding more than the max allowed inventory vectors per // Ensure adding more than the max allowed inventory vectors per
// message returns an error. // message returns an error.
for i := 0; i < wire.MaxInvPerMsg; i++ { for i := 0; i < MaxInvPerMsg; i++ {
err = msg.AddInvVect(iv) err = msg.AddInvVect(iv)
} }
if err == nil { if err == nil {
@ -60,8 +59,8 @@ func TestInv(t *testing.T) {
// Ensure creating the message with a size hint larger than the max // Ensure creating the message with a size hint larger than the max
// works as expected. // works as expected.
msg = wire.NewMsgInvSizeHint(wire.MaxInvPerMsg + 1) msg = NewMsgInvSizeHint(MaxInvPerMsg + 1)
wantCap := wire.MaxInvPerMsg wantCap := MaxInvPerMsg
if cap(msg.InvList) != wantCap { if cap(msg.InvList) != wantCap {
t.Errorf("NewMsgInvSizeHint: wrong cap for size hint - "+ t.Errorf("NewMsgInvSizeHint: wrong cap for size hint - "+
"got %v, want %v", cap(msg.InvList), wantCap) "got %v, want %v", cap(msg.InvList), wantCap)
@ -75,29 +74,29 @@ func TestInv(t *testing.T) {
func TestInvWire(t *testing.T) { func TestInvWire(t *testing.T) {
// Block 203707 hash. // Block 203707 hash.
hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc" hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc"
blockHash, err := wire.NewShaHashFromStr(hashStr) blockHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Transation 1 of Block 203707 hash. // Transation 1 of Block 203707 hash.
hashStr = "d28a3dc7392bf00a9855ee93dd9a81eff82a2c4fe57fbd42cfe71b487accfaf0" hashStr = "d28a3dc7392bf00a9855ee93dd9a81eff82a2c4fe57fbd42cfe71b487accfaf0"
txHash, err := wire.NewShaHashFromStr(hashStr) txHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
iv := wire.NewInvVect(wire.InvTypeBlock, blockHash) iv := NewInvVect(InvTypeBlock, blockHash)
iv2 := wire.NewInvVect(wire.InvTypeTx, txHash) iv2 := NewInvVect(InvTypeTx, txHash)
// Empty inv message. // Empty inv message.
NoInv := wire.NewMsgInv() NoInv := NewMsgInv()
NoInvEncoded := []byte{ NoInvEncoded := []byte{
0x00, // Varint for number of inventory vectors 0x00, // Varint for number of inventory vectors
} }
// Inv message with multiple inventory vectors. // Inv message with multiple inventory vectors.
MultiInv := wire.NewMsgInv() MultiInv := NewMsgInv()
MultiInv.AddInvVect(iv) MultiInv.AddInvVect(iv)
MultiInv.AddInvVect(iv2) MultiInv.AddInvVect(iv2)
MultiInvEncoded := []byte{ MultiInvEncoded := []byte{
@ -115,17 +114,17 @@ func TestInvWire(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgInv // Message to encode in *MsgInv // Message to encode
out *wire.MsgInv // Expected decoded message out *MsgInv // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version with no inv vectors. // Latest protocol version with no inv vectors.
{ {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Latest protocol version with multiple inv vectors. // Latest protocol version with multiple inv vectors.
@ -133,7 +132,7 @@ func TestInvWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version no inv vectors. // Protocol version BIP0035Version no inv vectors.
@ -141,7 +140,7 @@ func TestInvWire(t *testing.T) {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0035Version with multiple inv vectors. // Protocol version BIP0035Version with multiple inv vectors.
@ -149,7 +148,7 @@ func TestInvWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version no inv vectors. // Protocol version BIP0031Version no inv vectors.
@ -157,7 +156,7 @@ func TestInvWire(t *testing.T) {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version BIP0031Version with multiple inv vectors. // Protocol version BIP0031Version with multiple inv vectors.
@ -165,7 +164,7 @@ func TestInvWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion no inv vectors. // Protocol version NetAddressTimeVersion no inv vectors.
@ -173,7 +172,7 @@ func TestInvWire(t *testing.T) {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version NetAddressTimeVersion with multiple inv vectors. // Protocol version NetAddressTimeVersion with multiple inv vectors.
@ -181,7 +180,7 @@ func TestInvWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion no inv vectors. // Protocol version MultipleAddressVersion no inv vectors.
@ -189,7 +188,7 @@ func TestInvWire(t *testing.T) {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
// Protocol version MultipleAddressVersion with multiple inv vectors. // Protocol version MultipleAddressVersion with multiple inv vectors.
@ -197,7 +196,7 @@ func TestInvWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -217,7 +216,7 @@ func TestInvWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgInv var msg MsgInv
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -235,20 +234,20 @@ func TestInvWire(t *testing.T) {
// TestInvWireErrors performs negative tests against wire encode and decode // TestInvWireErrors performs negative tests against wire encode and decode
// of MsgInv to confirm error paths work correctly. // of MsgInv to confirm error paths work correctly.
func TestInvWireErrors(t *testing.T) { func TestInvWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
wireErr := &wire.MessageError{} wireErr := &MessageError{}
// Block 203707 hash. // Block 203707 hash.
hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc" hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc"
blockHash, err := wire.NewShaHashFromStr(hashStr) blockHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
iv := wire.NewInvVect(wire.InvTypeBlock, blockHash) iv := NewInvVect(InvTypeBlock, blockHash)
// Base inv message used to induce errors. // Base inv message used to induce errors.
baseInv := wire.NewMsgInv() baseInv := NewMsgInv()
baseInv.AddInvVect(iv) baseInv.AddInvVect(iv)
baseInvEncoded := []byte{ baseInvEncoded := []byte{
0x02, // Varint for number of inv vectors 0x02, // Varint for number of inv vectors
@ -261,8 +260,8 @@ func TestInvWireErrors(t *testing.T) {
// Inv message that forces an error by having more than the max allowed // Inv message that forces an error by having more than the max allowed
// inv vectors. // inv vectors.
maxInv := wire.NewMsgInv() maxInv := NewMsgInv()
for i := 0; i < wire.MaxInvPerMsg; i++ { for i := 0; i < MaxInvPerMsg; i++ {
maxInv.AddInvVect(iv) maxInv.AddInvVect(iv)
} }
maxInv.InvList = append(maxInv.InvList, iv) maxInv.InvList = append(maxInv.InvList, iv)
@ -271,12 +270,12 @@ func TestInvWireErrors(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgInv // Value to encode in *MsgInv // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Latest protocol version with intentional read/write errors. // Latest protocol version with intentional read/write errors.
// Force error in inventory vector count // Force error in inventory vector count
@ -298,9 +297,9 @@ func TestInvWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -309,7 +308,7 @@ func TestInvWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgInv var msg MsgInv
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -318,9 +317,9 @@ func TestInvWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View file

@ -1,22 +1,20 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
) )
func TestMemPool(t *testing.T) { func TestMemPool(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "mempool" wantCmd := "mempool"
msg := wire.NewMsgMemPool() msg := NewMsgMemPool()
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgMemPool: wrong command - got %v want %v", t.Errorf("NewMsgMemPool: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -40,7 +38,7 @@ func TestMemPool(t *testing.T) {
// Older protocol versions should fail encode since message didn't // Older protocol versions should fail encode since message didn't
// exist yet. // exist yet.
oldPver := wire.BIP0035Version - 1 oldPver := BIP0035Version - 1
err = msg.BtcEncode(&buf, oldPver) err = msg.BtcEncode(&buf, oldPver)
if err == nil { if err == nil {
s := "encode of MsgMemPool passed for old protocol version %v err <%v>" s := "encode of MsgMemPool passed for old protocol version %v err <%v>"
@ -48,7 +46,7 @@ func TestMemPool(t *testing.T) {
} }
// Test decode with latest protocol version. // Test decode with latest protocol version.
readmsg := wire.NewMsgMemPool() readmsg := NewMsgMemPool()
err = readmsg.BtcDecode(&buf, pver) err = readmsg.BtcDecode(&buf, pver)
if err != nil { if err != nil {
t.Errorf("decode of MsgMemPool failed [%v] err <%v>", buf, err) t.Errorf("decode of MsgMemPool failed [%v] err <%v>", buf, err)

View file

@ -1,8 +1,8 @@
// Copyright (c) 2014-2015 The btcsuite developers // Copyright (c) 2014-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -12,24 +12,23 @@ import (
"testing" "testing"
"time" "time"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestMerkleBlock tests the MsgMerkleBlock API. // TestMerkleBlock tests the MsgMerkleBlock API.
func TestMerkleBlock(t *testing.T) { func TestMerkleBlock(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Block 1 header. // Block 1 header.
prevHash := &blockOne.Header.PrevBlock prevHash := &blockOne.Header.PrevBlock
merkleHash := &blockOne.Header.MerkleRoot merkleHash := &blockOne.Header.MerkleRoot
bits := blockOne.Header.Bits bits := blockOne.Header.Bits
nonce := blockOne.Header.Nonce nonce := blockOne.Header.Nonce
bh := wire.NewBlockHeader(prevHash, merkleHash, bits, nonce) bh := NewBlockHeader(prevHash, merkleHash, bits, nonce)
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "merkleblock" wantCmd := "merkleblock"
msg := wire.NewMsgMerkleBlock(bh) msg := NewMsgMerkleBlock(bh)
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgBlock: wrong command - got %v want %v", t.Errorf("NewMsgBlock: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -47,9 +46,9 @@ func TestMerkleBlock(t *testing.T) {
// Load maxTxPerBlock hashes // Load maxTxPerBlock hashes
data := make([]byte, 32) data := make([]byte, 32)
for i := 0; i < wire.MaxTxPerBlock; i++ { for i := 0; i < maxTxPerBlock; i++ {
rand.Read(data) rand.Read(data)
hash, err := wire.NewShaHash(data) hash, err := NewShaHash(data)
if err != nil { if err != nil {
t.Errorf("NewShaHash failed: %v\n", err) t.Errorf("NewShaHash failed: %v\n", err)
return return
@ -63,7 +62,7 @@ func TestMerkleBlock(t *testing.T) {
// Add one more Tx to test failure. // Add one more Tx to test failure.
rand.Read(data) rand.Read(data)
hash, err := wire.NewShaHash(data) hash, err := NewShaHash(data)
if err != nil { if err != nil {
t.Errorf("NewShaHash failed: %v\n", err) t.Errorf("NewShaHash failed: %v\n", err)
return return
@ -82,7 +81,7 @@ func TestMerkleBlock(t *testing.T) {
} }
// Test decode with latest protocol version. // Test decode with latest protocol version.
readmsg := wire.MsgMerkleBlock{} readmsg := MsgMerkleBlock{}
err = readmsg.BtcDecode(&buf, pver) err = readmsg.BtcDecode(&buf, pver)
if err != nil { if err != nil {
t.Errorf("decode of MsgMerkleBlock failed [%v] err <%v>", buf, err) t.Errorf("decode of MsgMerkleBlock failed [%v] err <%v>", buf, err)
@ -100,7 +99,7 @@ func TestMerkleBlock(t *testing.T) {
// Force too many flag bytes to test maxFlagsPerMerkleBlock. // Force too many flag bytes to test maxFlagsPerMerkleBlock.
// Reset the number of hashes back to a valid value. // Reset the number of hashes back to a valid value.
msg.Hashes = msg.Hashes[len(msg.Hashes)-1:] msg.Hashes = msg.Hashes[len(msg.Hashes)-1:]
msg.Flags = make([]byte, wire.MaxFlagsPerMerkleBlock+1) msg.Flags = make([]byte, maxFlagsPerMerkleBlock+1)
err = msg.BtcEncode(&buf, pver) err = msg.BtcEncode(&buf, pver)
if err == nil { if err == nil {
t.Errorf("encode of MsgMerkleBlock succeeded with too many " + t.Errorf("encode of MsgMerkleBlock succeeded with too many " +
@ -117,21 +116,21 @@ func TestMerkleBlockCrossProtocol(t *testing.T) {
merkleHash := &blockOne.Header.MerkleRoot merkleHash := &blockOne.Header.MerkleRoot
bits := blockOne.Header.Bits bits := blockOne.Header.Bits
nonce := blockOne.Header.Nonce nonce := blockOne.Header.Nonce
bh := wire.NewBlockHeader(prevHash, merkleHash, bits, nonce) bh := NewBlockHeader(prevHash, merkleHash, bits, nonce)
msg := wire.NewMsgMerkleBlock(bh) msg := NewMsgMerkleBlock(bh)
// Encode with latest protocol version. // Encode with latest protocol version.
var buf bytes.Buffer var buf bytes.Buffer
err := msg.BtcEncode(&buf, wire.ProtocolVersion) err := msg.BtcEncode(&buf, ProtocolVersion)
if err != nil { if err != nil {
t.Errorf("encode of NewMsgFilterLoad failed %v err <%v>", msg, t.Errorf("encode of NewMsgFilterLoad failed %v err <%v>", msg,
err) err)
} }
// Decode with old protocol version. // Decode with old protocol version.
var readmsg wire.MsgFilterLoad var readmsg MsgFilterLoad
err = readmsg.BtcDecode(&buf, wire.BIP0031Version) err = readmsg.BtcDecode(&buf, BIP0031Version)
if err == nil { if err == nil {
t.Errorf("decode of MsgFilterLoad succeeded when it shouldn't have %v", t.Errorf("decode of MsgFilterLoad succeeded when it shouldn't have %v",
msg) msg)
@ -142,21 +141,21 @@ func TestMerkleBlockCrossProtocol(t *testing.T) {
// various numbers of transaction hashes and protocol versions. // various numbers of transaction hashes and protocol versions.
func TestMerkleBlockWire(t *testing.T) { func TestMerkleBlockWire(t *testing.T) {
tests := []struct { tests := []struct {
in *wire.MsgMerkleBlock // Message to encode in *MsgMerkleBlock // Message to encode
out *wire.MsgMerkleBlock // Expected decoded message out *MsgMerkleBlock // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
&merkleBlockOne, &merkleBlockOne, merkleBlockOneBytes, &merkleBlockOne, &merkleBlockOne, merkleBlockOneBytes,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0037Version. // Protocol version BIP0037Version.
{ {
&merkleBlockOne, &merkleBlockOne, merkleBlockOneBytes, &merkleBlockOne, &merkleBlockOne, merkleBlockOneBytes,
wire.BIP0037Version, BIP0037Version,
}, },
} }
@ -176,7 +175,7 @@ func TestMerkleBlockWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgMerkleBlock var msg MsgMerkleBlock
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -198,16 +197,16 @@ func TestMerkleBlockWireErrors(t *testing.T) {
// because the test data is using bytes encoded with that protocol // because the test data is using bytes encoded with that protocol
// version. // version.
pver := uint32(70001) pver := uint32(70001)
pverNoMerkleBlock := wire.BIP0037Version - 1 pverNoMerkleBlock := BIP0037Version - 1
wireErr := &wire.MessageError{} wireErr := &MessageError{}
tests := []struct { tests := []struct {
in *wire.MsgMerkleBlock // Value to encode in *MsgMerkleBlock // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Force error in version. // Force error in version.
{ {
@ -282,9 +281,9 @@ func TestMerkleBlockWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -293,7 +292,7 @@ func TestMerkleBlockWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgMerkleBlock var msg MsgMerkleBlock
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -302,9 +301,9 @@ func TestMerkleBlockWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)
@ -327,7 +326,7 @@ func TestMerkleBlockOverflowErrors(t *testing.T) {
// Create bytes for a merkle block that claims to have more than the max // Create bytes for a merkle block that claims to have more than the max
// allowed tx hashes. // allowed tx hashes.
var buf bytes.Buffer var buf bytes.Buffer
wire.TstWriteVarInt(&buf, pver, wire.MaxTxPerBlock+1) WriteVarInt(&buf, pver, maxTxPerBlock+1)
numHashesOffset := 84 numHashesOffset := 84
exceedMaxHashes := make([]byte, numHashesOffset) exceedMaxHashes := make([]byte, numHashesOffset)
copy(exceedMaxHashes, merkleBlockOneBytes[:numHashesOffset]) copy(exceedMaxHashes, merkleBlockOneBytes[:numHashesOffset])
@ -336,7 +335,7 @@ func TestMerkleBlockOverflowErrors(t *testing.T) {
// Create bytes for a merkle block that claims to have more than the max // Create bytes for a merkle block that claims to have more than the max
// allowed flag bytes. // allowed flag bytes.
buf.Reset() buf.Reset()
wire.TstWriteVarInt(&buf, pver, wire.MaxFlagsPerMerkleBlock+1) WriteVarInt(&buf, pver, maxFlagsPerMerkleBlock+1)
numFlagBytesOffset := 117 numFlagBytesOffset := 117
exceedMaxFlagBytes := make([]byte, numFlagBytesOffset) exceedMaxFlagBytes := make([]byte, numFlagBytesOffset)
copy(exceedMaxFlagBytes, merkleBlockOneBytes[:numFlagBytesOffset]) copy(exceedMaxFlagBytes, merkleBlockOneBytes[:numFlagBytesOffset])
@ -348,15 +347,15 @@ func TestMerkleBlockOverflowErrors(t *testing.T) {
err error // Expected error err error // Expected error
}{ }{
// Block that claims to have more than max allowed hashes. // Block that claims to have more than max allowed hashes.
{exceedMaxHashes, pver, &wire.MessageError{}}, {exceedMaxHashes, pver, &MessageError{}},
// Block that claims to have more than max allowed flag bytes. // Block that claims to have more than max allowed flag bytes.
{exceedMaxFlagBytes, pver, &wire.MessageError{}}, {exceedMaxFlagBytes, pver, &MessageError{}},
} }
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Decode from wire format. // Decode from wire format.
var msg wire.MsgMerkleBlock var msg MsgMerkleBlock
r := bytes.NewReader(test.buf) r := bytes.NewReader(test.buf)
err := msg.BtcDecode(r, test.pver) err := msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) { if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
@ -369,16 +368,16 @@ func TestMerkleBlockOverflowErrors(t *testing.T) {
// merkleBlockOne is a merkle block created from block one of the block chain // merkleBlockOne is a merkle block created from block one of the block chain
// where the first transaction matches. // where the first transaction matches.
var merkleBlockOne = wire.MsgMerkleBlock{ var merkleBlockOne = MsgMerkleBlock{
Header: wire.BlockHeader{ Header: BlockHeader{
Version: 1, Version: 1,
PrevBlock: wire.ShaHash([wire.HashSize]byte{ // Make go vet happy. PrevBlock: ShaHash([HashSize]byte{ // Make go vet happy.
0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72, 0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f, 0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f,
0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c, 0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
}), }),
MerkleRoot: wire.ShaHash([wire.HashSize]byte{ // Make go vet happy. MerkleRoot: ShaHash([HashSize]byte{ // Make go vet happy.
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44, 0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67, 0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1, 0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,
@ -389,8 +388,8 @@ var merkleBlockOne = wire.MsgMerkleBlock{
Nonce: 0x9962e301, // 2573394689 Nonce: 0x9962e301, // 2573394689
}, },
Transactions: 1, Transactions: 1,
Hashes: []*wire.ShaHash{ Hashes: []*ShaHash{
(*wire.ShaHash)(&[wire.HashSize]byte{ // Make go vet happy. (*ShaHash)(&[HashSize]byte{ // Make go vet happy.
0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44, 0x98, 0x20, 0x51, 0xfd, 0x1e, 0x4b, 0xa7, 0x44,
0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67, 0xbb, 0xbe, 0x68, 0x0e, 0x1f, 0xee, 0x14, 0x67,
0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1, 0x7b, 0xa1, 0xa3, 0xc3, 0x54, 0x0b, 0xf7, 0xb1,

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -10,17 +10,16 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestNotFound tests the MsgNotFound API. // TestNotFound tests the MsgNotFound API.
func TestNotFound(t *testing.T) { func TestNotFound(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "notfound" wantCmd := "notfound"
msg := wire.NewMsgNotFound() msg := NewMsgNotFound()
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgNotFound: wrong command - got %v want %v", t.Errorf("NewMsgNotFound: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -37,8 +36,8 @@ func TestNotFound(t *testing.T) {
} }
// Ensure inventory vectors are added properly. // Ensure inventory vectors are added properly.
hash := wire.ShaHash{} hash := ShaHash{}
iv := wire.NewInvVect(wire.InvTypeBlock, &hash) iv := NewInvVect(InvTypeBlock, &hash)
err := msg.AddInvVect(iv) err := msg.AddInvVect(iv)
if err != nil { if err != nil {
t.Errorf("AddInvVect: %v", err) t.Errorf("AddInvVect: %v", err)
@ -50,7 +49,7 @@ func TestNotFound(t *testing.T) {
// Ensure adding more than the max allowed inventory vectors per // Ensure adding more than the max allowed inventory vectors per
// message returns an error. // message returns an error.
for i := 0; i < wire.MaxInvPerMsg; i++ { for i := 0; i < MaxInvPerMsg; i++ {
err = msg.AddInvVect(iv) err = msg.AddInvVect(iv)
} }
if err == nil { if err == nil {
@ -66,29 +65,29 @@ func TestNotFound(t *testing.T) {
func TestNotFoundWire(t *testing.T) { func TestNotFoundWire(t *testing.T) {
// Block 203707 hash. // Block 203707 hash.
hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc" hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc"
blockHash, err := wire.NewShaHashFromStr(hashStr) blockHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Transation 1 of Block 203707 hash. // Transation 1 of Block 203707 hash.
hashStr = "d28a3dc7392bf00a9855ee93dd9a81eff82a2c4fe57fbd42cfe71b487accfaf0" hashStr = "d28a3dc7392bf00a9855ee93dd9a81eff82a2c4fe57fbd42cfe71b487accfaf0"
txHash, err := wire.NewShaHashFromStr(hashStr) txHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
iv := wire.NewInvVect(wire.InvTypeBlock, blockHash) iv := NewInvVect(InvTypeBlock, blockHash)
iv2 := wire.NewInvVect(wire.InvTypeTx, txHash) iv2 := NewInvVect(InvTypeTx, txHash)
// Empty notfound message. // Empty notfound message.
NoInv := wire.NewMsgNotFound() NoInv := NewMsgNotFound()
NoInvEncoded := []byte{ NoInvEncoded := []byte{
0x00, // Varint for number of inventory vectors 0x00, // Varint for number of inventory vectors
} }
// NotFound message with multiple inventory vectors. // NotFound message with multiple inventory vectors.
MultiInv := wire.NewMsgNotFound() MultiInv := NewMsgNotFound()
MultiInv.AddInvVect(iv) MultiInv.AddInvVect(iv)
MultiInv.AddInvVect(iv2) MultiInv.AddInvVect(iv2)
MultiInvEncoded := []byte{ MultiInvEncoded := []byte{
@ -106,17 +105,17 @@ func TestNotFoundWire(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgNotFound // Message to encode in *MsgNotFound // Message to encode
out *wire.MsgNotFound // Expected decoded message out *MsgNotFound // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version with no inv vectors. // Latest protocol version with no inv vectors.
{ {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Latest protocol version with multiple inv vectors. // Latest protocol version with multiple inv vectors.
@ -124,7 +123,7 @@ func TestNotFoundWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version no inv vectors. // Protocol version BIP0035Version no inv vectors.
@ -132,7 +131,7 @@ func TestNotFoundWire(t *testing.T) {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0035Version with multiple inv vectors. // Protocol version BIP0035Version with multiple inv vectors.
@ -140,7 +139,7 @@ func TestNotFoundWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version no inv vectors. // Protocol version BIP0031Version no inv vectors.
@ -148,7 +147,7 @@ func TestNotFoundWire(t *testing.T) {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version BIP0031Version with multiple inv vectors. // Protocol version BIP0031Version with multiple inv vectors.
@ -156,7 +155,7 @@ func TestNotFoundWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion no inv vectors. // Protocol version NetAddressTimeVersion no inv vectors.
@ -164,7 +163,7 @@ func TestNotFoundWire(t *testing.T) {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version NetAddressTimeVersion with multiple inv vectors. // Protocol version NetAddressTimeVersion with multiple inv vectors.
@ -172,7 +171,7 @@ func TestNotFoundWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion no inv vectors. // Protocol version MultipleAddressVersion no inv vectors.
@ -180,7 +179,7 @@ func TestNotFoundWire(t *testing.T) {
NoInv, NoInv,
NoInv, NoInv,
NoInvEncoded, NoInvEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
// Protocol version MultipleAddressVersion with multiple inv vectors. // Protocol version MultipleAddressVersion with multiple inv vectors.
@ -188,7 +187,7 @@ func TestNotFoundWire(t *testing.T) {
MultiInv, MultiInv,
MultiInv, MultiInv,
MultiInvEncoded, MultiInvEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -208,7 +207,7 @@ func TestNotFoundWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgNotFound var msg MsgNotFound
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -226,20 +225,20 @@ func TestNotFoundWire(t *testing.T) {
// TestNotFoundWireErrors performs negative tests against wire encode and decode // TestNotFoundWireErrors performs negative tests against wire encode and decode
// of MsgNotFound to confirm error paths work correctly. // of MsgNotFound to confirm error paths work correctly.
func TestNotFoundWireErrors(t *testing.T) { func TestNotFoundWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
wireErr := &wire.MessageError{} wireErr := &MessageError{}
// Block 203707 hash. // Block 203707 hash.
hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc" hashStr := "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc"
blockHash, err := wire.NewShaHashFromStr(hashStr) blockHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
iv := wire.NewInvVect(wire.InvTypeBlock, blockHash) iv := NewInvVect(InvTypeBlock, blockHash)
// Base message used to induce errors. // Base message used to induce errors.
baseNotFound := wire.NewMsgNotFound() baseNotFound := NewMsgNotFound()
baseNotFound.AddInvVect(iv) baseNotFound.AddInvVect(iv)
baseNotFoundEncoded := []byte{ baseNotFoundEncoded := []byte{
0x02, // Varint for number of inv vectors 0x02, // Varint for number of inv vectors
@ -252,8 +251,8 @@ func TestNotFoundWireErrors(t *testing.T) {
// Message that forces an error by having more than the max allowed inv // Message that forces an error by having more than the max allowed inv
// vectors. // vectors.
maxNotFound := wire.NewMsgNotFound() maxNotFound := NewMsgNotFound()
for i := 0; i < wire.MaxInvPerMsg; i++ { for i := 0; i < MaxInvPerMsg; i++ {
maxNotFound.AddInvVect(iv) maxNotFound.AddInvVect(iv)
} }
maxNotFound.InvList = append(maxNotFound.InvList, iv) maxNotFound.InvList = append(maxNotFound.InvList, iv)
@ -262,12 +261,12 @@ func TestNotFoundWireErrors(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgNotFound // Value to encode in *MsgNotFound // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Force error in inventory vector count // Force error in inventory vector count
{baseNotFound, baseNotFoundEncoded, pver, 0, io.ErrShortWrite, io.EOF}, {baseNotFound, baseNotFoundEncoded, pver, 0, io.ErrShortWrite, io.EOF},
@ -288,9 +287,9 @@ func TestNotFoundWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -299,7 +298,7 @@ func TestNotFoundWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgNotFound var msg MsgNotFound
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -308,9 +307,9 @@ func TestNotFoundWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -10,20 +10,19 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestPing tests the MsgPing API against the latest protocol version. // TestPing tests the MsgPing API against the latest protocol version.
func TestPing(t *testing.T) { func TestPing(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Ensure we get the same nonce back out. // Ensure we get the same nonce back out.
nonce, err := wire.RandomUint64() nonce, err := RandomUint64()
if err != nil { if err != nil {
t.Errorf("RandomUint64: Error generating nonce: %v", err) t.Errorf("RandomUint64: Error generating nonce: %v", err)
} }
msg := wire.NewMsgPing(nonce) msg := NewMsgPing(nonce)
if msg.Nonce != nonce { if msg.Nonce != nonce {
t.Errorf("NewMsgPing: wrong nonce - got %v, want %v", t.Errorf("NewMsgPing: wrong nonce - got %v, want %v",
msg.Nonce, nonce) msg.Nonce, nonce)
@ -52,13 +51,13 @@ func TestPing(t *testing.T) {
// BIP0031Version. // BIP0031Version.
func TestPingBIP0031(t *testing.T) { func TestPingBIP0031(t *testing.T) {
// Use the protocol version just prior to BIP0031Version changes. // Use the protocol version just prior to BIP0031Version changes.
pver := wire.BIP0031Version pver := BIP0031Version
nonce, err := wire.RandomUint64() nonce, err := RandomUint64()
if err != nil { if err != nil {
t.Errorf("RandomUint64: Error generating nonce: %v", err) t.Errorf("RandomUint64: Error generating nonce: %v", err)
} }
msg := wire.NewMsgPing(nonce) msg := NewMsgPing(nonce)
if msg.Nonce != nonce { if msg.Nonce != nonce {
t.Errorf("NewMsgPing: wrong nonce - got %v, want %v", t.Errorf("NewMsgPing: wrong nonce - got %v, want %v",
msg.Nonce, nonce) msg.Nonce, nonce)
@ -81,7 +80,7 @@ func TestPingBIP0031(t *testing.T) {
} }
// Test decode with old protocol version. // Test decode with old protocol version.
readmsg := wire.NewMsgPing(0) readmsg := NewMsgPing(0)
err = readmsg.BtcDecode(&buf, pver) err = readmsg.BtcDecode(&buf, pver)
if err != nil { if err != nil {
t.Errorf("decode of MsgPing failed [%v] err <%v>", buf, err) t.Errorf("decode of MsgPing failed [%v] err <%v>", buf, err)
@ -99,11 +98,11 @@ func TestPingBIP0031(t *testing.T) {
// TestPingCrossProtocol tests the MsgPing API when encoding with the latest // TestPingCrossProtocol tests the MsgPing API when encoding with the latest
// protocol version and decoding with BIP0031Version. // protocol version and decoding with BIP0031Version.
func TestPingCrossProtocol(t *testing.T) { func TestPingCrossProtocol(t *testing.T) {
nonce, err := wire.RandomUint64() nonce, err := RandomUint64()
if err != nil { if err != nil {
t.Errorf("RandomUint64: Error generating nonce: %v", err) t.Errorf("RandomUint64: Error generating nonce: %v", err)
} }
msg := wire.NewMsgPing(nonce) msg := NewMsgPing(nonce)
if msg.Nonce != nonce { if msg.Nonce != nonce {
t.Errorf("NewMsgPing: wrong nonce - got %v, want %v", t.Errorf("NewMsgPing: wrong nonce - got %v, want %v",
msg.Nonce, nonce) msg.Nonce, nonce)
@ -111,14 +110,14 @@ func TestPingCrossProtocol(t *testing.T) {
// Encode with latest protocol version. // Encode with latest protocol version.
var buf bytes.Buffer var buf bytes.Buffer
err = msg.BtcEncode(&buf, wire.ProtocolVersion) err = msg.BtcEncode(&buf, ProtocolVersion)
if err != nil { if err != nil {
t.Errorf("encode of MsgPing failed %v err <%v>", msg, err) t.Errorf("encode of MsgPing failed %v err <%v>", msg, err)
} }
// Decode with old protocol version. // Decode with old protocol version.
readmsg := wire.NewMsgPing(0) readmsg := NewMsgPing(0)
err = readmsg.BtcDecode(&buf, wire.BIP0031Version) err = readmsg.BtcDecode(&buf, BIP0031Version)
if err != nil { if err != nil {
t.Errorf("decode of MsgPing failed [%v] err <%v>", buf, err) t.Errorf("decode of MsgPing failed [%v] err <%v>", buf, err)
} }
@ -134,33 +133,33 @@ func TestPingCrossProtocol(t *testing.T) {
// versions. // versions.
func TestPingWire(t *testing.T) { func TestPingWire(t *testing.T) {
tests := []struct { tests := []struct {
in wire.MsgPing // Message to encode in MsgPing // Message to encode
out wire.MsgPing // Expected decoded message out MsgPing // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
wire.MsgPing{Nonce: 123123}, // 0x1e0f3 MsgPing{Nonce: 123123}, // 0x1e0f3
wire.MsgPing{Nonce: 123123}, // 0x1e0f3 MsgPing{Nonce: 123123}, // 0x1e0f3
[]byte{0xf3, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0xf3, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00},
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0031Version+1 // Protocol version BIP0031Version+1
{ {
wire.MsgPing{Nonce: 456456}, // 0x6f708 MsgPing{Nonce: 456456}, // 0x6f708
wire.MsgPing{Nonce: 456456}, // 0x6f708 MsgPing{Nonce: 456456}, // 0x6f708
[]byte{0x08, 0xf7, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x08, 0xf7, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00},
wire.BIP0031Version + 1, BIP0031Version + 1,
}, },
// Protocol version BIP0031Version // Protocol version BIP0031Version
{ {
wire.MsgPing{Nonce: 789789}, // 0xc0d1d MsgPing{Nonce: 789789}, // 0xc0d1d
wire.MsgPing{Nonce: 0}, // No nonce for pver MsgPing{Nonce: 0}, // No nonce for pver
[]byte{}, // No nonce for pver []byte{}, // No nonce for pver
wire.BIP0031Version, BIP0031Version,
}, },
} }
@ -180,7 +179,7 @@ func TestPingWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgPing var msg MsgPing
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -198,19 +197,19 @@ func TestPingWire(t *testing.T) {
// TestPingWireErrors performs negative tests against wire encode and decode // TestPingWireErrors performs negative tests against wire encode and decode
// of MsgPing to confirm error paths work correctly. // of MsgPing to confirm error paths work correctly.
func TestPingWireErrors(t *testing.T) { func TestPingWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
tests := []struct { tests := []struct {
in *wire.MsgPing // Value to encode in *MsgPing // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Latest protocol version with intentional read/write errors. // Latest protocol version with intentional read/write errors.
{ {
&wire.MsgPing{Nonce: 123123}, // 0x1e0f3 &MsgPing{Nonce: 123123}, // 0x1e0f3
[]byte{0xf3, 0xe0, 0x01, 0x00}, []byte{0xf3, 0xe0, 0x01, 0x00},
pver, pver,
2, 2,
@ -231,7 +230,7 @@ func TestPingWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgPing var msg MsgPing
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if err != test.readErr { if err != test.readErr {

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -10,19 +10,18 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestPongLatest tests the MsgPong API against the latest protocol version. // TestPongLatest tests the MsgPong API against the latest protocol version.
func TestPongLatest(t *testing.T) { func TestPongLatest(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
nonce, err := wire.RandomUint64() nonce, err := RandomUint64()
if err != nil { if err != nil {
t.Errorf("RandomUint64: error generating nonce: %v", err) t.Errorf("RandomUint64: error generating nonce: %v", err)
} }
msg := wire.NewMsgPong(nonce) msg := NewMsgPong(nonce)
if msg.Nonce != nonce { if msg.Nonce != nonce {
t.Errorf("NewMsgPong: wrong nonce - got %v, want %v", t.Errorf("NewMsgPong: wrong nonce - got %v, want %v",
msg.Nonce, nonce) msg.Nonce, nonce)
@ -52,7 +51,7 @@ func TestPongLatest(t *testing.T) {
} }
// Test decode with latest protocol version. // Test decode with latest protocol version.
readmsg := wire.NewMsgPong(0) readmsg := NewMsgPong(0)
err = readmsg.BtcDecode(&buf, pver) err = readmsg.BtcDecode(&buf, pver)
if err != nil { if err != nil {
t.Errorf("decode of MsgPong failed [%v] err <%v>", buf, err) t.Errorf("decode of MsgPong failed [%v] err <%v>", buf, err)
@ -70,13 +69,13 @@ func TestPongLatest(t *testing.T) {
// BIP0031Version. // BIP0031Version.
func TestPongBIP0031(t *testing.T) { func TestPongBIP0031(t *testing.T) {
// Use the protocol version just prior to BIP0031Version changes. // Use the protocol version just prior to BIP0031Version changes.
pver := wire.BIP0031Version pver := BIP0031Version
nonce, err := wire.RandomUint64() nonce, err := RandomUint64()
if err != nil { if err != nil {
t.Errorf("Error generating nonce: %v", err) t.Errorf("Error generating nonce: %v", err)
} }
msg := wire.NewMsgPong(nonce) msg := NewMsgPong(nonce)
if msg.Nonce != nonce { if msg.Nonce != nonce {
t.Errorf("Should get same nonce back out.") t.Errorf("Should get same nonce back out.")
} }
@ -97,7 +96,7 @@ func TestPongBIP0031(t *testing.T) {
} }
// Test decode with old protocol version. // Test decode with old protocol version.
readmsg := wire.NewMsgPong(0) readmsg := NewMsgPong(0)
err = readmsg.BtcDecode(&buf, pver) err = readmsg.BtcDecode(&buf, pver)
if err == nil { if err == nil {
t.Errorf("decode of MsgPong succeeded when it shouldn't have %v", t.Errorf("decode of MsgPong succeeded when it shouldn't have %v",
@ -116,25 +115,25 @@ func TestPongBIP0031(t *testing.T) {
// TestPongCrossProtocol tests the MsgPong API when encoding with the latest // TestPongCrossProtocol tests the MsgPong API when encoding with the latest
// protocol version and decoding with BIP0031Version. // protocol version and decoding with BIP0031Version.
func TestPongCrossProtocol(t *testing.T) { func TestPongCrossProtocol(t *testing.T) {
nonce, err := wire.RandomUint64() nonce, err := RandomUint64()
if err != nil { if err != nil {
t.Errorf("Error generating nonce: %v", err) t.Errorf("Error generating nonce: %v", err)
} }
msg := wire.NewMsgPong(nonce) msg := NewMsgPong(nonce)
if msg.Nonce != nonce { if msg.Nonce != nonce {
t.Errorf("Should get same nonce back out.") t.Errorf("Should get same nonce back out.")
} }
// Encode with latest protocol version. // Encode with latest protocol version.
var buf bytes.Buffer var buf bytes.Buffer
err = msg.BtcEncode(&buf, wire.ProtocolVersion) err = msg.BtcEncode(&buf, ProtocolVersion)
if err != nil { if err != nil {
t.Errorf("encode of MsgPong failed %v err <%v>", msg, err) t.Errorf("encode of MsgPong failed %v err <%v>", msg, err)
} }
// Decode with old protocol version. // Decode with old protocol version.
readmsg := wire.NewMsgPong(0) readmsg := NewMsgPong(0)
err = readmsg.BtcDecode(&buf, wire.BIP0031Version) err = readmsg.BtcDecode(&buf, BIP0031Version)
if err == nil { if err == nil {
t.Errorf("encode of MsgPong succeeded when it shouldn't have %v", t.Errorf("encode of MsgPong succeeded when it shouldn't have %v",
msg) msg)
@ -151,25 +150,25 @@ func TestPongCrossProtocol(t *testing.T) {
// versions. // versions.
func TestPongWire(t *testing.T) { func TestPongWire(t *testing.T) {
tests := []struct { tests := []struct {
in wire.MsgPong // Message to encode in MsgPong // Message to encode
out wire.MsgPong // Expected decoded message out MsgPong // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
wire.MsgPong{Nonce: 123123}, // 0x1e0f3 MsgPong{Nonce: 123123}, // 0x1e0f3
wire.MsgPong{Nonce: 123123}, // 0x1e0f3 MsgPong{Nonce: 123123}, // 0x1e0f3
[]byte{0xf3, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0xf3, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00},
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0031Version+1 // Protocol version BIP0031Version+1
{ {
wire.MsgPong{Nonce: 456456}, // 0x6f708 MsgPong{Nonce: 456456}, // 0x6f708
wire.MsgPong{Nonce: 456456}, // 0x6f708 MsgPong{Nonce: 456456}, // 0x6f708
[]byte{0x08, 0xf7, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00}, []byte{0x08, 0xf7, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00},
wire.BIP0031Version + 1, BIP0031Version + 1,
}, },
} }
@ -189,7 +188,7 @@ func TestPongWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgPong var msg MsgPong
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -207,22 +206,22 @@ func TestPongWire(t *testing.T) {
// TestPongWireErrors performs negative tests against wire encode and decode // TestPongWireErrors performs negative tests against wire encode and decode
// of MsgPong to confirm error paths work correctly. // of MsgPong to confirm error paths work correctly.
func TestPongWireErrors(t *testing.T) { func TestPongWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
pverNoPong := wire.BIP0031Version pverNoPong := BIP0031Version
wireErr := &wire.MessageError{} wireErr := &MessageError{}
basePong := wire.NewMsgPong(123123) // 0x1e0f3 basePong := NewMsgPong(123123) // 0x1e0f3
basePongEncoded := []byte{ basePongEncoded := []byte{
0xf3, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
} }
tests := []struct { tests := []struct {
in *wire.MsgPong // Value to encode in *MsgPong // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Latest protocol version with intentional read/write errors. // Latest protocol version with intentional read/write errors.
// Force error in nonce. // Force error in nonce.
@ -242,9 +241,9 @@ func TestPongWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -253,7 +252,7 @@ func TestPongWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgPong var msg MsgPong
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -262,9 +261,9 @@ func TestPongWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View file

@ -1,8 +1,8 @@
// Copyright (c) 2014-2015 The btcsuite developers // Copyright (c) 2014-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -10,24 +10,23 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestRejectCodeStringer tests the stringized output for the reject code type. // TestRejectCodeStringer tests the stringized output for the reject code type.
func TestRejectCodeStringer(t *testing.T) { func TestRejectCodeStringer(t *testing.T) {
tests := []struct { tests := []struct {
in wire.RejectCode in RejectCode
want string want string
}{ }{
{wire.RejectMalformed, "REJECT_MALFORMED"}, {RejectMalformed, "REJECT_MALFORMED"},
{wire.RejectInvalid, "REJECT_INVALID"}, {RejectInvalid, "REJECT_INVALID"},
{wire.RejectObsolete, "REJECT_OBSOLETE"}, {RejectObsolete, "REJECT_OBSOLETE"},
{wire.RejectDuplicate, "REJECT_DUPLICATE"}, {RejectDuplicate, "REJECT_DUPLICATE"},
{wire.RejectNonstandard, "REJECT_NONSTANDARD"}, {RejectNonstandard, "REJECT_NONSTANDARD"},
{wire.RejectDust, "REJECT_DUST"}, {RejectDust, "REJECT_DUST"},
{wire.RejectInsufficientFee, "REJECT_INSUFFICIENTFEE"}, {RejectInsufficientFee, "REJECT_INSUFFICIENTFEE"},
{wire.RejectCheckpoint, "REJECT_CHECKPOINT"}, {RejectCheckpoint, "REJECT_CHECKPOINT"},
{0xff, "Unknown RejectCode (255)"}, {0xff, "Unknown RejectCode (255)"},
} }
@ -45,16 +44,16 @@ func TestRejectCodeStringer(t *testing.T) {
// TestRejectLatest tests the MsgPong API against the latest protocol version. // TestRejectLatest tests the MsgPong API against the latest protocol version.
func TestRejectLatest(t *testing.T) { func TestRejectLatest(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Create reject message data. // Create reject message data.
rejCommand := (&wire.MsgBlock{}).Command() rejCommand := (&MsgBlock{}).Command()
rejCode := wire.RejectDuplicate rejCode := RejectDuplicate
rejReason := "duplicate block" rejReason := "duplicate block"
rejHash := mainNetGenesisHash rejHash := mainNetGenesisHash
// Ensure we get the correct data back out. // Ensure we get the correct data back out.
msg := wire.NewMsgReject(rejCommand, rejCode, rejReason) msg := NewMsgReject(rejCommand, rejCode, rejReason)
msg.Hash = rejHash msg.Hash = rejHash
if msg.Cmd != rejCommand { if msg.Cmd != rejCommand {
t.Errorf("NewMsgReject: wrong rejected command - got %v, "+ t.Errorf("NewMsgReject: wrong rejected command - got %v, "+
@ -77,7 +76,7 @@ func TestRejectLatest(t *testing.T) {
} }
// Ensure max payload is expected value for latest protocol version. // Ensure max payload is expected value for latest protocol version.
wantPayload := uint32(wire.MaxMessagePayload) wantPayload := uint32(MaxMessagePayload)
maxPayload := msg.MaxPayloadLength(pver) maxPayload := msg.MaxPayloadLength(pver)
if maxPayload != wantPayload { if maxPayload != wantPayload {
t.Errorf("MaxPayloadLength: wrong max payload length for "+ t.Errorf("MaxPayloadLength: wrong max payload length for "+
@ -93,7 +92,7 @@ func TestRejectLatest(t *testing.T) {
} }
// Test decode with latest protocol version. // Test decode with latest protocol version.
readMsg := wire.MsgReject{} readMsg := MsgReject{}
err = readMsg.BtcDecode(&buf, pver) err = readMsg.BtcDecode(&buf, pver)
if err != nil { if err != nil {
t.Errorf("decode of MsgReject failed %v err <%v>", buf.Bytes(), t.Errorf("decode of MsgReject failed %v err <%v>", buf.Bytes(),
@ -123,15 +122,15 @@ func TestRejectLatest(t *testing.T) {
// before the version which introduced it (RejectVersion). // before the version which introduced it (RejectVersion).
func TestRejectBeforeAdded(t *testing.T) { func TestRejectBeforeAdded(t *testing.T) {
// Use the protocol version just prior to RejectVersion. // Use the protocol version just prior to RejectVersion.
pver := wire.RejectVersion - 1 pver := RejectVersion - 1
// Create reject message data. // Create reject message data.
rejCommand := (&wire.MsgBlock{}).Command() rejCommand := (&MsgBlock{}).Command()
rejCode := wire.RejectDuplicate rejCode := RejectDuplicate
rejReason := "duplicate block" rejReason := "duplicate block"
rejHash := mainNetGenesisHash rejHash := mainNetGenesisHash
msg := wire.NewMsgReject(rejCommand, rejCode, rejReason) msg := NewMsgReject(rejCommand, rejCode, rejReason)
msg.Hash = rejHash msg.Hash = rejHash
// Ensure max payload is expected value for old protocol version. // Ensure max payload is expected value for old protocol version.
@ -150,7 +149,7 @@ func TestRejectBeforeAdded(t *testing.T) {
} }
// // Test decode with old protocol version. // // Test decode with old protocol version.
readMsg := wire.MsgReject{} readMsg := MsgReject{}
err = readMsg.BtcDecode(&buf, pver) err = readMsg.BtcDecode(&buf, pver)
if err == nil { if err == nil {
t.Errorf("decode of MsgReject succeeded when it shouldn't "+ t.Errorf("decode of MsgReject succeeded when it shouldn't "+
@ -182,24 +181,24 @@ func TestRejectBeforeAdded(t *testing.T) {
// introduced it (RejectVersion). // introduced it (RejectVersion).
func TestRejectCrossProtocol(t *testing.T) { func TestRejectCrossProtocol(t *testing.T) {
// Create reject message data. // Create reject message data.
rejCommand := (&wire.MsgBlock{}).Command() rejCommand := (&MsgBlock{}).Command()
rejCode := wire.RejectDuplicate rejCode := RejectDuplicate
rejReason := "duplicate block" rejReason := "duplicate block"
rejHash := mainNetGenesisHash rejHash := mainNetGenesisHash
msg := wire.NewMsgReject(rejCommand, rejCode, rejReason) msg := NewMsgReject(rejCommand, rejCode, rejReason)
msg.Hash = rejHash msg.Hash = rejHash
// Encode with latest protocol version. // Encode with latest protocol version.
var buf bytes.Buffer var buf bytes.Buffer
err := msg.BtcEncode(&buf, wire.ProtocolVersion) err := msg.BtcEncode(&buf, ProtocolVersion)
if err != nil { if err != nil {
t.Errorf("encode of MsgReject failed %v err <%v>", msg, err) t.Errorf("encode of MsgReject failed %v err <%v>", msg, err)
} }
// Decode with old protocol version. // Decode with old protocol version.
readMsg := wire.MsgReject{} readMsg := MsgReject{}
err = readMsg.BtcDecode(&buf, wire.RejectVersion-1) err = readMsg.BtcDecode(&buf, RejectVersion-1)
if err == nil { if err == nil {
t.Errorf("encode of MsgReject succeeded when it shouldn't "+ t.Errorf("encode of MsgReject succeeded when it shouldn't "+
"have %v", msg) "have %v", msg)
@ -226,37 +225,37 @@ func TestRejectCrossProtocol(t *testing.T) {
// protocol versions. // protocol versions.
func TestRejectWire(t *testing.T) { func TestRejectWire(t *testing.T) {
tests := []struct { tests := []struct {
msg wire.MsgReject // Message to encode msg MsgReject // Message to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version rejected command version (no hash). // Latest protocol version rejected command version (no hash).
{ {
wire.MsgReject{ MsgReject{
Cmd: "version", Cmd: "version",
Code: wire.RejectDuplicate, Code: RejectDuplicate,
Reason: "duplicate version", Reason: "duplicate version",
}, },
[]byte{ []byte{
0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, // "version" 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, // "version"
0x12, // wire.RejectDuplicate 0x12, // RejectDuplicate
0x11, 0x64, 0x75, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x11, 0x64, 0x75, 0x70, 0x6c, 0x69, 0x63, 0x61,
0x74, 0x65, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x74, 0x65, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
0x6f, 0x6e, // "duplicate version" 0x6f, 0x6e, // "duplicate version"
}, },
wire.ProtocolVersion, ProtocolVersion,
}, },
// Latest protocol version rejected command block (has hash). // Latest protocol version rejected command block (has hash).
{ {
wire.MsgReject{ MsgReject{
Cmd: "block", Cmd: "block",
Code: wire.RejectDuplicate, Code: RejectDuplicate,
Reason: "duplicate block", Reason: "duplicate block",
Hash: mainNetGenesisHash, Hash: mainNetGenesisHash,
}, },
[]byte{ []byte{
0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, // "block" 0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, // "block"
0x12, // wire.RejectDuplicate 0x12, // RejectDuplicate
0x0f, 0x64, 0x75, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x0f, 0x64, 0x75, 0x70, 0x6c, 0x69, 0x63, 0x61,
0x74, 0x65, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, // "duplicate block" 0x74, 0x65, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, // "duplicate block"
0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72, 0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
@ -264,7 +263,7 @@ func TestRejectWire(t *testing.T) {
0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c, 0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, // mainNetGenesisHash 0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, // mainNetGenesisHash
}, },
wire.ProtocolVersion, ProtocolVersion,
}, },
} }
@ -284,7 +283,7 @@ func TestRejectWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgReject var msg MsgReject
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -302,16 +301,15 @@ func TestRejectWire(t *testing.T) {
// TestRejectWireErrors performs negative tests against wire encode and decode // TestRejectWireErrors performs negative tests against wire encode and decode
// of MsgReject to confirm error paths work correctly. // of MsgReject to confirm error paths work correctly.
func TestRejectWireErrors(t *testing.T) { func TestRejectWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
pverNoReject := wire.RejectVersion - 1 pverNoReject := RejectVersion - 1
wireErr := &wire.MessageError{} wireErr := &MessageError{}
baseReject := wire.NewMsgReject("block", wire.RejectDuplicate, baseReject := NewMsgReject("block", RejectDuplicate, "duplicate block")
"duplicate block")
baseReject.Hash = mainNetGenesisHash baseReject.Hash = mainNetGenesisHash
baseRejectEncoded := []byte{ baseRejectEncoded := []byte{
0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, // "block" 0x05, 0x62, 0x6c, 0x6f, 0x63, 0x6b, // "block"
0x12, // wire.RejectDuplicate 0x12, // RejectDuplicate
0x0f, 0x64, 0x75, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x0f, 0x64, 0x75, 0x70, 0x6c, 0x69, 0x63, 0x61,
0x74, 0x65, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, // "duplicate block" 0x74, 0x65, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, // "duplicate block"
0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72, 0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
@ -321,12 +319,12 @@ func TestRejectWireErrors(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgReject // Value to encode in *MsgReject // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Latest protocol version with intentional read/write errors. // Latest protocol version with intentional read/write errors.
// Force error in reject command. // Force error in reject command.
@ -352,9 +350,9 @@ func TestRejectWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -363,7 +361,7 @@ func TestRejectWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgReject var msg MsgReject
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -372,9 +370,9 @@ func TestRejectWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View file

@ -2,25 +2,24 @@
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestSendHeaders tests the MsgSendHeaders API against the latest protocol // TestSendHeaders tests the MsgSendHeaders API against the latest protocol
// version. // version.
func TestSendHeaders(t *testing.T) { func TestSendHeaders(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "sendheaders" wantCmd := "sendheaders"
msg := wire.NewMsgSendHeaders() msg := NewMsgSendHeaders()
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgSendHeaders: wrong command - got %v want %v", t.Errorf("NewMsgSendHeaders: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -45,7 +44,7 @@ func TestSendHeaders(t *testing.T) {
// Older protocol versions should fail encode since message didn't // Older protocol versions should fail encode since message didn't
// exist yet. // exist yet.
oldPver := wire.SendHeadersVersion - 1 oldPver := SendHeadersVersion - 1
err = msg.BtcEncode(&buf, oldPver) err = msg.BtcEncode(&buf, oldPver)
if err == nil { if err == nil {
s := "encode of MsgSendHeaders passed for old protocol " + s := "encode of MsgSendHeaders passed for old protocol " +
@ -54,7 +53,7 @@ func TestSendHeaders(t *testing.T) {
} }
// Test decode with latest protocol version. // Test decode with latest protocol version.
readmsg := wire.NewMsgSendHeaders() readmsg := NewMsgSendHeaders()
err = readmsg.BtcDecode(&buf, pver) err = readmsg.BtcDecode(&buf, pver)
if err != nil { if err != nil {
t.Errorf("decode of MsgSendHeaders failed [%v] err <%v>", buf, t.Errorf("decode of MsgSendHeaders failed [%v] err <%v>", buf,
@ -77,9 +76,9 @@ func TestSendHeaders(t *testing.T) {
// prior to version SendHeadersVersion. // prior to version SendHeadersVersion.
func TestSendHeadersBIP0130(t *testing.T) { func TestSendHeadersBIP0130(t *testing.T) {
// Use the protocol version just prior to SendHeadersVersion changes. // Use the protocol version just prior to SendHeadersVersion changes.
pver := wire.SendHeadersVersion - 1 pver := SendHeadersVersion - 1
msg := wire.NewMsgSendHeaders() msg := NewMsgSendHeaders()
// Test encode with old protocol version. // Test encode with old protocol version.
var buf bytes.Buffer var buf bytes.Buffer
@ -90,7 +89,7 @@ func TestSendHeadersBIP0130(t *testing.T) {
} }
// Test decode with old protocol version. // Test decode with old protocol version.
readmsg := wire.NewMsgSendHeaders() readmsg := NewMsgSendHeaders()
err = readmsg.BtcDecode(&buf, pver) err = readmsg.BtcDecode(&buf, pver)
if err == nil { if err == nil {
t.Errorf("decode of MsgSendHeaders succeeded when it should " + t.Errorf("decode of MsgSendHeaders succeeded when it should " +
@ -103,19 +102,19 @@ func TestSendHeadersBIP0130(t *testing.T) {
// TestSendHeadersCrossProtocol tests the MsgSendHeaders API when encoding with // TestSendHeadersCrossProtocol tests the MsgSendHeaders API when encoding with
// the latest protocol version and decoding with SendHeadersVersion. // the latest protocol version and decoding with SendHeadersVersion.
func TestSendHeadersCrossProtocol(t *testing.T) { func TestSendHeadersCrossProtocol(t *testing.T) {
msg := wire.NewMsgSendHeaders() msg := NewMsgSendHeaders()
// Encode with latest protocol version. // Encode with latest protocol version.
var buf bytes.Buffer var buf bytes.Buffer
err := msg.BtcEncode(&buf, wire.ProtocolVersion) err := msg.BtcEncode(&buf, ProtocolVersion)
if err != nil { if err != nil {
t.Errorf("encode of MsgSendHeaders failed %v err <%v>", msg, t.Errorf("encode of MsgSendHeaders failed %v err <%v>", msg,
err) err)
} }
// Decode with old protocol version. // Decode with old protocol version.
readmsg := wire.NewMsgSendHeaders() readmsg := NewMsgSendHeaders()
err = readmsg.BtcDecode(&buf, wire.SendHeadersVersion) err = readmsg.BtcDecode(&buf, SendHeadersVersion)
if err != nil { if err != nil {
t.Errorf("decode of MsgSendHeaders failed [%v] err <%v>", buf, t.Errorf("decode of MsgSendHeaders failed [%v] err <%v>", buf,
err) err)
@ -125,21 +124,21 @@ func TestSendHeadersCrossProtocol(t *testing.T) {
// TestSendHeadersWire tests the MsgSendHeaders wire encode and decode for // TestSendHeadersWire tests the MsgSendHeaders wire encode and decode for
// various protocol versions. // various protocol versions.
func TestSendHeadersWire(t *testing.T) { func TestSendHeadersWire(t *testing.T) {
msgSendHeaders := wire.NewMsgSendHeaders() msgSendHeaders := NewMsgSendHeaders()
msgSendHeadersEncoded := []byte{} msgSendHeadersEncoded := []byte{}
tests := []struct { tests := []struct {
in *wire.MsgSendHeaders // Message to encode in *MsgSendHeaders // Message to encode
out *wire.MsgSendHeaders // Expected decoded message out *MsgSendHeaders // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
msgSendHeaders, msgSendHeaders,
msgSendHeaders, msgSendHeaders,
msgSendHeadersEncoded, msgSendHeadersEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version SendHeadersVersion+1 // Protocol version SendHeadersVersion+1
@ -147,7 +146,7 @@ func TestSendHeadersWire(t *testing.T) {
msgSendHeaders, msgSendHeaders,
msgSendHeaders, msgSendHeaders,
msgSendHeadersEncoded, msgSendHeadersEncoded,
wire.SendHeadersVersion + 1, SendHeadersVersion + 1,
}, },
// Protocol version SendHeadersVersion // Protocol version SendHeadersVersion
@ -155,7 +154,7 @@ func TestSendHeadersWire(t *testing.T) {
msgSendHeaders, msgSendHeaders,
msgSendHeaders, msgSendHeaders,
msgSendHeadersEncoded, msgSendHeadersEncoded,
wire.SendHeadersVersion, SendHeadersVersion,
}, },
} }
@ -175,7 +174,7 @@ func TestSendHeadersWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgSendHeaders var msg MsgSendHeaders
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -11,24 +11,23 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestTx tests the MsgTx API. // TestTx tests the MsgTx API.
func TestTx(t *testing.T) { func TestTx(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Block 100000 hash. // Block 100000 hash.
hashStr := "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506" hashStr := "3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
hash, err := wire.NewShaHashFromStr(hashStr) hash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "tx" wantCmd := "tx"
msg := wire.NewMsgTx() msg := NewMsgTx()
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgAddr: wrong command - got %v want %v", t.Errorf("NewMsgAddr: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -48,7 +47,7 @@ func TestTx(t *testing.T) {
// NOTE: This is a block hash and made up index, but we're only // NOTE: This is a block hash and made up index, but we're only
// testing package functionality. // testing package functionality.
prevOutIndex := uint32(1) prevOutIndex := uint32(1)
prevOut := wire.NewOutPoint(hash, prevOutIndex) prevOut := NewOutPoint(hash, prevOutIndex)
if !prevOut.Hash.IsEqual(hash) { if !prevOut.Hash.IsEqual(hash) {
t.Errorf("NewOutPoint: wrong hash - got %v, want %v", t.Errorf("NewOutPoint: wrong hash - got %v, want %v",
spew.Sprint(&prevOut.Hash), spew.Sprint(hash)) spew.Sprint(&prevOut.Hash), spew.Sprint(hash))
@ -65,7 +64,7 @@ func TestTx(t *testing.T) {
// Ensure we get the same transaction input back out. // Ensure we get the same transaction input back out.
sigScript := []byte{0x04, 0x31, 0xdc, 0x00, 0x1b, 0x01, 0x62} sigScript := []byte{0x04, 0x31, 0xdc, 0x00, 0x1b, 0x01, 0x62}
txIn := wire.NewTxIn(prevOut, sigScript) txIn := NewTxIn(prevOut, sigScript)
if !reflect.DeepEqual(&txIn.PreviousOutPoint, prevOut) { if !reflect.DeepEqual(&txIn.PreviousOutPoint, prevOut) {
t.Errorf("NewTxIn: wrong prev outpoint - got %v, want %v", t.Errorf("NewTxIn: wrong prev outpoint - got %v, want %v",
spew.Sprint(&txIn.PreviousOutPoint), spew.Sprint(&txIn.PreviousOutPoint),
@ -92,7 +91,7 @@ func TestTx(t *testing.T) {
0xa6, // 65-byte signature 0xa6, // 65-byte signature
0xac, // OP_CHECKSIG 0xac, // OP_CHECKSIG
} }
txOut := wire.NewTxOut(txValue, pkScript) txOut := NewTxOut(txValue, pkScript)
if txOut.Value != txValue { if txOut.Value != txValue {
t.Errorf("NewTxOut: wrong pk script - got %v, want %v", t.Errorf("NewTxOut: wrong pk script - got %v, want %v",
txOut.Value, txValue) txOut.Value, txValue)
@ -132,23 +131,23 @@ func TestTx(t *testing.T) {
func TestTxSha(t *testing.T) { func TestTxSha(t *testing.T) {
// Hash of first transaction from block 113875. // Hash of first transaction from block 113875.
hashStr := "f051e59b5e2503ac626d03aaeac8ab7be2d72ba4b7e97119c5852d70d52dcb86" hashStr := "f051e59b5e2503ac626d03aaeac8ab7be2d72ba4b7e97119c5852d70d52dcb86"
wantHash, err := wire.NewShaHashFromStr(hashStr) wantHash, err := NewShaHashFromStr(hashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
return return
} }
// First transaction from block 113875. // First transaction from block 113875.
msgTx := wire.NewMsgTx() msgTx := NewMsgTx()
txIn := wire.TxIn{ txIn := TxIn{
PreviousOutPoint: wire.OutPoint{ PreviousOutPoint: OutPoint{
Hash: wire.ShaHash{}, Hash: ShaHash{},
Index: 0xffffffff, Index: 0xffffffff,
}, },
SignatureScript: []byte{0x04, 0x31, 0xdc, 0x00, 0x1b, 0x01, 0x62}, SignatureScript: []byte{0x04, 0x31, 0xdc, 0x00, 0x1b, 0x01, 0x62},
Sequence: 0xffffffff, Sequence: 0xffffffff,
} }
txOut := wire.TxOut{ txOut := TxOut{
Value: 5000000000, Value: 5000000000,
PkScript: []byte{ PkScript: []byte{
0x41, // OP_DATA_65 0x41, // OP_DATA_65
@ -180,7 +179,7 @@ func TestTxSha(t *testing.T) {
// of transaction inputs and outputs and protocol versions. // of transaction inputs and outputs and protocol versions.
func TestTxWire(t *testing.T) { func TestTxWire(t *testing.T) {
// Empty tx message. // Empty tx message.
noTx := wire.NewMsgTx() noTx := NewMsgTx()
noTx.Version = 1 noTx.Version = 1
noTxEncoded := []byte{ noTxEncoded := []byte{
0x01, 0x00, 0x00, 0x00, // Version 0x01, 0x00, 0x00, 0x00, // Version
@ -190,17 +189,17 @@ func TestTxWire(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgTx // Message to encode in *MsgTx // Message to encode
out *wire.MsgTx // Expected decoded message out *MsgTx // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version with no transactions. // Latest protocol version with no transactions.
{ {
noTx, noTx,
noTx, noTx,
noTxEncoded, noTxEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Latest protocol version with multiple transactions. // Latest protocol version with multiple transactions.
@ -208,7 +207,7 @@ func TestTxWire(t *testing.T) {
multiTx, multiTx,
multiTx, multiTx,
multiTxEncoded, multiTxEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version with no transactions. // Protocol version BIP0035Version with no transactions.
@ -216,7 +215,7 @@ func TestTxWire(t *testing.T) {
noTx, noTx,
noTx, noTx,
noTxEncoded, noTxEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0035Version with multiple transactions. // Protocol version BIP0035Version with multiple transactions.
@ -224,7 +223,7 @@ func TestTxWire(t *testing.T) {
multiTx, multiTx,
multiTx, multiTx,
multiTxEncoded, multiTxEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version with no transactions. // Protocol version BIP0031Version with no transactions.
@ -232,7 +231,7 @@ func TestTxWire(t *testing.T) {
noTx, noTx,
noTx, noTx,
noTxEncoded, noTxEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version BIP0031Version with multiple transactions. // Protocol version BIP0031Version with multiple transactions.
@ -240,7 +239,7 @@ func TestTxWire(t *testing.T) {
multiTx, multiTx,
multiTx, multiTx,
multiTxEncoded, multiTxEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion with no transactions. // Protocol version NetAddressTimeVersion with no transactions.
@ -248,7 +247,7 @@ func TestTxWire(t *testing.T) {
noTx, noTx,
noTx, noTx,
noTxEncoded, noTxEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version NetAddressTimeVersion with multiple transactions. // Protocol version NetAddressTimeVersion with multiple transactions.
@ -256,7 +255,7 @@ func TestTxWire(t *testing.T) {
multiTx, multiTx,
multiTx, multiTx,
multiTxEncoded, multiTxEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion with no transactions. // Protocol version MultipleAddressVersion with no transactions.
@ -264,7 +263,7 @@ func TestTxWire(t *testing.T) {
noTx, noTx,
noTx, noTx,
noTxEncoded, noTxEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
// Protocol version MultipleAddressVersion with multiple transactions. // Protocol version MultipleAddressVersion with multiple transactions.
@ -272,7 +271,7 @@ func TestTxWire(t *testing.T) {
multiTx, multiTx,
multiTx, multiTx,
multiTxEncoded, multiTxEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -292,7 +291,7 @@ func TestTxWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgTx var msg MsgTx
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -316,12 +315,12 @@ func TestTxWireErrors(t *testing.T) {
pver := uint32(60002) pver := uint32(60002)
tests := []struct { tests := []struct {
in *wire.MsgTx // Value to encode in *MsgTx // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Force error in version. // Force error in version.
{multiTx, multiTxEncoded, pver, 0, io.ErrShortWrite, io.EOF}, {multiTx, multiTxEncoded, pver, 0, io.ErrShortWrite, io.EOF},
@ -361,7 +360,7 @@ func TestTxWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgTx var msg MsgTx
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = msg.BtcDecode(r, test.pver) err = msg.BtcDecode(r, test.pver)
if err != test.readErr { if err != test.readErr {
@ -374,7 +373,7 @@ func TestTxWireErrors(t *testing.T) {
// TestTxSerialize tests MsgTx serialize and deserialize. // TestTxSerialize tests MsgTx serialize and deserialize.
func TestTxSerialize(t *testing.T) { func TestTxSerialize(t *testing.T) {
noTx := wire.NewMsgTx() noTx := NewMsgTx()
noTx.Version = 1 noTx.Version = 1
noTxEncoded := []byte{ noTxEncoded := []byte{
0x01, 0x00, 0x00, 0x00, // Version 0x01, 0x00, 0x00, 0x00, // Version
@ -384,10 +383,10 @@ func TestTxSerialize(t *testing.T) {
} }
tests := []struct { tests := []struct {
in *wire.MsgTx // Message to encode in *MsgTx // Message to encode
out *wire.MsgTx // Expected decoded message out *MsgTx // Expected decoded message
buf []byte // Serialized data buf []byte // Serialized data
pkScriptLocs []int // Expected output script locations pkScriptLocs []int // Expected output script locations
}{ }{
// No transactions. // No transactions.
{ {
@ -422,7 +421,7 @@ func TestTxSerialize(t *testing.T) {
} }
// Deserialize the transaction. // Deserialize the transaction.
var tx wire.MsgTx var tx MsgTx
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = tx.Deserialize(rbuf) err = tx.Deserialize(rbuf)
if err != nil { if err != nil {
@ -460,11 +459,11 @@ func TestTxSerialize(t *testing.T) {
// of MsgTx to confirm error paths work correctly. // of MsgTx to confirm error paths work correctly.
func TestTxSerializeErrors(t *testing.T) { func TestTxSerializeErrors(t *testing.T) {
tests := []struct { tests := []struct {
in *wire.MsgTx // Value to encode in *MsgTx // Value to encode
buf []byte // Serialized data buf []byte // Serialized data
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Force error in version. // Force error in version.
{multiTx, multiTxEncoded, 0, io.ErrShortWrite, io.EOF}, {multiTx, multiTxEncoded, 0, io.ErrShortWrite, io.EOF},
@ -504,7 +503,7 @@ func TestTxSerializeErrors(t *testing.T) {
} }
// Deserialize the transaction. // Deserialize the transaction.
var tx wire.MsgTx var tx MsgTx
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = tx.Deserialize(r) err = tx.Deserialize(r)
if err != test.readErr { if err != test.readErr {
@ -538,7 +537,7 @@ func TestTxOverflowErrors(t *testing.T) {
0x00, 0x00, 0x00, 0x01, // Version 0x00, 0x00, 0x00, 0x01, // Version
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, // Varint for number of input transactions 0xff, // Varint for number of input transactions
}, pver, txVer, &wire.MessageError{}, }, pver, txVer, &MessageError{},
}, },
// Transaction that claims to have ~uint64(0) outputs. // Transaction that claims to have ~uint64(0) outputs.
@ -548,7 +547,7 @@ func TestTxOverflowErrors(t *testing.T) {
0x00, // Varint for number of input transactions 0x00, // Varint for number of input transactions
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, // Varint for number of output transactions 0xff, // Varint for number of output transactions
}, pver, txVer, &wire.MessageError{}, }, pver, txVer, &MessageError{},
}, },
// Transaction that has an input with a signature script that // Transaction that has an input with a signature script that
@ -564,7 +563,7 @@ func TestTxOverflowErrors(t *testing.T) {
0xff, 0xff, 0xff, 0xff, // Prevous output index 0xff, 0xff, 0xff, 0xff, // Prevous output index
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, // Varint for length of signature script 0xff, // Varint for length of signature script
}, pver, txVer, &wire.MessageError{}, }, pver, txVer, &MessageError{},
}, },
// Transaction that has an output with a public key script // Transaction that has an output with a public key script
@ -584,14 +583,14 @@ func TestTxOverflowErrors(t *testing.T) {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Transaction amount 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Transaction amount
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, // Varint for length of public key script 0xff, // Varint for length of public key script
}, pver, txVer, &wire.MessageError{}, }, pver, txVer, &MessageError{},
}, },
} }
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
// Decode from wire format. // Decode from wire format.
var msg wire.MsgTx var msg MsgTx
r := bytes.NewReader(test.buf) r := bytes.NewReader(test.buf)
err := msg.BtcDecode(r, test.pver) err := msg.BtcDecode(r, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.err) { if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
@ -615,12 +614,12 @@ func TestTxOverflowErrors(t *testing.T) {
// transactions is accurate. // transactions is accurate.
func TestTxSerializeSize(t *testing.T) { func TestTxSerializeSize(t *testing.T) {
// Empty tx message. // Empty tx message.
noTx := wire.NewMsgTx() noTx := NewMsgTx()
noTx.Version = 1 noTx.Version = 1
tests := []struct { tests := []struct {
in *wire.MsgTx // Tx to encode in *MsgTx // Tx to encode
size int // Expected serialized size size int // Expected serialized size
}{ }{
// No inputs or outpus. // No inputs or outpus.
{noTx, 10}, {noTx, 10},
@ -641,12 +640,12 @@ func TestTxSerializeSize(t *testing.T) {
} }
// multiTx is a MsgTx with an input and output and used in various tests. // multiTx is a MsgTx with an input and output and used in various tests.
var multiTx = &wire.MsgTx{ var multiTx = &MsgTx{
Version: 1, Version: 1,
TxIn: []*wire.TxIn{ TxIn: []*TxIn{
{ {
PreviousOutPoint: wire.OutPoint{ PreviousOutPoint: OutPoint{
Hash: wire.ShaHash{}, Hash: ShaHash{},
Index: 0xffffffff, Index: 0xffffffff,
}, },
SignatureScript: []byte{ SignatureScript: []byte{
@ -655,7 +654,7 @@ var multiTx = &wire.MsgTx{
Sequence: 0xffffffff, Sequence: 0xffffffff,
}, },
}, },
TxOut: []*wire.TxOut{ TxOut: []*TxOut{
{ {
Value: 0x12a05f200, Value: 0x12a05f200,
PkScript: []byte{ PkScript: []byte{

View file

@ -1,25 +1,24 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
"reflect" "reflect"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestVerAck tests the MsgVerAck API. // TestVerAck tests the MsgVerAck API.
func TestVerAck(t *testing.T) { func TestVerAck(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Ensure the command is expected value. // Ensure the command is expected value.
wantCmd := "verack" wantCmd := "verack"
msg := wire.NewMsgVerAck() msg := NewMsgVerAck()
if cmd := msg.Command(); cmd != wantCmd { if cmd := msg.Command(); cmd != wantCmd {
t.Errorf("NewMsgVerAck: wrong command - got %v want %v", t.Errorf("NewMsgVerAck: wrong command - got %v want %v",
cmd, wantCmd) cmd, wantCmd)
@ -40,21 +39,21 @@ func TestVerAck(t *testing.T) {
// TestVerAckWire tests the MsgVerAck wire encode and decode for various // TestVerAckWire tests the MsgVerAck wire encode and decode for various
// protocol versions. // protocol versions.
func TestVerAckWire(t *testing.T) { func TestVerAckWire(t *testing.T) {
msgVerAck := wire.NewMsgVerAck() msgVerAck := NewMsgVerAck()
msgVerAckEncoded := []byte{} msgVerAckEncoded := []byte{}
tests := []struct { tests := []struct {
in *wire.MsgVerAck // Message to encode in *MsgVerAck // Message to encode
out *wire.MsgVerAck // Expected decoded message out *MsgVerAck // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
msgVerAck, msgVerAck,
msgVerAck, msgVerAck,
msgVerAckEncoded, msgVerAckEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0035Version. // Protocol version BIP0035Version.
@ -62,7 +61,7 @@ func TestVerAckWire(t *testing.T) {
msgVerAck, msgVerAck,
msgVerAck, msgVerAck,
msgVerAckEncoded, msgVerAckEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version. // Protocol version BIP0031Version.
@ -70,7 +69,7 @@ func TestVerAckWire(t *testing.T) {
msgVerAck, msgVerAck,
msgVerAck, msgVerAck,
msgVerAckEncoded, msgVerAckEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion. // Protocol version NetAddressTimeVersion.
@ -78,7 +77,7 @@ func TestVerAckWire(t *testing.T) {
msgVerAck, msgVerAck,
msgVerAck, msgVerAck,
msgVerAckEncoded, msgVerAckEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion. // Protocol version MultipleAddressVersion.
@ -86,7 +85,7 @@ func TestVerAckWire(t *testing.T) {
msgVerAck, msgVerAck,
msgVerAck, msgVerAck,
msgVerAckEncoded, msgVerAckEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -106,7 +105,7 @@ func TestVerAckWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgVerAck var msg MsgVerAck
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -13,33 +13,32 @@ import (
"testing" "testing"
"time" "time"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
// TestVersion tests the MsgVersion API. // TestVersion tests the MsgVersion API.
func TestVersion(t *testing.T) { func TestVersion(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
// Create version message data. // Create version message data.
lastBlock := int32(234234) lastBlock := int32(234234)
tcpAddrMe := &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8333} tcpAddrMe := &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8333}
me, err := wire.NewNetAddress(tcpAddrMe, wire.SFNodeNetwork) me, err := NewNetAddress(tcpAddrMe, SFNodeNetwork)
if err != nil { if err != nil {
t.Errorf("NewNetAddress: %v", err) t.Errorf("NewNetAddress: %v", err)
} }
tcpAddrYou := &net.TCPAddr{IP: net.ParseIP("192.168.0.1"), Port: 8333} tcpAddrYou := &net.TCPAddr{IP: net.ParseIP("192.168.0.1"), Port: 8333}
you, err := wire.NewNetAddress(tcpAddrYou, wire.SFNodeNetwork) you, err := NewNetAddress(tcpAddrYou, SFNodeNetwork)
if err != nil { if err != nil {
t.Errorf("NewNetAddress: %v", err) t.Errorf("NewNetAddress: %v", err)
} }
nonce, err := wire.RandomUint64() nonce, err := RandomUint64()
if err != nil { if err != nil {
t.Errorf("RandomUint64: error generating nonce: %v", err) t.Errorf("RandomUint64: error generating nonce: %v", err)
} }
// Ensure we get the correct data back out. // Ensure we get the correct data back out.
msg := wire.NewMsgVersion(me, you, nonce, lastBlock) msg := NewMsgVersion(me, you, nonce, lastBlock)
if msg.ProtocolVersion != int32(pver) { if msg.ProtocolVersion != int32(pver) {
t.Errorf("NewMsgVersion: wrong protocol version - got %v, want %v", t.Errorf("NewMsgVersion: wrong protocol version - got %v, want %v",
msg.ProtocolVersion, pver) msg.ProtocolVersion, pver)
@ -56,9 +55,9 @@ func TestVersion(t *testing.T) {
t.Errorf("NewMsgVersion: wrong nonce - got %v, want %v", t.Errorf("NewMsgVersion: wrong nonce - got %v, want %v",
msg.Nonce, nonce) msg.Nonce, nonce)
} }
if msg.UserAgent != wire.DefaultUserAgent { if msg.UserAgent != DefaultUserAgent {
t.Errorf("NewMsgVersion: wrong user agent - got %v, want %v", t.Errorf("NewMsgVersion: wrong user agent - got %v, want %v",
msg.UserAgent, wire.DefaultUserAgent) msg.UserAgent, DefaultUserAgent)
} }
if msg.LastBlock != lastBlock { if msg.LastBlock != lastBlock {
t.Errorf("NewMsgVersion: wrong last block - got %v, want %v", t.Errorf("NewMsgVersion: wrong last block - got %v, want %v",
@ -70,7 +69,7 @@ func TestVersion(t *testing.T) {
} }
msg.AddUserAgent("myclient", "1.2.3", "optional", "comments") msg.AddUserAgent("myclient", "1.2.3", "optional", "comments")
customUserAgent := wire.DefaultUserAgent + "myclient:1.2.3(optional; comments)/" customUserAgent := DefaultUserAgent + "myclient:1.2.3(optional; comments)/"
if msg.UserAgent != customUserAgent { if msg.UserAgent != customUserAgent {
t.Errorf("AddUserAgent: wrong user agent - got %s, want %s", t.Errorf("AddUserAgent: wrong user agent - got %s, want %s",
msg.UserAgent, customUserAgent) msg.UserAgent, customUserAgent)
@ -85,10 +84,10 @@ func TestVersion(t *testing.T) {
// accounting for ":", "/" // accounting for ":", "/"
err = msg.AddUserAgent(strings.Repeat("t", err = msg.AddUserAgent(strings.Repeat("t",
wire.MaxUserAgentLen-len(customUserAgent)-2+1), "") MaxUserAgentLen-len(customUserAgent)-2+1), "")
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
t.Errorf("AddUserAgent: expected error not received "+ t.Errorf("AddUserAgent: expected error not received "+
"- got %v, want %T", err, wire.MessageError{}) "- got %v, want %T", err, MessageError{})
} }
@ -98,7 +97,7 @@ func TestVersion(t *testing.T) {
msg.Services, 0) msg.Services, 0)
} }
if msg.HasService(wire.SFNodeNetwork) { if msg.HasService(SFNodeNetwork) {
t.Errorf("HasService: SFNodeNetwork service is set") t.Errorf("HasService: SFNodeNetwork service is set")
} }
@ -123,18 +122,18 @@ func TestVersion(t *testing.T) {
} }
// Ensure adding the full service node flag works. // Ensure adding the full service node flag works.
msg.AddService(wire.SFNodeNetwork) msg.AddService(SFNodeNetwork)
if msg.Services != wire.SFNodeNetwork { if msg.Services != SFNodeNetwork {
t.Errorf("AddService: wrong services - got %v, want %v", t.Errorf("AddService: wrong services - got %v, want %v",
msg.Services, wire.SFNodeNetwork) msg.Services, SFNodeNetwork)
} }
if !msg.HasService(wire.SFNodeNetwork) { if !msg.HasService(SFNodeNetwork) {
t.Errorf("HasService: SFNodeNetwork service not set") t.Errorf("HasService: SFNodeNetwork service not set")
} }
// Use a fake connection. // Use a fake connection.
conn := &fakeConn{localAddr: tcpAddrMe, remoteAddr: tcpAddrYou} conn := &fakeConn{localAddr: tcpAddrMe, remoteAddr: tcpAddrYou}
msg, err = wire.NewMsgVersionFromConn(conn, nonce, lastBlock) msg, err = NewMsgVersionFromConn(conn, nonce, lastBlock)
if err != nil { if err != nil {
t.Errorf("NewMsgVersionFromConn: %v", err) t.Errorf("NewMsgVersionFromConn: %v", err)
} }
@ -154,10 +153,10 @@ func TestVersion(t *testing.T) {
localAddr: &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8333}, localAddr: &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8333},
remoteAddr: tcpAddrYou, remoteAddr: tcpAddrYou,
} }
msg, err = wire.NewMsgVersionFromConn(conn, nonce, lastBlock) msg, err = NewMsgVersionFromConn(conn, nonce, lastBlock)
if err != wire.ErrInvalidNetAddr { if err != ErrInvalidNetAddr {
t.Errorf("NewMsgVersionFromConn: expected error not received "+ t.Errorf("NewMsgVersionFromConn: expected error not received "+
"- got %v, want %v", err, wire.ErrInvalidNetAddr) "- got %v, want %v", err, ErrInvalidNetAddr)
} }
// Use a fake connection with remote UDP addresses to force a failure. // Use a fake connection with remote UDP addresses to force a failure.
@ -165,10 +164,10 @@ func TestVersion(t *testing.T) {
localAddr: tcpAddrMe, localAddr: tcpAddrMe,
remoteAddr: &net.UDPAddr{IP: net.ParseIP("192.168.0.1"), Port: 8333}, remoteAddr: &net.UDPAddr{IP: net.ParseIP("192.168.0.1"), Port: 8333},
} }
msg, err = wire.NewMsgVersionFromConn(conn, nonce, lastBlock) msg, err = NewMsgVersionFromConn(conn, nonce, lastBlock)
if err != wire.ErrInvalidNetAddr { if err != ErrInvalidNetAddr {
t.Errorf("NewMsgVersionFromConn: expected error not received "+ t.Errorf("NewMsgVersionFromConn: expected error not received "+
"- got %v, want %v", err, wire.ErrInvalidNetAddr) "- got %v, want %v", err, ErrInvalidNetAddr)
} }
return return
@ -187,17 +186,17 @@ func TestVersionWire(t *testing.T) {
verRelayTxFalseEncoded[len(verRelayTxFalseEncoded)-1] = 0 verRelayTxFalseEncoded[len(verRelayTxFalseEncoded)-1] = 0
tests := []struct { tests := []struct {
in *wire.MsgVersion // Message to encode in *MsgVersion // Message to encode
out *wire.MsgVersion // Expected decoded message out *MsgVersion // Expected decoded message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version. // Latest protocol version.
{ {
baseVersionBIP0037, baseVersionBIP0037,
baseVersionBIP0037, baseVersionBIP0037,
baseVersionBIP0037Encoded, baseVersionBIP0037Encoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version BIP0037Version with relay transactions field // Protocol version BIP0037Version with relay transactions field
@ -206,7 +205,7 @@ func TestVersionWire(t *testing.T) {
baseVersionBIP0037, baseVersionBIP0037,
baseVersionBIP0037, baseVersionBIP0037,
baseVersionBIP0037Encoded, baseVersionBIP0037Encoded,
wire.BIP0037Version, BIP0037Version,
}, },
// Protocol version BIP0037Version with relay transactions field // Protocol version BIP0037Version with relay transactions field
@ -215,7 +214,7 @@ func TestVersionWire(t *testing.T) {
verRelayTxFalse, verRelayTxFalse,
verRelayTxFalse, verRelayTxFalse,
verRelayTxFalseEncoded, verRelayTxFalseEncoded,
wire.BIP0037Version, BIP0037Version,
}, },
// Protocol version BIP0035Version. // Protocol version BIP0035Version.
@ -223,7 +222,7 @@ func TestVersionWire(t *testing.T) {
baseVersion, baseVersion,
baseVersion, baseVersion,
baseVersionEncoded, baseVersionEncoded,
wire.BIP0035Version, BIP0035Version,
}, },
// Protocol version BIP0031Version. // Protocol version BIP0031Version.
@ -231,7 +230,7 @@ func TestVersionWire(t *testing.T) {
baseVersion, baseVersion,
baseVersion, baseVersion,
baseVersionEncoded, baseVersionEncoded,
wire.BIP0031Version, BIP0031Version,
}, },
// Protocol version NetAddressTimeVersion. // Protocol version NetAddressTimeVersion.
@ -239,7 +238,7 @@ func TestVersionWire(t *testing.T) {
baseVersion, baseVersion,
baseVersion, baseVersion,
baseVersionEncoded, baseVersionEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version MultipleAddressVersion. // Protocol version MultipleAddressVersion.
@ -247,7 +246,7 @@ func TestVersionWire(t *testing.T) {
baseVersion, baseVersion,
baseVersion, baseVersion,
baseVersionEncoded, baseVersionEncoded,
wire.MultipleAddressVersion, MultipleAddressVersion,
}, },
} }
@ -267,7 +266,7 @@ func TestVersionWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgVersion var msg MsgVersion
rbuf := bytes.NewBuffer(test.buf) rbuf := bytes.NewBuffer(test.buf)
err = msg.BtcDecode(rbuf, test.pver) err = msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -289,7 +288,7 @@ func TestVersionWireErrors(t *testing.T) {
// because the test data is using bytes encoded with that protocol // because the test data is using bytes encoded with that protocol
// version. // version.
pver := uint32(60002) pver := uint32(60002)
wireErr := &wire.MessageError{} wireErr := &MessageError{}
// Ensure calling MsgVersion.BtcDecode with a non *bytes.Buffer returns // Ensure calling MsgVersion.BtcDecode with a non *bytes.Buffer returns
// error. // error.
@ -302,12 +301,12 @@ func TestVersionWireErrors(t *testing.T) {
// Copy the base version and change the user agent to exceed max limits. // Copy the base version and change the user agent to exceed max limits.
bvc := *baseVersion bvc := *baseVersion
exceedUAVer := &bvc exceedUAVer := &bvc
newUA := "/" + strings.Repeat("t", wire.MaxUserAgentLen-8+1) + ":0.0.1/" newUA := "/" + strings.Repeat("t", MaxUserAgentLen-8+1) + ":0.0.1/"
exceedUAVer.UserAgent = newUA exceedUAVer.UserAgent = newUA
// Encode the new UA length as a varint. // Encode the new UA length as a varint.
var newUAVarIntBuf bytes.Buffer var newUAVarIntBuf bytes.Buffer
err := wire.TstWriteVarInt(&newUAVarIntBuf, pver, uint64(len(newUA))) err := WriteVarInt(&newUAVarIntBuf, pver, uint64(len(newUA)))
if err != nil { if err != nil {
t.Errorf("WriteVarInt: error %v", err) t.Errorf("WriteVarInt: error %v", err)
} }
@ -324,12 +323,12 @@ func TestVersionWireErrors(t *testing.T) {
copy(exceedUAVerEncoded[83+len(newUA):], baseVersionEncoded[97:100]) copy(exceedUAVerEncoded[83+len(newUA):], baseVersionEncoded[97:100])
tests := []struct { tests := []struct {
in *wire.MsgVersion // Value to encode in *MsgVersion // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Force error in protocol version. // Force error in protocol version.
{baseVersion, baseVersionEncoded, pver, 0, io.ErrShortWrite, io.EOF}, {baseVersion, baseVersionEncoded, pver, 0, io.ErrShortWrite, io.EOF},
@ -353,7 +352,7 @@ func TestVersionWireErrors(t *testing.T) {
// it's optional. // it's optional.
{ {
baseVersionBIP0037, baseVersionBIP0037Encoded, baseVersionBIP0037, baseVersionBIP0037Encoded,
wire.BIP0037Version, 101, io.ErrShortWrite, nil, BIP0037Version, 101, io.ErrShortWrite, nil,
}, },
// Force error due to user agent too big // Force error due to user agent too big
{exceedUAVer, exceedUAVerEncoded, pver, newLen, wireErr, wireErr}, {exceedUAVer, exceedUAVerEncoded, pver, newLen, wireErr, wireErr},
@ -370,9 +369,9 @@ func TestVersionWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("BtcEncode #%d wrong error got: %v, "+ t.Errorf("BtcEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -381,7 +380,7 @@ func TestVersionWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var msg wire.MsgVersion var msg MsgVersion
buf := bytes.NewBuffer(test.buf[0:test.max]) buf := bytes.NewBuffer(test.buf[0:test.max])
err = msg.BtcDecode(buf, test.pver) err = msg.BtcDecode(buf, test.pver)
if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) { if reflect.TypeOf(err) != reflect.TypeOf(test.readErr) {
@ -390,9 +389,9 @@ func TestVersionWireErrors(t *testing.T) {
continue continue
} }
// For errors which are not of type wire.MessageError, check // For errors which are not of type MessageError, check them for
// them for equality. // equality.
if _, ok := err.(*wire.MessageError); !ok { if _, ok := err.(*MessageError); !ok {
if err != test.readErr { if err != test.readErr {
t.Errorf("BtcDecode #%d wrong error got: %v, "+ t.Errorf("BtcDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)
@ -407,13 +406,13 @@ func TestVersionWireErrors(t *testing.T) {
func TestVersionOptionalFields(t *testing.T) { func TestVersionOptionalFields(t *testing.T) {
// onlyRequiredVersion is a version message that only contains the // onlyRequiredVersion is a version message that only contains the
// required versions and all other values set to their default values. // required versions and all other values set to their default values.
onlyRequiredVersion := wire.MsgVersion{ onlyRequiredVersion := MsgVersion{
ProtocolVersion: 60002, ProtocolVersion: 60002,
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST) Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST)
AddrYou: wire.NetAddress{ AddrYou: NetAddress{
Timestamp: time.Time{}, // Zero value -- no timestamp in version Timestamp: time.Time{}, // Zero value -- no timestamp in version
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
IP: net.ParseIP("192.168.0.1"), IP: net.ParseIP("192.168.0.1"),
Port: 8333, Port: 8333,
}, },
@ -424,9 +423,9 @@ func TestVersionOptionalFields(t *testing.T) {
// addrMeVersion is a version message that contains all fields through // addrMeVersion is a version message that contains all fields through
// the AddrMe field. // the AddrMe field.
addrMeVersion := onlyRequiredVersion addrMeVersion := onlyRequiredVersion
addrMeVersion.AddrMe = wire.NetAddress{ addrMeVersion.AddrMe = NetAddress{
Timestamp: time.Time{}, // Zero value -- no timestamp in version Timestamp: time.Time{}, // Zero value -- no timestamp in version
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
IP: net.ParseIP("127.0.0.1"), IP: net.ParseIP("127.0.0.1"),
Port: 8333, Port: 8333,
} }
@ -455,40 +454,40 @@ func TestVersionOptionalFields(t *testing.T) {
copy(lastBlockVersionEncoded, baseVersionEncoded) copy(lastBlockVersionEncoded, baseVersionEncoded)
tests := []struct { tests := []struct {
msg *wire.MsgVersion // Expected message msg *MsgVersion // Expected message
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
{ {
&onlyRequiredVersion, &onlyRequiredVersion,
onlyRequiredVersionEncoded, onlyRequiredVersionEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
{ {
&addrMeVersion, &addrMeVersion,
addrMeVersionEncoded, addrMeVersionEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
{ {
&nonceVersion, &nonceVersion,
nonceVersionEncoded, nonceVersionEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
{ {
&uaVersion, &uaVersion,
uaVersionEncoded, uaVersionEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
{ {
&lastBlockVersion, &lastBlockVersion,
lastBlockVersionEncoded, lastBlockVersionEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
} }
for i, test := range tests { for i, test := range tests {
// Decode the message from wire format. // Decode the message from wire format.
var msg wire.MsgVersion var msg MsgVersion
rbuf := bytes.NewBuffer(test.buf) rbuf := bytes.NewBuffer(test.buf)
err := msg.BtcDecode(rbuf, test.pver) err := msg.BtcDecode(rbuf, test.pver)
if err != nil { if err != nil {
@ -504,19 +503,19 @@ func TestVersionOptionalFields(t *testing.T) {
} }
// baseVersion is used in the various tests as a baseline MsgVersion. // baseVersion is used in the various tests as a baseline MsgVersion.
var baseVersion = &wire.MsgVersion{ var baseVersion = &MsgVersion{
ProtocolVersion: 60002, ProtocolVersion: 60002,
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST) Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST)
AddrYou: wire.NetAddress{ AddrYou: NetAddress{
Timestamp: time.Time{}, // Zero value -- no timestamp in version Timestamp: time.Time{}, // Zero value -- no timestamp in version
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
IP: net.ParseIP("192.168.0.1"), IP: net.ParseIP("192.168.0.1"),
Port: 8333, Port: 8333,
}, },
AddrMe: wire.NetAddress{ AddrMe: NetAddress{
Timestamp: time.Time{}, // Zero value -- no timestamp in version Timestamp: time.Time{}, // Zero value -- no timestamp in version
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
IP: net.ParseIP("127.0.0.1"), IP: net.ParseIP("127.0.0.1"),
Port: 8333, Port: 8333,
}, },
@ -550,19 +549,19 @@ var baseVersionEncoded = []byte{
// baseVersionBIP0037 is used in the various tests as a baseline MsgVersion for // baseVersionBIP0037 is used in the various tests as a baseline MsgVersion for
// BIP0037. // BIP0037.
var baseVersionBIP0037 = &wire.MsgVersion{ var baseVersionBIP0037 = &MsgVersion{
ProtocolVersion: 70001, ProtocolVersion: 70001,
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST) Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST)
AddrYou: wire.NetAddress{ AddrYou: NetAddress{
Timestamp: time.Time{}, // Zero value -- no timestamp in version Timestamp: time.Time{}, // Zero value -- no timestamp in version
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
IP: net.ParseIP("192.168.0.1"), IP: net.ParseIP("192.168.0.1"),
Port: 8333, Port: 8333,
}, },
AddrMe: wire.NetAddress{ AddrMe: NetAddress{
Timestamp: time.Time{}, // Zero value -- no timestamp in version Timestamp: time.Time{}, // Zero value -- no timestamp in version
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
IP: net.ParseIP("127.0.0.1"), IP: net.ParseIP("127.0.0.1"),
Port: 8333, Port: 8333,
}, },

View file

@ -1,8 +1,8 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
@ -12,7 +12,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
) )
@ -26,7 +25,7 @@ func TestNetAddress(t *testing.T) {
IP: ip, IP: ip,
Port: port, Port: port,
} }
na, err := wire.NewNetAddress(tcpAddr, 0) na, err := NewNetAddress(tcpAddr, 0)
if err != nil { if err != nil {
t.Errorf("NewNetAddress: %v", err) t.Errorf("NewNetAddress: %v", err)
} }
@ -43,24 +42,24 @@ func TestNetAddress(t *testing.T) {
t.Errorf("NetNetAddress: wrong services - got %v, want %v", t.Errorf("NetNetAddress: wrong services - got %v, want %v",
na.Services, 0) na.Services, 0)
} }
if na.HasService(wire.SFNodeNetwork) { if na.HasService(SFNodeNetwork) {
t.Errorf("HasService: SFNodeNetwork service is set") t.Errorf("HasService: SFNodeNetwork service is set")
} }
// Ensure adding the full service node flag works. // Ensure adding the full service node flag works.
na.AddService(wire.SFNodeNetwork) na.AddService(SFNodeNetwork)
if na.Services != wire.SFNodeNetwork { if na.Services != SFNodeNetwork {
t.Errorf("AddService: wrong services - got %v, want %v", t.Errorf("AddService: wrong services - got %v, want %v",
na.Services, wire.SFNodeNetwork) na.Services, SFNodeNetwork)
} }
if !na.HasService(wire.SFNodeNetwork) { if !na.HasService(SFNodeNetwork) {
t.Errorf("HasService: SFNodeNetwork service not set") t.Errorf("HasService: SFNodeNetwork service not set")
} }
// Ensure max payload is expected value for latest protocol version. // Ensure max payload is expected value for latest protocol version.
pver := wire.ProtocolVersion pver := ProtocolVersion
wantPayload := uint32(30) wantPayload := uint32(30)
maxPayload := wire.TstMaxNetAddressPayload(wire.ProtocolVersion) maxPayload := maxNetAddressPayload(ProtocolVersion)
if maxPayload != wantPayload { if maxPayload != wantPayload {
t.Errorf("maxNetAddressPayload: wrong max payload length for "+ t.Errorf("maxNetAddressPayload: wrong max payload length for "+
"protocol version %d - got %v, want %v", pver, "protocol version %d - got %v, want %v", pver,
@ -69,9 +68,9 @@ func TestNetAddress(t *testing.T) {
// Protocol version before NetAddressTimeVersion when timestamp was // Protocol version before NetAddressTimeVersion when timestamp was
// added. Ensure max payload is expected value for it. // added. Ensure max payload is expected value for it.
pver = wire.NetAddressTimeVersion - 1 pver = NetAddressTimeVersion - 1
wantPayload = 26 wantPayload = 26
maxPayload = wire.TstMaxNetAddressPayload(pver) maxPayload = maxNetAddressPayload(pver)
if maxPayload != wantPayload { if maxPayload != wantPayload {
t.Errorf("maxNetAddressPayload: wrong max payload length for "+ t.Errorf("maxNetAddressPayload: wrong max payload length for "+
"protocol version %d - got %v, want %v", pver, "protocol version %d - got %v, want %v", pver,
@ -80,10 +79,10 @@ func TestNetAddress(t *testing.T) {
// Check for expected failure on wrong address type. // Check for expected failure on wrong address type.
udpAddr := &net.UDPAddr{} udpAddr := &net.UDPAddr{}
_, err = wire.NewNetAddress(udpAddr, 0) _, err = NewNetAddress(udpAddr, 0)
if err != wire.ErrInvalidNetAddr { if err != ErrInvalidNetAddr {
t.Errorf("NewNetAddress: expected error not received - "+ t.Errorf("NewNetAddress: expected error not received - "+
"got %v, want %v", err, wire.ErrInvalidNetAddr) "got %v, want %v", err, ErrInvalidNetAddr)
} }
} }
@ -91,9 +90,9 @@ func TestNetAddress(t *testing.T) {
// protocol versions and timestamp flag combinations. // protocol versions and timestamp flag combinations.
func TestNetAddressWire(t *testing.T) { func TestNetAddressWire(t *testing.T) {
// baseNetAddr is used in the various tests as a baseline NetAddress. // baseNetAddr is used in the various tests as a baseline NetAddress.
baseNetAddr := wire.NetAddress{ baseNetAddr := NetAddress{
Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
IP: net.ParseIP("127.0.0.1"), IP: net.ParseIP("127.0.0.1"),
Port: 8333, Port: 8333,
} }
@ -121,11 +120,11 @@ func TestNetAddressWire(t *testing.T) {
} }
tests := []struct { tests := []struct {
in wire.NetAddress // NetAddress to encode in NetAddress // NetAddress to encode
out wire.NetAddress // Expected decoded NetAddress out NetAddress // Expected decoded NetAddress
ts bool // Include timestamp? ts bool // Include timestamp?
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
}{ }{
// Latest protocol version without ts flag. // Latest protocol version without ts flag.
{ {
@ -133,7 +132,7 @@ func TestNetAddressWire(t *testing.T) {
baseNetAddrNoTS, baseNetAddrNoTS,
false, false,
baseNetAddrNoTSEncoded, baseNetAddrNoTSEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Latest protocol version with ts flag. // Latest protocol version with ts flag.
@ -142,7 +141,7 @@ func TestNetAddressWire(t *testing.T) {
baseNetAddr, baseNetAddr,
true, true,
baseNetAddrEncoded, baseNetAddrEncoded,
wire.ProtocolVersion, ProtocolVersion,
}, },
// Protocol version NetAddressTimeVersion without ts flag. // Protocol version NetAddressTimeVersion without ts flag.
@ -151,7 +150,7 @@ func TestNetAddressWire(t *testing.T) {
baseNetAddrNoTS, baseNetAddrNoTS,
false, false,
baseNetAddrNoTSEncoded, baseNetAddrNoTSEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version NetAddressTimeVersion with ts flag. // Protocol version NetAddressTimeVersion with ts flag.
@ -160,7 +159,7 @@ func TestNetAddressWire(t *testing.T) {
baseNetAddr, baseNetAddr,
true, true,
baseNetAddrEncoded, baseNetAddrEncoded,
wire.NetAddressTimeVersion, NetAddressTimeVersion,
}, },
// Protocol version NetAddressTimeVersion-1 without ts flag. // Protocol version NetAddressTimeVersion-1 without ts flag.
@ -169,7 +168,7 @@ func TestNetAddressWire(t *testing.T) {
baseNetAddrNoTS, baseNetAddrNoTS,
false, false,
baseNetAddrNoTSEncoded, baseNetAddrNoTSEncoded,
wire.NetAddressTimeVersion - 1, NetAddressTimeVersion - 1,
}, },
// Protocol version NetAddressTimeVersion-1 with timestamp. // Protocol version NetAddressTimeVersion-1 with timestamp.
@ -181,7 +180,7 @@ func TestNetAddressWire(t *testing.T) {
baseNetAddrNoTS, baseNetAddrNoTS,
true, true,
baseNetAddrNoTSEncoded, baseNetAddrNoTSEncoded,
wire.NetAddressTimeVersion - 1, NetAddressTimeVersion - 1,
}, },
} }
@ -189,7 +188,7 @@ func TestNetAddressWire(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
var buf bytes.Buffer var buf bytes.Buffer
err := wire.TstWriteNetAddress(&buf, test.pver, &test.in, test.ts) err := writeNetAddress(&buf, test.pver, &test.in, test.ts)
if err != nil { if err != nil {
t.Errorf("writeNetAddress #%d error %v", i, err) t.Errorf("writeNetAddress #%d error %v", i, err)
continue continue
@ -201,9 +200,9 @@ func TestNetAddressWire(t *testing.T) {
} }
// Decode the message from wire format. // Decode the message from wire format.
var na wire.NetAddress var na NetAddress
rbuf := bytes.NewReader(test.buf) rbuf := bytes.NewReader(test.buf)
err = wire.TstReadNetAddress(rbuf, test.pver, &na, test.ts) err = readNetAddress(rbuf, test.pver, &na, test.ts)
if err != nil { if err != nil {
t.Errorf("readNetAddress #%d error %v", i, err) t.Errorf("readNetAddress #%d error %v", i, err)
continue continue
@ -219,25 +218,25 @@ func TestNetAddressWire(t *testing.T) {
// TestNetAddressWireErrors performs negative tests against wire encode and // TestNetAddressWireErrors performs negative tests against wire encode and
// decode NetAddress to confirm error paths work correctly. // decode NetAddress to confirm error paths work correctly.
func TestNetAddressWireErrors(t *testing.T) { func TestNetAddressWireErrors(t *testing.T) {
pver := wire.ProtocolVersion pver := ProtocolVersion
pverNAT := wire.NetAddressTimeVersion - 1 pverNAT := NetAddressTimeVersion - 1
// baseNetAddr is used in the various tests as a baseline NetAddress. // baseNetAddr is used in the various tests as a baseline NetAddress.
baseNetAddr := wire.NetAddress{ baseNetAddr := NetAddress{
Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST Timestamp: time.Unix(0x495fab29, 0), // 2009-01-03 12:15:05 -0600 CST
Services: wire.SFNodeNetwork, Services: SFNodeNetwork,
IP: net.ParseIP("127.0.0.1"), IP: net.ParseIP("127.0.0.1"),
Port: 8333, Port: 8333,
} }
tests := []struct { tests := []struct {
in *wire.NetAddress // Value to encode in *NetAddress // Value to encode
buf []byte // Wire encoding buf []byte // Wire encoding
pver uint32 // Protocol version for wire encoding pver uint32 // Protocol version for wire encoding
ts bool // Include timestamp flag ts bool // Include timestamp flag
max int // Max size of fixed buffer to induce errors max int // Max size of fixed buffer to induce errors
writeErr error // Expected write error writeErr error // Expected write error
readErr error // Expected read error readErr error // Expected read error
}{ }{
// Latest protocol version with timestamp and intentional // Latest protocol version with timestamp and intentional
// read/write errors. // read/write errors.
@ -274,7 +273,7 @@ func TestNetAddressWireErrors(t *testing.T) {
for i, test := range tests { for i, test := range tests {
// Encode to wire format. // Encode to wire format.
w := newFixedWriter(test.max) w := newFixedWriter(test.max)
err := wire.TstWriteNetAddress(w, test.pver, test.in, test.ts) err := writeNetAddress(w, test.pver, test.in, test.ts)
if err != test.writeErr { if err != test.writeErr {
t.Errorf("writeNetAddress #%d wrong error got: %v, want: %v", t.Errorf("writeNetAddress #%d wrong error got: %v, want: %v",
i, err, test.writeErr) i, err, test.writeErr)
@ -282,9 +281,9 @@ func TestNetAddressWireErrors(t *testing.T) {
} }
// Decode from wire format. // Decode from wire format.
var na wire.NetAddress var na NetAddress
r := newFixedReader(test.max, test.buf) r := newFixedReader(test.max, test.buf)
err = wire.TstReadNetAddress(r, test.pver, &na, test.ts) err = readNetAddress(r, test.pver, &na, test.ts)
if err != test.readErr { if err != test.readErr {
t.Errorf("readNetAddress #%d wrong error got: %v, want: %v", t.Errorf("readNetAddress #%d wrong error got: %v, want: %v",
i, err, test.readErr) i, err, test.readErr)

View file

@ -1,25 +1,21 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import "testing"
"testing"
"github.com/btcsuite/btcd/wire"
)
// TestServiceFlagStringer tests the stringized output for service flag types. // TestServiceFlagStringer tests the stringized output for service flag types.
func TestServiceFlagStringer(t *testing.T) { func TestServiceFlagStringer(t *testing.T) {
tests := []struct { tests := []struct {
in wire.ServiceFlag in ServiceFlag
want string want string
}{ }{
{0, "0x0"}, {0, "0x0"},
{wire.SFNodeNetwork, "SFNodeNetwork"}, {SFNodeNetwork, "SFNodeNetwork"},
{wire.SFNodeGetUTXO, "SFNodeGetUTXO"}, {SFNodeGetUTXO, "SFNodeGetUTXO"},
{wire.SFNodeBloom, "SFNodeBloom"}, {SFNodeBloom, "SFNodeBloom"},
{0xffffffff, "SFNodeNetwork|SFNodeGetUTXO|SFNodeBloom|0xfffffff8"}, {0xffffffff, "SFNodeNetwork|SFNodeGetUTXO|SFNodeBloom|0xfffffff8"},
} }
@ -37,13 +33,13 @@ func TestServiceFlagStringer(t *testing.T) {
// TestBitcoinNetStringer tests the stringized output for bitcoin net types. // TestBitcoinNetStringer tests the stringized output for bitcoin net types.
func TestBitcoinNetStringer(t *testing.T) { func TestBitcoinNetStringer(t *testing.T) {
tests := []struct { tests := []struct {
in wire.BitcoinNet in BitcoinNet
want string want string
}{ }{
{wire.MainNet, "MainNet"}, {MainNet, "MainNet"},
{wire.TestNet, "TestNet"}, {TestNet, "TestNet"},
{wire.TestNet3, "TestNet3"}, {TestNet3, "TestNet3"},
{wire.SimNet, "SimNet"}, {SimNet, "SimNet"},
{0xffffffff, "Unknown BitcoinNet (4294967295)"}, {0xffffffff, "Unknown BitcoinNet (4294967295)"},
} }

View file

@ -1,15 +1,13 @@
// Copyright (c) 2013-2015 The btcsuite developers // Copyright (c) 2013-2016 The btcsuite developers
// Use of this source code is governed by an ISC // Use of this source code is governed by an ISC
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package wire_test package wire
import ( import (
"bytes" "bytes"
"encoding/hex" "encoding/hex"
"testing" "testing"
"github.com/btcsuite/btcd/wire"
) )
// TestShaHash tests the ShaHash API. // TestShaHash tests the ShaHash API.
@ -17,7 +15,7 @@ func TestShaHash(t *testing.T) {
// Hash of block 234439. // Hash of block 234439.
blockHashStr := "14a0810ac680a3eb3f82edc878cea25ec41d6b790744e5daeef" blockHashStr := "14a0810ac680a3eb3f82edc878cea25ec41d6b790744e5daeef"
blockHash, err := wire.NewShaHashFromStr(blockHashStr) blockHash, err := NewShaHashFromStr(blockHashStr)
if err != nil { if err != nil {
t.Errorf("NewShaHashFromStr: %v", err) t.Errorf("NewShaHashFromStr: %v", err)
} }
@ -30,15 +28,15 @@ func TestShaHash(t *testing.T) {
0xa6, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa6, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
} }
hash, err := wire.NewShaHash(buf) hash, err := NewShaHash(buf)
if err != nil { if err != nil {
t.Errorf("NewShaHash: unexpected error %v", err) t.Errorf("NewShaHash: unexpected error %v", err)
} }
// Ensure proper size. // Ensure proper size.
if len(hash) != wire.HashSize { if len(hash) != HashSize {
t.Errorf("NewShaHash: hash length mismatch - got: %v, want: %v", t.Errorf("NewShaHash: hash length mismatch - got: %v, want: %v",
len(hash), wire.HashSize) len(hash), HashSize)
} }
// Ensure contents match. // Ensure contents match.
@ -70,8 +68,8 @@ func TestShaHash(t *testing.T) {
} }
// Invalid size for NewShaHash. // Invalid size for NewShaHash.
invalidHash := make([]byte, wire.HashSize+1) invalidHash := make([]byte, HashSize+1)
_, err = wire.NewShaHash(invalidHash) _, err = NewShaHash(invalidHash)
if err == nil { if err == nil {
t.Errorf("NewShaHash: failed to received expected err - got: nil") t.Errorf("NewShaHash: failed to received expected err - got: nil")
} }
@ -81,7 +79,7 @@ func TestShaHash(t *testing.T) {
func TestShaHashString(t *testing.T) { func TestShaHashString(t *testing.T) {
// Block 100000 hash. // Block 100000 hash.
wantStr := "000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506" wantStr := "000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
hash := wire.ShaHash([wire.HashSize]byte{ // Make go vet happy. hash := ShaHash([HashSize]byte{ // Make go vet happy.
0x06, 0xe5, 0x33, 0xfd, 0x1a, 0xda, 0x86, 0x39, 0x06, 0xe5, 0x33, 0xfd, 0x1a, 0xda, 0x86, 0x39,
0x1f, 0x3f, 0x6c, 0x34, 0x32, 0x04, 0xb0, 0xd2, 0x1f, 0x3f, 0x6c, 0x34, 0x32, 0x04, 0xb0, 0xd2,
0x78, 0xd4, 0xaa, 0xec, 0x1c, 0x0b, 0x20, 0xaa, 0x78, 0xd4, 0xaa, 0xec, 0x1c, 0x0b, 0x20, 0xaa,
@ -99,7 +97,7 @@ func TestShaHashString(t *testing.T) {
func TestNewShaHashFromStr(t *testing.T) { func TestNewShaHashFromStr(t *testing.T) {
tests := []struct { tests := []struct {
in string in string
want wire.ShaHash want ShaHash
err error err error
}{ }{
// Genesis hash. // Genesis hash.
@ -119,14 +117,14 @@ func TestNewShaHashFromStr(t *testing.T) {
// Empty string. // Empty string.
{ {
"", "",
wire.ShaHash{}, ShaHash{},
nil, nil,
}, },
// Single digit hash. // Single digit hash.
{ {
"1", "1",
wire.ShaHash([wire.HashSize]byte{ // Make go vet happy. ShaHash([HashSize]byte{ // Make go vet happy.
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 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, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
@ -138,7 +136,7 @@ func TestNewShaHashFromStr(t *testing.T) {
// Block 203707 with stripped leading zeros. // Block 203707 with stripped leading zeros.
{ {
"3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc", "3264bc2ac36a60840790ba1d475d01367e7c723da941069e9dc",
wire.ShaHash([wire.HashSize]byte{ // Make go vet happy. ShaHash([HashSize]byte{ // Make go vet happy.
0xdc, 0xe9, 0x69, 0x10, 0x94, 0xda, 0x23, 0xc7, 0xdc, 0xe9, 0x69, 0x10, 0x94, 0xda, 0x23, 0xc7,
0xe7, 0x67, 0x13, 0xd0, 0x75, 0xd4, 0xa1, 0x0b, 0xe7, 0x67, 0x13, 0xd0, 0x75, 0xd4, 0xa1, 0x0b,
0x79, 0x40, 0x08, 0xa6, 0x36, 0xac, 0xc2, 0x4b, 0x79, 0x40, 0x08, 0xa6, 0x36, 0xac, 0xc2, 0x4b,
@ -150,14 +148,14 @@ func TestNewShaHashFromStr(t *testing.T) {
// Hash string that is too long. // Hash string that is too long.
{ {
"01234567890123456789012345678901234567890123456789012345678912345", "01234567890123456789012345678901234567890123456789012345678912345",
wire.ShaHash{}, ShaHash{},
wire.ErrHashStrSize, ErrHashStrSize,
}, },
// Hash string that is contains non-hex chars. // Hash string that is contains non-hex chars.
{ {
"abcdefg", "abcdefg",
wire.ShaHash{}, ShaHash{},
hex.InvalidByteError('g'), hex.InvalidByteError('g'),
}, },
} }
@ -166,7 +164,7 @@ func TestNewShaHashFromStr(t *testing.T) {
unexpectedResultStr := "NewShaHashFromStr #%d got: %v want: %v" unexpectedResultStr := "NewShaHashFromStr #%d got: %v want: %v"
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
result, err := wire.NewShaHashFromStr(test.in) result, err := NewShaHashFromStr(test.in)
if err != test.err { if err != test.err {
t.Errorf(unexpectedErrStr, i, err, test.err) t.Errorf(unexpectedErrStr, i, err, test.err)
continue continue