msgaddrv2_test.go raw

   1  package wire
   2  
   3  import (
   4  	"bytes"
   5  	"io"
   6  	"testing"
   7  )
   8  
   9  // TestAddrV2Decode checks that decoding an addrv2 message off the wire behaves
  10  // as expected. This means ignoring certain addresses, and failing in certain
  11  // failure scenarios.
  12  func TestAddrV2Decode(t *testing.T) {
  13  	tests := []struct {
  14  		buf           []byte
  15  		expectedError bool
  16  		expectedAddrs int
  17  	}{
  18  		// Exceeding max addresses.
  19  		{
  20  			[]byte{0xfd, 0xff, 0xff},
  21  			true,
  22  			0,
  23  		},
  24  
  25  		// Invalid address size.
  26  		{
  27  			[]byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x05},
  28  			true,
  29  			0,
  30  		},
  31  
  32  		// One valid address and one skipped address
  33  		{
  34  			[]byte{
  35  				0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04,
  36  				0x7f, 0x00, 0x00, 0x01, 0x22, 0x22, 0x00, 0x00,
  37  				0x00, 0x00, 0x00, 0x02, 0x10, 0xfd, 0x87, 0xd8,
  38  				0x7e, 0xeb, 0x43, 0xff, 0xfe, 0xcc, 0x39, 0xa8,
  39  				0x73, 0x69, 0x15, 0xff, 0xff, 0x22, 0x22,
  40  			},
  41  			false,
  42  			1,
  43  		},
  44  		// Truncated address.
  45  		{
  46  			[]byte{
  47  				0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04,
  48  				0x7f, 0x00, 0x00,
  49  			},
  50  			true,
  51  			0,
  52  		},
  53  	}
  54  
  55  	t.Logf("Running %d tests", len(tests))
  56  	for i, test := range tests {
  57  		r := bytes.NewReader(test.buf)
  58  		m := &MsgAddrV2{}
  59  
  60  		err := m.BtcDecode(r, 0, LatestEncoding)
  61  		if test.expectedError {
  62  			if err == nil {
  63  				t.Errorf("Test #%d expected error", i)
  64  			}
  65  
  66  			continue
  67  		} else if err != nil {
  68  			t.Errorf("Test #%d unexpected error %v", i, err)
  69  		}
  70  
  71  		// Trying to read more should give EOF.
  72  		var b [1]byte
  73  		if _, err := r.Read(b[:]); err != io.EOF {
  74  			t.Errorf("Test #%d did not cleanly finish reading", i)
  75  		}
  76  
  77  		if len(m.AddrList) != test.expectedAddrs {
  78  			t.Errorf("Test #%d expected %d addrs, instead of %d",
  79  				i, test.expectedAddrs, len(m.AddrList))
  80  		}
  81  	}
  82  }
  83