github.com/dashpay/godash@v0.0.0-20160726055534-e038a21e0e3d/wire/common_test.go (about)

     1  // Copyright (c) 2013-2015 The btcsuite developers
     2  // Copyright (c) 2016 The Dash developers
     3  // Use of this source code is governed by an ISC
     4  // license that can be found in the LICENSE file.
     5  
     6  package wire_test
     7  
     8  import (
     9  	"bytes"
    10  	"fmt"
    11  	"io"
    12  	"reflect"
    13  	"strings"
    14  	"testing"
    15  
    16  	"github.com/dashpay/godash/wire"
    17  	"github.com/davecgh/go-spew/spew"
    18  )
    19  
    20  // mainNetGenesisHash is the hash of the first block in the block chain for the
    21  // main network (genesis block).
    22  var mainNetGenesisHash = wire.ShaHash([wire.HashSize]byte{ // Make go vet happy.
    23  	0x6f, 0xe2, 0x8c, 0x0a, 0xb6, 0xf1, 0xb3, 0x72,
    24  	0xc1, 0xa6, 0xa2, 0x46, 0xae, 0x63, 0xf7, 0x4f,
    25  	0x93, 0x1e, 0x83, 0x65, 0xe1, 0x5a, 0x08, 0x9c,
    26  	0x68, 0xd6, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
    27  })
    28  
    29  // mainNetGenesisMerkleRoot is the hash of the first transaction in the genesis
    30  // block for the main network.
    31  var mainNetGenesisMerkleRoot = wire.ShaHash([wire.HashSize]byte{ // Make go vet happy.
    32  	0x3b, 0xa3, 0xed, 0xfd, 0x7a, 0x7b, 0x12, 0xb2,
    33  	0x7a, 0xc7, 0x2c, 0x3e, 0x67, 0x76, 0x8f, 0x61,
    34  	0x7f, 0xc8, 0x1b, 0xc3, 0x88, 0x8a, 0x51, 0x32,
    35  	0x3a, 0x9f, 0xb8, 0xaa, 0x4b, 0x1e, 0x5e, 0x4a,
    36  })
    37  
    38  // fakeRandReader implements the io.Reader interface and is used to force
    39  // errors in the RandomUint64 function.
    40  type fakeRandReader struct {
    41  	n   int
    42  	err error
    43  }
    44  
    45  // Read returns the fake reader error and the lesser of the fake reader value
    46  // and the length of p.
    47  func (r *fakeRandReader) Read(p []byte) (int, error) {
    48  	n := r.n
    49  	if n > len(p) {
    50  		n = len(p)
    51  	}
    52  	return n, r.err
    53  }
    54  
    55  // TestElementWire tests wire encode and decode for various element types.  This
    56  // is mainly to test the "fast" paths in readElement and writeElement which use
    57  // type assertions to avoid reflection when possible.
    58  func TestElementWire(t *testing.T) {
    59  	type writeElementReflect int32
    60  
    61  	tests := []struct {
    62  		in  interface{} // Value to encode
    63  		buf []byte      // Wire encoding
    64  	}{
    65  		{int32(1), []byte{0x01, 0x00, 0x00, 0x00}},
    66  		{uint32(256), []byte{0x00, 0x01, 0x00, 0x00}},
    67  		{
    68  			int64(65536),
    69  			[]byte{0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00},
    70  		},
    71  		{
    72  			uint64(4294967296),
    73  			[]byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00},
    74  		},
    75  		{
    76  			true,
    77  			[]byte{0x01},
    78  		},
    79  		{
    80  			false,
    81  			[]byte{0x00},
    82  		},
    83  		{
    84  			[4]byte{0x01, 0x02, 0x03, 0x04},
    85  			[]byte{0x01, 0x02, 0x03, 0x04},
    86  		},
    87  		{
    88  			[wire.CommandSize]byte{
    89  				0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
    90  				0x09, 0x0a, 0x0b, 0x0c,
    91  			},
    92  			[]byte{
    93  				0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
    94  				0x09, 0x0a, 0x0b, 0x0c,
    95  			},
    96  		},
    97  		{
    98  			[16]byte{
    99  				0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   100  				0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
   101  			},
   102  			[]byte{
   103  				0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   104  				0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
   105  			},
   106  		},
   107  		{
   108  			(*wire.ShaHash)(&[wire.HashSize]byte{ // Make go vet happy.
   109  				0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   110  				0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
   111  				0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
   112  				0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
   113  			}),
   114  			[]byte{
   115  				0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   116  				0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
   117  				0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
   118  				0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
   119  			},
   120  		},
   121  		{
   122  			wire.ServiceFlag(wire.SFNodeNetwork),
   123  			[]byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
   124  		},
   125  		{
   126  			wire.InvType(wire.InvTypeTx),
   127  			[]byte{0x01, 0x00, 0x00, 0x00},
   128  		},
   129  		{
   130  			wire.BitcoinNet(wire.MainNet),
   131  			[]byte{0xf9, 0xbe, 0xb4, 0xd9},
   132  		},
   133  		// Type not supported by the "fast" path and requires reflection.
   134  		{
   135  			writeElementReflect(1),
   136  			[]byte{0x01, 0x00, 0x00, 0x00},
   137  		},
   138  	}
   139  
   140  	t.Logf("Running %d tests", len(tests))
   141  	for i, test := range tests {
   142  		// Write to wire format.
   143  		var buf bytes.Buffer
   144  		err := wire.TstWriteElement(&buf, test.in)
   145  		if err != nil {
   146  			t.Errorf("writeElement #%d error %v", i, err)
   147  			continue
   148  		}
   149  		if !bytes.Equal(buf.Bytes(), test.buf) {
   150  			t.Errorf("writeElement #%d\n got: %s want: %s", i,
   151  				spew.Sdump(buf.Bytes()), spew.Sdump(test.buf))
   152  			continue
   153  		}
   154  
   155  		// Read from wire format.
   156  		rbuf := bytes.NewReader(test.buf)
   157  		val := test.in
   158  		if reflect.ValueOf(test.in).Kind() != reflect.Ptr {
   159  			val = reflect.New(reflect.TypeOf(test.in)).Interface()
   160  		}
   161  		err = wire.TstReadElement(rbuf, val)
   162  		if err != nil {
   163  			t.Errorf("readElement #%d error %v", i, err)
   164  			continue
   165  		}
   166  		ival := val
   167  		if reflect.ValueOf(test.in).Kind() != reflect.Ptr {
   168  			ival = reflect.Indirect(reflect.ValueOf(val)).Interface()
   169  		}
   170  		if !reflect.DeepEqual(ival, test.in) {
   171  			t.Errorf("readElement #%d\n got: %s want: %s", i,
   172  				spew.Sdump(ival), spew.Sdump(test.in))
   173  			continue
   174  		}
   175  	}
   176  }
   177  
   178  // TestElementWireErrors performs negative tests against wire encode and decode
   179  // of various element types to confirm error paths work correctly.
   180  func TestElementWireErrors(t *testing.T) {
   181  	tests := []struct {
   182  		in       interface{} // Value to encode
   183  		max      int         // Max size of fixed buffer to induce errors
   184  		writeErr error       // Expected write error
   185  		readErr  error       // Expected read error
   186  	}{
   187  		{int32(1), 0, io.ErrShortWrite, io.EOF},
   188  		{uint32(256), 0, io.ErrShortWrite, io.EOF},
   189  		{int64(65536), 0, io.ErrShortWrite, io.EOF},
   190  		{true, 0, io.ErrShortWrite, io.EOF},
   191  		{[4]byte{0x01, 0x02, 0x03, 0x04}, 0, io.ErrShortWrite, io.EOF},
   192  		{
   193  			[wire.CommandSize]byte{
   194  				0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   195  				0x09, 0x0a, 0x0b, 0x0c,
   196  			},
   197  			0, io.ErrShortWrite, io.EOF,
   198  		},
   199  		{
   200  			[16]byte{
   201  				0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   202  				0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
   203  			},
   204  			0, io.ErrShortWrite, io.EOF,
   205  		},
   206  		{
   207  			(*wire.ShaHash)(&[wire.HashSize]byte{ // Make go vet happy.
   208  				0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
   209  				0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
   210  				0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
   211  				0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
   212  			}),
   213  			0, io.ErrShortWrite, io.EOF,
   214  		},
   215  		{wire.ServiceFlag(wire.SFNodeNetwork), 0, io.ErrShortWrite, io.EOF},
   216  		{wire.InvType(wire.InvTypeTx), 0, io.ErrShortWrite, io.EOF},
   217  		{wire.BitcoinNet(wire.MainNet), 0, io.ErrShortWrite, io.EOF},
   218  	}
   219  
   220  	t.Logf("Running %d tests", len(tests))
   221  	for i, test := range tests {
   222  		// Encode to wire format.
   223  		w := newFixedWriter(test.max)
   224  		err := wire.TstWriteElement(w, test.in)
   225  		if err != test.writeErr {
   226  			t.Errorf("writeElement #%d wrong error got: %v, want: %v",
   227  				i, err, test.writeErr)
   228  			continue
   229  		}
   230  
   231  		// Decode from wire format.
   232  		r := newFixedReader(test.max, nil)
   233  		val := test.in
   234  		if reflect.ValueOf(test.in).Kind() != reflect.Ptr {
   235  			val = reflect.New(reflect.TypeOf(test.in)).Interface()
   236  		}
   237  		err = wire.TstReadElement(r, val)
   238  		if err != test.readErr {
   239  			t.Errorf("readElement #%d wrong error got: %v, want: %v",
   240  				i, err, test.readErr)
   241  			continue
   242  		}
   243  	}
   244  }
   245  
   246  // TestVarIntWire tests wire encode and decode for variable length integers.
   247  func TestVarIntWire(t *testing.T) {
   248  	pver := wire.ProtocolVersion
   249  
   250  	tests := []struct {
   251  		in   uint64 // Value to encode
   252  		out  uint64 // Expected decoded value
   253  		buf  []byte // Wire encoding
   254  		pver uint32 // Protocol version for wire encoding
   255  	}{
   256  		// Latest protocol version.
   257  		// Single byte
   258  		{0, 0, []byte{0x00}, pver},
   259  		// Max single byte
   260  		{0xfc, 0xfc, []byte{0xfc}, pver},
   261  		// Min 2-byte
   262  		{0xfd, 0xfd, []byte{0xfd, 0x0fd, 0x00}, pver},
   263  		// Max 2-byte
   264  		{0xffff, 0xffff, []byte{0xfd, 0xff, 0xff}, pver},
   265  		// Min 4-byte
   266  		{0x10000, 0x10000, []byte{0xfe, 0x00, 0x00, 0x01, 0x00}, pver},
   267  		// Max 4-byte
   268  		{0xffffffff, 0xffffffff, []byte{0xfe, 0xff, 0xff, 0xff, 0xff}, pver},
   269  		// Min 8-byte
   270  		{
   271  			0x100000000, 0x100000000,
   272  			[]byte{0xff, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00},
   273  			pver,
   274  		},
   275  		// Max 8-byte
   276  		{
   277  			0xffffffffffffffff, 0xffffffffffffffff,
   278  			[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
   279  			pver,
   280  		},
   281  	}
   282  
   283  	t.Logf("Running %d tests", len(tests))
   284  	for i, test := range tests {
   285  		// Encode to wire format.
   286  		var buf bytes.Buffer
   287  		err := wire.TstWriteVarInt(&buf, test.pver, test.in)
   288  		if err != nil {
   289  			t.Errorf("WriteVarInt #%d error %v", i, err)
   290  			continue
   291  		}
   292  		if !bytes.Equal(buf.Bytes(), test.buf) {
   293  			t.Errorf("WriteVarInt #%d\n got: %s want: %s", i,
   294  				spew.Sdump(buf.Bytes()), spew.Sdump(test.buf))
   295  			continue
   296  		}
   297  
   298  		// Decode from wire format.
   299  		rbuf := bytes.NewReader(test.buf)
   300  		val, err := wire.TstReadVarInt(rbuf, test.pver)
   301  		if err != nil {
   302  			t.Errorf("ReadVarInt #%d error %v", i, err)
   303  			continue
   304  		}
   305  		if val != test.out {
   306  			t.Errorf("ReadVarInt #%d\n got: %d want: %d", i,
   307  				val, test.out)
   308  			continue
   309  		}
   310  	}
   311  }
   312  
   313  // TestVarIntWireErrors performs negative tests against wire encode and decode
   314  // of variable length integers to confirm error paths work correctly.
   315  func TestVarIntWireErrors(t *testing.T) {
   316  	pver := wire.ProtocolVersion
   317  
   318  	tests := []struct {
   319  		in       uint64 // Value to encode
   320  		buf      []byte // Wire encoding
   321  		pver     uint32 // Protocol version for wire encoding
   322  		max      int    // Max size of fixed buffer to induce errors
   323  		writeErr error  // Expected write error
   324  		readErr  error  // Expected read error
   325  	}{
   326  		// Force errors on discriminant.
   327  		{0, []byte{0x00}, pver, 0, io.ErrShortWrite, io.EOF},
   328  		// Force errors on 2-byte read/write.
   329  		{0xfd, []byte{0xfd}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
   330  		// Force errors on 4-byte read/write.
   331  		{0x10000, []byte{0xfe}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
   332  		// Force errors on 8-byte read/write.
   333  		{0x100000000, []byte{0xff}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
   334  	}
   335  
   336  	t.Logf("Running %d tests", len(tests))
   337  	for i, test := range tests {
   338  		// Encode to wire format.
   339  		w := newFixedWriter(test.max)
   340  		err := wire.TstWriteVarInt(w, test.pver, test.in)
   341  		if err != test.writeErr {
   342  			t.Errorf("WriteVarInt #%d wrong error got: %v, want: %v",
   343  				i, err, test.writeErr)
   344  			continue
   345  		}
   346  
   347  		// Decode from wire format.
   348  		r := newFixedReader(test.max, test.buf)
   349  		_, err = wire.TstReadVarInt(r, test.pver)
   350  		if err != test.readErr {
   351  			t.Errorf("ReadVarInt #%d wrong error got: %v, want: %v",
   352  				i, err, test.readErr)
   353  			continue
   354  		}
   355  	}
   356  }
   357  
   358  // TestVarIntNonCanonical ensures variable length integers that are not encoded
   359  // canonically return the expected error.
   360  func TestVarIntNonCanonical(t *testing.T) {
   361  	pver := wire.ProtocolVersion
   362  
   363  	tests := []struct {
   364  		name string // Test name for easier identification
   365  		in   []byte // Value to decode
   366  		pver uint32 // Protocol version for wire encoding
   367  	}{
   368  		{
   369  			"0 encoded with 3 bytes", []byte{0xfd, 0x00, 0x00},
   370  			pver,
   371  		},
   372  		{
   373  			"max single-byte value encoded with 3 bytes",
   374  			[]byte{0xfd, 0xfc, 0x00}, pver,
   375  		},
   376  		{
   377  			"0 encoded with 5 bytes",
   378  			[]byte{0xfe, 0x00, 0x00, 0x00, 0x00}, pver,
   379  		},
   380  		{
   381  			"max three-byte value encoded with 5 bytes",
   382  			[]byte{0xfe, 0xff, 0xff, 0x00, 0x00}, pver,
   383  		},
   384  		{
   385  			"0 encoded with 9 bytes",
   386  			[]byte{0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
   387  			pver,
   388  		},
   389  		{
   390  			"max five-byte value encoded with 9 bytes",
   391  			[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00},
   392  			pver,
   393  		},
   394  	}
   395  
   396  	t.Logf("Running %d tests", len(tests))
   397  	for i, test := range tests {
   398  		// Decode from wire format.
   399  		rbuf := bytes.NewReader(test.in)
   400  		val, err := wire.TstReadVarInt(rbuf, test.pver)
   401  		if _, ok := err.(*wire.MessageError); !ok {
   402  			t.Errorf("ReadVarInt #%d (%s) unexpected error %v", i,
   403  				test.name, err)
   404  			continue
   405  		}
   406  		if val != 0 {
   407  			t.Errorf("ReadVarInt #%d (%s)\n got: %d want: 0", i,
   408  				test.name, val)
   409  			continue
   410  		}
   411  	}
   412  }
   413  
   414  // TestVarIntWire tests the serialize size for variable length integers.
   415  func TestVarIntSerializeSize(t *testing.T) {
   416  	tests := []struct {
   417  		val  uint64 // Value to get the serialized size for
   418  		size int    // Expected serialized size
   419  	}{
   420  		// Single byte
   421  		{0, 1},
   422  		// Max single byte
   423  		{0xfc, 1},
   424  		// Min 2-byte
   425  		{0xfd, 3},
   426  		// Max 2-byte
   427  		{0xffff, 3},
   428  		// Min 4-byte
   429  		{0x10000, 5},
   430  		// Max 4-byte
   431  		{0xffffffff, 5},
   432  		// Min 8-byte
   433  		{0x100000000, 9},
   434  		// Max 8-byte
   435  		{0xffffffffffffffff, 9},
   436  	}
   437  
   438  	t.Logf("Running %d tests", len(tests))
   439  	for i, test := range tests {
   440  		serializedSize := wire.VarIntSerializeSize(test.val)
   441  		if serializedSize != test.size {
   442  			t.Errorf("VarIntSerializeSize #%d got: %d, want: %d", i,
   443  				serializedSize, test.size)
   444  			continue
   445  		}
   446  	}
   447  }
   448  
   449  // TestVarStringWire tests wire encode and decode for variable length strings.
   450  func TestVarStringWire(t *testing.T) {
   451  	pver := wire.ProtocolVersion
   452  
   453  	// str256 is a string that takes a 2-byte varint to encode.
   454  	str256 := strings.Repeat("test", 64)
   455  
   456  	tests := []struct {
   457  		in   string // String to encode
   458  		out  string // String to decoded value
   459  		buf  []byte // Wire encoding
   460  		pver uint32 // Protocol version for wire encoding
   461  	}{
   462  		// Latest protocol version.
   463  		// Empty string
   464  		{"", "", []byte{0x00}, pver},
   465  		// Single byte varint + string
   466  		{"Test", "Test", append([]byte{0x04}, []byte("Test")...), pver},
   467  		// 2-byte varint + string
   468  		{str256, str256, append([]byte{0xfd, 0x00, 0x01}, []byte(str256)...), pver},
   469  	}
   470  
   471  	t.Logf("Running %d tests", len(tests))
   472  	for i, test := range tests {
   473  		// Encode to wire format.
   474  		var buf bytes.Buffer
   475  		err := wire.WriteVarString(&buf, test.pver, test.in)
   476  		if err != nil {
   477  			t.Errorf("WriteVarString #%d error %v", i, err)
   478  			continue
   479  		}
   480  		if !bytes.Equal(buf.Bytes(), test.buf) {
   481  			t.Errorf("WriteVarString #%d\n got: %s want: %s", i,
   482  				spew.Sdump(buf.Bytes()), spew.Sdump(test.buf))
   483  			continue
   484  		}
   485  
   486  		// Decode from wire format.
   487  		rbuf := bytes.NewReader(test.buf)
   488  		val, err := wire.ReadVarString(rbuf, test.pver)
   489  		if err != nil {
   490  			t.Errorf("ReadVarString #%d error %v", i, err)
   491  			continue
   492  		}
   493  		if val != test.out {
   494  			t.Errorf("ReadVarString #%d\n got: %s want: %s", i,
   495  				val, test.out)
   496  			continue
   497  		}
   498  	}
   499  }
   500  
   501  // TestVarStringWireErrors performs negative tests against wire encode and
   502  // decode of variable length strings to confirm error paths work correctly.
   503  func TestVarStringWireErrors(t *testing.T) {
   504  	pver := wire.ProtocolVersion
   505  
   506  	// str256 is a string that takes a 2-byte varint to encode.
   507  	str256 := strings.Repeat("test", 64)
   508  
   509  	tests := []struct {
   510  		in       string // Value to encode
   511  		buf      []byte // Wire encoding
   512  		pver     uint32 // Protocol version for wire encoding
   513  		max      int    // Max size of fixed buffer to induce errors
   514  		writeErr error  // Expected write error
   515  		readErr  error  // Expected read error
   516  	}{
   517  		// Latest protocol version with intentional read/write errors.
   518  		// Force errors on empty string.
   519  		{"", []byte{0x00}, pver, 0, io.ErrShortWrite, io.EOF},
   520  		// Force error on single byte varint + string.
   521  		{"Test", []byte{0x04}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
   522  		// Force errors on 2-byte varint + string.
   523  		{str256, []byte{0xfd}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
   524  	}
   525  
   526  	t.Logf("Running %d tests", len(tests))
   527  	for i, test := range tests {
   528  		// Encode to wire format.
   529  		w := newFixedWriter(test.max)
   530  		err := wire.WriteVarString(w, test.pver, test.in)
   531  		if err != test.writeErr {
   532  			t.Errorf("WriteVarString #%d wrong error got: %v, want: %v",
   533  				i, err, test.writeErr)
   534  			continue
   535  		}
   536  
   537  		// Decode from wire format.
   538  		r := newFixedReader(test.max, test.buf)
   539  		_, err = wire.ReadVarString(r, test.pver)
   540  		if err != test.readErr {
   541  			t.Errorf("ReadVarString #%d wrong error got: %v, want: %v",
   542  				i, err, test.readErr)
   543  			continue
   544  		}
   545  	}
   546  }
   547  
   548  // TestVarStringOverflowErrors performs tests to ensure deserializing variable
   549  // length strings intentionally crafted to use large values for the string
   550  // length are handled properly.  This could otherwise potentially be used as an
   551  // attack vector.
   552  func TestVarStringOverflowErrors(t *testing.T) {
   553  	pver := wire.ProtocolVersion
   554  
   555  	tests := []struct {
   556  		buf  []byte // Wire encoding
   557  		pver uint32 // Protocol version for wire encoding
   558  		err  error  // Expected error
   559  	}{
   560  		{[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
   561  			pver, &wire.MessageError{}},
   562  		{[]byte{0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
   563  			pver, &wire.MessageError{}},
   564  	}
   565  
   566  	t.Logf("Running %d tests", len(tests))
   567  	for i, test := range tests {
   568  		// Decode from wire format.
   569  		rbuf := bytes.NewReader(test.buf)
   570  		_, err := wire.ReadVarString(rbuf, test.pver)
   571  		if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
   572  			t.Errorf("ReadVarString #%d wrong error got: %v, "+
   573  				"want: %v", i, err, reflect.TypeOf(test.err))
   574  			continue
   575  		}
   576  	}
   577  
   578  }
   579  
   580  // TestVarBytesWire tests wire encode and decode for variable length byte array.
   581  func TestVarBytesWire(t *testing.T) {
   582  	pver := wire.ProtocolVersion
   583  
   584  	// bytes256 is a byte array that takes a 2-byte varint to encode.
   585  	bytes256 := bytes.Repeat([]byte{0x01}, 256)
   586  
   587  	tests := []struct {
   588  		in   []byte // Byte Array to write
   589  		buf  []byte // Wire encoding
   590  		pver uint32 // Protocol version for wire encoding
   591  	}{
   592  		// Latest protocol version.
   593  		// Empty byte array
   594  		{[]byte{}, []byte{0x00}, pver},
   595  		// Single byte varint + byte array
   596  		{[]byte{0x01}, []byte{0x01, 0x01}, pver},
   597  		// 2-byte varint + byte array
   598  		{bytes256, append([]byte{0xfd, 0x00, 0x01}, bytes256...), pver},
   599  	}
   600  
   601  	t.Logf("Running %d tests", len(tests))
   602  	for i, test := range tests {
   603  		// Encode to wire format.
   604  		var buf bytes.Buffer
   605  		err := wire.TstWriteVarBytes(&buf, test.pver, test.in)
   606  		if err != nil {
   607  			t.Errorf("WriteVarBytes #%d error %v", i, err)
   608  			continue
   609  		}
   610  		if !bytes.Equal(buf.Bytes(), test.buf) {
   611  			t.Errorf("WriteVarBytes #%d\n got: %s want: %s", i,
   612  				spew.Sdump(buf.Bytes()), spew.Sdump(test.buf))
   613  			continue
   614  		}
   615  
   616  		// Decode from wire format.
   617  		rbuf := bytes.NewReader(test.buf)
   618  		val, err := wire.TstReadVarBytes(rbuf, test.pver,
   619  			wire.MaxMessagePayload, "test payload")
   620  		if err != nil {
   621  			t.Errorf("ReadVarBytes #%d error %v", i, err)
   622  			continue
   623  		}
   624  		if !bytes.Equal(buf.Bytes(), test.buf) {
   625  			t.Errorf("ReadVarBytes #%d\n got: %s want: %s", i,
   626  				val, test.buf)
   627  			continue
   628  		}
   629  	}
   630  }
   631  
   632  // TestVarBytesWireErrors performs negative tests against wire encode and
   633  // decode of variable length byte arrays to confirm error paths work correctly.
   634  func TestVarBytesWireErrors(t *testing.T) {
   635  	pver := wire.ProtocolVersion
   636  
   637  	// bytes256 is a byte array that takes a 2-byte varint to encode.
   638  	bytes256 := bytes.Repeat([]byte{0x01}, 256)
   639  
   640  	tests := []struct {
   641  		in       []byte // Byte Array to write
   642  		buf      []byte // Wire encoding
   643  		pver     uint32 // Protocol version for wire encoding
   644  		max      int    // Max size of fixed buffer to induce errors
   645  		writeErr error  // Expected write error
   646  		readErr  error  // Expected read error
   647  	}{
   648  		// Latest protocol version with intentional read/write errors.
   649  		// Force errors on empty byte array.
   650  		{[]byte{}, []byte{0x00}, pver, 0, io.ErrShortWrite, io.EOF},
   651  		// Force error on single byte varint + byte array.
   652  		{[]byte{0x01, 0x02, 0x03}, []byte{0x04}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
   653  		// Force errors on 2-byte varint + byte array.
   654  		{bytes256, []byte{0xfd}, pver, 2, io.ErrShortWrite, io.ErrUnexpectedEOF},
   655  	}
   656  
   657  	t.Logf("Running %d tests", len(tests))
   658  	for i, test := range tests {
   659  		// Encode to wire format.
   660  		w := newFixedWriter(test.max)
   661  		err := wire.TstWriteVarBytes(w, test.pver, test.in)
   662  		if err != test.writeErr {
   663  			t.Errorf("WriteVarBytes #%d wrong error got: %v, want: %v",
   664  				i, err, test.writeErr)
   665  			continue
   666  		}
   667  
   668  		// Decode from wire format.
   669  		r := newFixedReader(test.max, test.buf)
   670  		_, err = wire.TstReadVarBytes(r, test.pver,
   671  			wire.MaxMessagePayload, "test payload")
   672  		if err != test.readErr {
   673  			t.Errorf("ReadVarBytes #%d wrong error got: %v, want: %v",
   674  				i, err, test.readErr)
   675  			continue
   676  		}
   677  	}
   678  }
   679  
   680  // TestVarBytesOverflowErrors performs tests to ensure deserializing variable
   681  // length byte arrays intentionally crafted to use large values for the array
   682  // length are handled properly.  This could otherwise potentially be used as an
   683  // attack vector.
   684  func TestVarBytesOverflowErrors(t *testing.T) {
   685  	pver := wire.ProtocolVersion
   686  
   687  	tests := []struct {
   688  		buf  []byte // Wire encoding
   689  		pver uint32 // Protocol version for wire encoding
   690  		err  error  // Expected error
   691  	}{
   692  		{[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
   693  			pver, &wire.MessageError{}},
   694  		{[]byte{0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
   695  			pver, &wire.MessageError{}},
   696  	}
   697  
   698  	t.Logf("Running %d tests", len(tests))
   699  	for i, test := range tests {
   700  		// Decode from wire format.
   701  		rbuf := bytes.NewReader(test.buf)
   702  		_, err := wire.TstReadVarBytes(rbuf, test.pver,
   703  			wire.MaxMessagePayload, "test payload")
   704  		if reflect.TypeOf(err) != reflect.TypeOf(test.err) {
   705  			t.Errorf("ReadVarBytes #%d wrong error got: %v, "+
   706  				"want: %v", i, err, reflect.TypeOf(test.err))
   707  			continue
   708  		}
   709  	}
   710  
   711  }
   712  
   713  // TestRandomUint64 exercises the randomness of the random number generator on
   714  // the system by ensuring the probability of the generated numbers.  If the RNG
   715  // is evenly distributed as a proper cryptographic RNG should be, there really
   716  // should only be 1 number < 2^56 in 2^8 tries for a 64-bit number.  However,
   717  // use a higher number of 5 to really ensure the test doesn't fail unless the
   718  // RNG is just horrendous.
   719  func TestRandomUint64(t *testing.T) {
   720  	tries := 1 << 8              // 2^8
   721  	watermark := uint64(1 << 56) // 2^56
   722  	maxHits := 5
   723  	badRNG := "The random number generator on this system is clearly " +
   724  		"terrible since we got %d values less than %d in %d runs " +
   725  		"when only %d was expected"
   726  
   727  	numHits := 0
   728  	for i := 0; i < tries; i++ {
   729  		nonce, err := wire.RandomUint64()
   730  		if err != nil {
   731  			t.Errorf("RandomUint64 iteration %d failed - err %v",
   732  				i, err)
   733  			return
   734  		}
   735  		if nonce < watermark {
   736  			numHits++
   737  		}
   738  		if numHits > maxHits {
   739  			str := fmt.Sprintf(badRNG, numHits, watermark, tries, maxHits)
   740  			t.Errorf("Random Uint64 iteration %d failed - %v %v", i,
   741  				str, numHits)
   742  			return
   743  		}
   744  	}
   745  }
   746  
   747  // TestRandomUint64Errors uses a fake reader to force error paths to be executed
   748  // and checks the results accordingly.
   749  func TestRandomUint64Errors(t *testing.T) {
   750  	// Test short reads.
   751  	fr := &fakeRandReader{n: 2, err: io.EOF}
   752  	nonce, err := wire.TstRandomUint64(fr)
   753  	if err != io.ErrUnexpectedEOF {
   754  		t.Errorf("Error not expected value of %v [%v]",
   755  			io.ErrUnexpectedEOF, err)
   756  	}
   757  	if nonce != 0 {
   758  		t.Errorf("Nonce is not 0 [%v]", nonce)
   759  	}
   760  }