github.com/lbryio/lbcd@v0.22.119/wire/common_test.go (about)

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