github.com/phillinzzz/newBsc@v1.1.6/rlp/decode_test.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rlp
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/hex"
    22  	"errors"
    23  	"fmt"
    24  	"io"
    25  	"math/big"
    26  	"reflect"
    27  	"strings"
    28  	"testing"
    29  
    30  	"github.com/phillinzzz/newBsc/common/math"
    31  )
    32  
    33  func TestStreamKind(t *testing.T) {
    34  	tests := []struct {
    35  		input    string
    36  		wantKind Kind
    37  		wantLen  uint64
    38  	}{
    39  		{"00", Byte, 0},
    40  		{"01", Byte, 0},
    41  		{"7F", Byte, 0},
    42  		{"80", String, 0},
    43  		{"B7", String, 55},
    44  		{"B90400", String, 1024},
    45  		{"BFFFFFFFFFFFFFFFFF", String, ^uint64(0)},
    46  		{"C0", List, 0},
    47  		{"C8", List, 8},
    48  		{"F7", List, 55},
    49  		{"F90400", List, 1024},
    50  		{"FFFFFFFFFFFFFFFFFF", List, ^uint64(0)},
    51  	}
    52  
    53  	for i, test := range tests {
    54  		// using plainReader to inhibit input limit errors.
    55  		s := NewStream(newPlainReader(unhex(test.input)), 0)
    56  		kind, len, err := s.Kind()
    57  		if err != nil {
    58  			t.Errorf("test %d: Kind returned error: %v", i, err)
    59  			continue
    60  		}
    61  		if kind != test.wantKind {
    62  			t.Errorf("test %d: kind mismatch: got %d, want %d", i, kind, test.wantKind)
    63  		}
    64  		if len != test.wantLen {
    65  			t.Errorf("test %d: len mismatch: got %d, want %d", i, len, test.wantLen)
    66  		}
    67  	}
    68  }
    69  
    70  func TestNewListStream(t *testing.T) {
    71  	ls := NewListStream(bytes.NewReader(unhex("0101010101")), 3)
    72  	if k, size, err := ls.Kind(); k != List || size != 3 || err != nil {
    73  		t.Errorf("Kind() returned (%v, %d, %v), expected (List, 3, nil)", k, size, err)
    74  	}
    75  	if size, err := ls.List(); size != 3 || err != nil {
    76  		t.Errorf("List() returned (%d, %v), expected (3, nil)", size, err)
    77  	}
    78  	for i := 0; i < 3; i++ {
    79  		if val, err := ls.Uint(); val != 1 || err != nil {
    80  			t.Errorf("Uint() returned (%d, %v), expected (1, nil)", val, err)
    81  		}
    82  	}
    83  	if err := ls.ListEnd(); err != nil {
    84  		t.Errorf("ListEnd() returned %v, expected (3, nil)", err)
    85  	}
    86  }
    87  
    88  func TestStreamErrors(t *testing.T) {
    89  	withoutInputLimit := func(b []byte) *Stream {
    90  		return NewStream(newPlainReader(b), 0)
    91  	}
    92  	withCustomInputLimit := func(limit uint64) func([]byte) *Stream {
    93  		return func(b []byte) *Stream {
    94  			return NewStream(bytes.NewReader(b), limit)
    95  		}
    96  	}
    97  
    98  	type calls []string
    99  	tests := []struct {
   100  		string
   101  		calls
   102  		newStream func([]byte) *Stream // uses bytes.Reader if nil
   103  		error     error
   104  	}{
   105  		{"C0", calls{"Bytes"}, nil, ErrExpectedString},
   106  		{"C0", calls{"Uint"}, nil, ErrExpectedString},
   107  		{"89000000000000000001", calls{"Uint"}, nil, errUintOverflow},
   108  		{"00", calls{"List"}, nil, ErrExpectedList},
   109  		{"80", calls{"List"}, nil, ErrExpectedList},
   110  		{"C0", calls{"List", "Uint"}, nil, EOL},
   111  		{"C8C9010101010101010101", calls{"List", "Kind"}, nil, ErrElemTooLarge},
   112  		{"C3C2010201", calls{"List", "List", "Uint", "Uint", "ListEnd", "Uint"}, nil, EOL},
   113  		{"00", calls{"ListEnd"}, nil, errNotInList},
   114  		{"C401020304", calls{"List", "Uint", "ListEnd"}, nil, errNotAtEOL},
   115  
   116  		// Non-canonical integers (e.g. leading zero bytes).
   117  		{"00", calls{"Uint"}, nil, ErrCanonInt},
   118  		{"820002", calls{"Uint"}, nil, ErrCanonInt},
   119  		{"8133", calls{"Uint"}, nil, ErrCanonSize},
   120  		{"817F", calls{"Uint"}, nil, ErrCanonSize},
   121  		{"8180", calls{"Uint"}, nil, nil},
   122  
   123  		// Non-valid boolean
   124  		{"02", calls{"Bool"}, nil, errors.New("rlp: invalid boolean value: 2")},
   125  
   126  		// Size tags must use the smallest possible encoding.
   127  		// Leading zero bytes in the size tag are also rejected.
   128  		{"8100", calls{"Uint"}, nil, ErrCanonSize},
   129  		{"8100", calls{"Bytes"}, nil, ErrCanonSize},
   130  		{"8101", calls{"Bytes"}, nil, ErrCanonSize},
   131  		{"817F", calls{"Bytes"}, nil, ErrCanonSize},
   132  		{"8180", calls{"Bytes"}, nil, nil},
   133  		{"B800", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
   134  		{"B90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
   135  		{"B90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
   136  		{"BA0002FFFF", calls{"Bytes"}, withoutInputLimit, ErrCanonSize},
   137  		{"F800", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
   138  		{"F90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
   139  		{"F90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
   140  		{"FA0002FFFF", calls{"List"}, withoutInputLimit, ErrCanonSize},
   141  
   142  		// Expected EOF
   143  		{"", calls{"Kind"}, nil, io.EOF},
   144  		{"", calls{"Uint"}, nil, io.EOF},
   145  		{"", calls{"List"}, nil, io.EOF},
   146  		{"8180", calls{"Uint", "Uint"}, nil, io.EOF},
   147  		{"C0", calls{"List", "ListEnd", "List"}, nil, io.EOF},
   148  
   149  		{"", calls{"List"}, withoutInputLimit, io.EOF},
   150  		{"8180", calls{"Uint", "Uint"}, withoutInputLimit, io.EOF},
   151  		{"C0", calls{"List", "ListEnd", "List"}, withoutInputLimit, io.EOF},
   152  
   153  		// Input limit errors.
   154  		{"81", calls{"Bytes"}, nil, ErrValueTooLarge},
   155  		{"81", calls{"Uint"}, nil, ErrValueTooLarge},
   156  		{"81", calls{"Raw"}, nil, ErrValueTooLarge},
   157  		{"BFFFFFFFFFFFFFFFFFFF", calls{"Bytes"}, nil, ErrValueTooLarge},
   158  		{"C801", calls{"List"}, nil, ErrValueTooLarge},
   159  
   160  		// Test for list element size check overflow.
   161  		{"CD04040404FFFFFFFFFFFFFFFFFF0303", calls{"List", "Uint", "Uint", "Uint", "Uint", "List"}, nil, ErrElemTooLarge},
   162  
   163  		// Test for input limit overflow. Since we are counting the limit
   164  		// down toward zero in Stream.remaining, reading too far can overflow
   165  		// remaining to a large value, effectively disabling the limit.
   166  		{"C40102030401", calls{"Raw", "Uint"}, withCustomInputLimit(5), io.EOF},
   167  		{"C4010203048180", calls{"Raw", "Uint"}, withCustomInputLimit(6), ErrValueTooLarge},
   168  
   169  		// Check that the same calls are fine without a limit.
   170  		{"C40102030401", calls{"Raw", "Uint"}, withoutInputLimit, nil},
   171  		{"C4010203048180", calls{"Raw", "Uint"}, withoutInputLimit, nil},
   172  
   173  		// Unexpected EOF. This only happens when there is
   174  		// no input limit, so the reader needs to be 'dumbed down'.
   175  		{"81", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF},
   176  		{"81", calls{"Uint"}, withoutInputLimit, io.ErrUnexpectedEOF},
   177  		{"BFFFFFFFFFFFFFFF", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF},
   178  		{"C801", calls{"List", "Uint", "Uint"}, withoutInputLimit, io.ErrUnexpectedEOF},
   179  
   180  		// This test verifies that the input position is advanced
   181  		// correctly when calling Bytes for empty strings. Kind can be called
   182  		// any number of times in between and doesn't advance.
   183  		{"C3808080", calls{
   184  			"List",  // enter the list
   185  			"Bytes", // past first element
   186  
   187  			"Kind", "Kind", "Kind", // this shouldn't advance
   188  
   189  			"Bytes", // past second element
   190  
   191  			"Kind", "Kind", // can't hurt to try
   192  
   193  			"Bytes", // past final element
   194  			"Bytes", // this one should fail
   195  		}, nil, EOL},
   196  	}
   197  
   198  testfor:
   199  	for i, test := range tests {
   200  		if test.newStream == nil {
   201  			test.newStream = func(b []byte) *Stream { return NewStream(bytes.NewReader(b), 0) }
   202  		}
   203  		s := test.newStream(unhex(test.string))
   204  		rs := reflect.ValueOf(s)
   205  		for j, call := range test.calls {
   206  			fval := rs.MethodByName(call)
   207  			ret := fval.Call(nil)
   208  			err := "<nil>"
   209  			if lastret := ret[len(ret)-1].Interface(); lastret != nil {
   210  				err = lastret.(error).Error()
   211  			}
   212  			if j == len(test.calls)-1 {
   213  				want := "<nil>"
   214  				if test.error != nil {
   215  					want = test.error.Error()
   216  				}
   217  				if err != want {
   218  					t.Log(test)
   219  					t.Errorf("test %d: last call (%s) error mismatch\ngot:  %s\nwant: %s",
   220  						i, call, err, test.error)
   221  				}
   222  			} else if err != "<nil>" {
   223  				t.Log(test)
   224  				t.Errorf("test %d: call %d (%s) unexpected error: %q", i, j, call, err)
   225  				continue testfor
   226  			}
   227  		}
   228  	}
   229  }
   230  
   231  func TestStreamList(t *testing.T) {
   232  	s := NewStream(bytes.NewReader(unhex("C80102030405060708")), 0)
   233  
   234  	len, err := s.List()
   235  	if err != nil {
   236  		t.Fatalf("List error: %v", err)
   237  	}
   238  	if len != 8 {
   239  		t.Fatalf("List returned invalid length, got %d, want 8", len)
   240  	}
   241  
   242  	for i := uint64(1); i <= 8; i++ {
   243  		v, err := s.Uint()
   244  		if err != nil {
   245  			t.Fatalf("Uint error: %v", err)
   246  		}
   247  		if i != v {
   248  			t.Errorf("Uint returned wrong value, got %d, want %d", v, i)
   249  		}
   250  	}
   251  
   252  	if _, err := s.Uint(); err != EOL {
   253  		t.Errorf("Uint error mismatch, got %v, want %v", err, EOL)
   254  	}
   255  	if err = s.ListEnd(); err != nil {
   256  		t.Fatalf("ListEnd error: %v", err)
   257  	}
   258  }
   259  
   260  func TestStreamRaw(t *testing.T) {
   261  	tests := []struct {
   262  		input  string
   263  		output string
   264  	}{
   265  		{
   266  			"C58401010101",
   267  			"8401010101",
   268  		},
   269  		{
   270  			"F842B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
   271  			"B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
   272  		},
   273  	}
   274  	for i, tt := range tests {
   275  		s := NewStream(bytes.NewReader(unhex(tt.input)), 0)
   276  		s.List()
   277  
   278  		want := unhex(tt.output)
   279  		raw, err := s.Raw()
   280  		if err != nil {
   281  			t.Fatal(err)
   282  		}
   283  		if !bytes.Equal(want, raw) {
   284  			t.Errorf("test %d: raw mismatch: got %x, want %x", i, raw, want)
   285  		}
   286  	}
   287  }
   288  
   289  func TestDecodeErrors(t *testing.T) {
   290  	r := bytes.NewReader(nil)
   291  
   292  	if err := Decode(r, nil); err != errDecodeIntoNil {
   293  		t.Errorf("Decode(r, nil) error mismatch, got %q, want %q", err, errDecodeIntoNil)
   294  	}
   295  
   296  	var nilptr *struct{}
   297  	if err := Decode(r, nilptr); err != errDecodeIntoNil {
   298  		t.Errorf("Decode(r, nilptr) error mismatch, got %q, want %q", err, errDecodeIntoNil)
   299  	}
   300  
   301  	if err := Decode(r, struct{}{}); err != errNoPointer {
   302  		t.Errorf("Decode(r, struct{}{}) error mismatch, got %q, want %q", err, errNoPointer)
   303  	}
   304  
   305  	expectErr := "rlp: type chan bool is not RLP-serializable"
   306  	if err := Decode(r, new(chan bool)); err == nil || err.Error() != expectErr {
   307  		t.Errorf("Decode(r, new(chan bool)) error mismatch, got %q, want %q", err, expectErr)
   308  	}
   309  
   310  	if err := Decode(r, new(uint)); err != io.EOF {
   311  		t.Errorf("Decode(r, new(int)) error mismatch, got %q, want %q", err, io.EOF)
   312  	}
   313  }
   314  
   315  type decodeTest struct {
   316  	input string
   317  	ptr   interface{}
   318  	value interface{}
   319  	error string
   320  }
   321  
   322  type simplestruct struct {
   323  	A uint
   324  	B string
   325  }
   326  
   327  type recstruct struct {
   328  	I     uint
   329  	Child *recstruct `rlp:"nil"`
   330  }
   331  
   332  type bigIntStruct struct {
   333  	I *big.Int
   334  	B string
   335  }
   336  
   337  type invalidNilTag struct {
   338  	X []byte `rlp:"nil"`
   339  }
   340  
   341  type invalidTail1 struct {
   342  	A uint `rlp:"tail"`
   343  	B string
   344  }
   345  
   346  type invalidTail2 struct {
   347  	A uint
   348  	B string `rlp:"tail"`
   349  }
   350  
   351  type tailRaw struct {
   352  	A    uint
   353  	Tail []RawValue `rlp:"tail"`
   354  }
   355  
   356  type tailUint struct {
   357  	A    uint
   358  	Tail []uint `rlp:"tail"`
   359  }
   360  
   361  type tailPrivateFields struct {
   362  	A    uint
   363  	Tail []uint `rlp:"tail"`
   364  	x, y bool   //lint:ignore U1000 unused fields required for testing purposes.
   365  }
   366  
   367  type nilListUint struct {
   368  	X *uint `rlp:"nilList"`
   369  }
   370  
   371  type nilStringSlice struct {
   372  	X *[]uint `rlp:"nilString"`
   373  }
   374  
   375  type intField struct {
   376  	X int
   377  }
   378  
   379  var (
   380  	veryBigInt = new(big.Int).Add(
   381  		big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16),
   382  		big.NewInt(0xFFFF),
   383  	)
   384  	veryVeryBigInt = new(big.Int).Exp(veryBigInt, big.NewInt(8), nil)
   385  )
   386  
   387  type hasIgnoredField struct {
   388  	A uint
   389  	B uint `rlp:"-"`
   390  	C uint
   391  }
   392  
   393  var decodeTests = []decodeTest{
   394  	// booleans
   395  	{input: "01", ptr: new(bool), value: true},
   396  	{input: "80", ptr: new(bool), value: false},
   397  	{input: "02", ptr: new(bool), error: "rlp: invalid boolean value: 2"},
   398  
   399  	// integers
   400  	{input: "05", ptr: new(uint32), value: uint32(5)},
   401  	{input: "80", ptr: new(uint32), value: uint32(0)},
   402  	{input: "820505", ptr: new(uint32), value: uint32(0x0505)},
   403  	{input: "83050505", ptr: new(uint32), value: uint32(0x050505)},
   404  	{input: "8405050505", ptr: new(uint32), value: uint32(0x05050505)},
   405  	{input: "850505050505", ptr: new(uint32), error: "rlp: input string too long for uint32"},
   406  	{input: "C0", ptr: new(uint32), error: "rlp: expected input string or byte for uint32"},
   407  	{input: "00", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"},
   408  	{input: "8105", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"},
   409  	{input: "820004", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"},
   410  	{input: "B8020004", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"},
   411  
   412  	// slices
   413  	{input: "C0", ptr: new([]uint), value: []uint{}},
   414  	{input: "C80102030405060708", ptr: new([]uint), value: []uint{1, 2, 3, 4, 5, 6, 7, 8}},
   415  	{input: "F8020004", ptr: new([]uint), error: "rlp: non-canonical size information for []uint"},
   416  
   417  	// arrays
   418  	{input: "C50102030405", ptr: new([5]uint), value: [5]uint{1, 2, 3, 4, 5}},
   419  	{input: "C0", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"},
   420  	{input: "C102", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"},
   421  	{input: "C6010203040506", ptr: new([5]uint), error: "rlp: input list has too many elements for [5]uint"},
   422  	{input: "F8020004", ptr: new([5]uint), error: "rlp: non-canonical size information for [5]uint"},
   423  
   424  	// zero sized arrays
   425  	{input: "C0", ptr: new([0]uint), value: [0]uint{}},
   426  	{input: "C101", ptr: new([0]uint), error: "rlp: input list has too many elements for [0]uint"},
   427  
   428  	// byte slices
   429  	{input: "01", ptr: new([]byte), value: []byte{1}},
   430  	{input: "80", ptr: new([]byte), value: []byte{}},
   431  	{input: "8D6162636465666768696A6B6C6D", ptr: new([]byte), value: []byte("abcdefghijklm")},
   432  	{input: "C0", ptr: new([]byte), error: "rlp: expected input string or byte for []uint8"},
   433  	{input: "8105", ptr: new([]byte), error: "rlp: non-canonical size information for []uint8"},
   434  
   435  	// byte arrays
   436  	{input: "02", ptr: new([1]byte), value: [1]byte{2}},
   437  	{input: "8180", ptr: new([1]byte), value: [1]byte{128}},
   438  	{input: "850102030405", ptr: new([5]byte), value: [5]byte{1, 2, 3, 4, 5}},
   439  
   440  	// byte array errors
   441  	{input: "02", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"},
   442  	{input: "80", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"},
   443  	{input: "820000", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"},
   444  	{input: "C0", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"},
   445  	{input: "C3010203", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"},
   446  	{input: "86010203040506", ptr: new([5]byte), error: "rlp: input string too long for [5]uint8"},
   447  	{input: "8105", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"},
   448  	{input: "817F", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"},
   449  
   450  	// zero sized byte arrays
   451  	{input: "80", ptr: new([0]byte), value: [0]byte{}},
   452  	{input: "01", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"},
   453  	{input: "8101", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"},
   454  
   455  	// strings
   456  	{input: "00", ptr: new(string), value: "\000"},
   457  	{input: "8D6162636465666768696A6B6C6D", ptr: new(string), value: "abcdefghijklm"},
   458  	{input: "C0", ptr: new(string), error: "rlp: expected input string or byte for string"},
   459  
   460  	// big ints
   461  	{input: "80", ptr: new(*big.Int), value: big.NewInt(0)},
   462  	{input: "01", ptr: new(*big.Int), value: big.NewInt(1)},
   463  	{input: "89FFFFFFFFFFFFFFFFFF", ptr: new(*big.Int), value: veryBigInt},
   464  	{input: "B848FFFFFFFFFFFFFFFFF800000000000000001BFFFFFFFFFFFFFFFFC8000000000000000045FFFFFFFFFFFFFFFFC800000000000000001BFFFFFFFFFFFFFFFFF8000000000000000001", ptr: new(*big.Int), value: veryVeryBigInt},
   465  	{input: "10", ptr: new(big.Int), value: *big.NewInt(16)}, // non-pointer also works
   466  	{input: "C0", ptr: new(*big.Int), error: "rlp: expected input string or byte for *big.Int"},
   467  	{input: "00", ptr: new(*big.Int), error: "rlp: non-canonical integer (leading zero bytes) for *big.Int"},
   468  	{input: "820001", ptr: new(*big.Int), error: "rlp: non-canonical integer (leading zero bytes) for *big.Int"},
   469  	{input: "8105", ptr: new(*big.Int), error: "rlp: non-canonical size information for *big.Int"},
   470  
   471  	// structs
   472  	{
   473  		input: "C50583343434",
   474  		ptr:   new(simplestruct),
   475  		value: simplestruct{5, "444"},
   476  	},
   477  	{
   478  		input: "C601C402C203C0",
   479  		ptr:   new(recstruct),
   480  		value: recstruct{1, &recstruct{2, &recstruct{3, nil}}},
   481  	},
   482  	{
   483  		// This checks that empty big.Int works correctly in struct context. It's easy to
   484  		// miss the update of s.kind for this case, so it needs its own test.
   485  		input: "C58083343434",
   486  		ptr:   new(bigIntStruct),
   487  		value: bigIntStruct{new(big.Int), "444"},
   488  	},
   489  
   490  	// struct errors
   491  	{
   492  		input: "C0",
   493  		ptr:   new(simplestruct),
   494  		error: "rlp: too few elements for rlp.simplestruct",
   495  	},
   496  	{
   497  		input: "C105",
   498  		ptr:   new(simplestruct),
   499  		error: "rlp: too few elements for rlp.simplestruct",
   500  	},
   501  	{
   502  		input: "C7C50583343434C0",
   503  		ptr:   new([]*simplestruct),
   504  		error: "rlp: too few elements for rlp.simplestruct, decoding into ([]*rlp.simplestruct)[1]",
   505  	},
   506  	{
   507  		input: "83222222",
   508  		ptr:   new(simplestruct),
   509  		error: "rlp: expected input list for rlp.simplestruct",
   510  	},
   511  	{
   512  		input: "C3010101",
   513  		ptr:   new(simplestruct),
   514  		error: "rlp: input list has too many elements for rlp.simplestruct",
   515  	},
   516  	{
   517  		input: "C501C3C00000",
   518  		ptr:   new(recstruct),
   519  		error: "rlp: expected input string or byte for uint, decoding into (rlp.recstruct).Child.I",
   520  	},
   521  	{
   522  		input: "C103",
   523  		ptr:   new(intField),
   524  		error: "rlp: type int is not RLP-serializable (struct field rlp.intField.X)",
   525  	},
   526  	{
   527  		input: "C50102C20102",
   528  		ptr:   new(tailUint),
   529  		error: "rlp: expected input string or byte for uint, decoding into (rlp.tailUint).Tail[1]",
   530  	},
   531  	{
   532  		input: "C0",
   533  		ptr:   new(invalidNilTag),
   534  		error: `rlp: invalid struct tag "nil" for rlp.invalidNilTag.X (field is not a pointer)`,
   535  	},
   536  
   537  	// struct tag "tail"
   538  	{
   539  		input: "C3010203",
   540  		ptr:   new(tailRaw),
   541  		value: tailRaw{A: 1, Tail: []RawValue{unhex("02"), unhex("03")}},
   542  	},
   543  	{
   544  		input: "C20102",
   545  		ptr:   new(tailRaw),
   546  		value: tailRaw{A: 1, Tail: []RawValue{unhex("02")}},
   547  	},
   548  	{
   549  		input: "C101",
   550  		ptr:   new(tailRaw),
   551  		value: tailRaw{A: 1, Tail: []RawValue{}},
   552  	},
   553  	{
   554  		input: "C3010203",
   555  		ptr:   new(tailPrivateFields),
   556  		value: tailPrivateFields{A: 1, Tail: []uint{2, 3}},
   557  	},
   558  	{
   559  		input: "C0",
   560  		ptr:   new(invalidTail1),
   561  		error: `rlp: invalid struct tag "tail" for rlp.invalidTail1.A (must be on last field)`,
   562  	},
   563  	{
   564  		input: "C0",
   565  		ptr:   new(invalidTail2),
   566  		error: `rlp: invalid struct tag "tail" for rlp.invalidTail2.B (field type is not slice)`,
   567  	},
   568  
   569  	// struct tag "-"
   570  	{
   571  		input: "C20102",
   572  		ptr:   new(hasIgnoredField),
   573  		value: hasIgnoredField{A: 1, C: 2},
   574  	},
   575  
   576  	// struct tag "nilList"
   577  	{
   578  		input: "C180",
   579  		ptr:   new(nilListUint),
   580  		error: "rlp: wrong kind of empty value (got String, want List) for *uint, decoding into (rlp.nilListUint).X",
   581  	},
   582  	{
   583  		input: "C1C0",
   584  		ptr:   new(nilListUint),
   585  		value: nilListUint{},
   586  	},
   587  	{
   588  		input: "C103",
   589  		ptr:   new(nilListUint),
   590  		value: func() interface{} {
   591  			v := uint(3)
   592  			return nilListUint{X: &v}
   593  		}(),
   594  	},
   595  
   596  	// struct tag "nilString"
   597  	{
   598  		input: "C1C0",
   599  		ptr:   new(nilStringSlice),
   600  		error: "rlp: wrong kind of empty value (got List, want String) for *[]uint, decoding into (rlp.nilStringSlice).X",
   601  	},
   602  	{
   603  		input: "C180",
   604  		ptr:   new(nilStringSlice),
   605  		value: nilStringSlice{},
   606  	},
   607  	{
   608  		input: "C2C103",
   609  		ptr:   new(nilStringSlice),
   610  		value: nilStringSlice{X: &[]uint{3}},
   611  	},
   612  
   613  	// RawValue
   614  	{input: "01", ptr: new(RawValue), value: RawValue(unhex("01"))},
   615  	{input: "82FFFF", ptr: new(RawValue), value: RawValue(unhex("82FFFF"))},
   616  	{input: "C20102", ptr: new([]RawValue), value: []RawValue{unhex("01"), unhex("02")}},
   617  
   618  	// pointers
   619  	{input: "00", ptr: new(*[]byte), value: &[]byte{0}},
   620  	{input: "80", ptr: new(*uint), value: uintp(0)},
   621  	{input: "C0", ptr: new(*uint), error: "rlp: expected input string or byte for uint"},
   622  	{input: "07", ptr: new(*uint), value: uintp(7)},
   623  	{input: "817F", ptr: new(*uint), error: "rlp: non-canonical size information for uint"},
   624  	{input: "8180", ptr: new(*uint), value: uintp(0x80)},
   625  	{input: "C109", ptr: new(*[]uint), value: &[]uint{9}},
   626  	{input: "C58403030303", ptr: new(*[][]byte), value: &[][]byte{{3, 3, 3, 3}}},
   627  
   628  	// check that input position is advanced also for empty values.
   629  	{input: "C3808005", ptr: new([]*uint), value: []*uint{uintp(0), uintp(0), uintp(5)}},
   630  
   631  	// interface{}
   632  	{input: "00", ptr: new(interface{}), value: []byte{0}},
   633  	{input: "01", ptr: new(interface{}), value: []byte{1}},
   634  	{input: "80", ptr: new(interface{}), value: []byte{}},
   635  	{input: "850505050505", ptr: new(interface{}), value: []byte{5, 5, 5, 5, 5}},
   636  	{input: "C0", ptr: new(interface{}), value: []interface{}{}},
   637  	{input: "C50183040404", ptr: new(interface{}), value: []interface{}{[]byte{1}, []byte{4, 4, 4}}},
   638  	{
   639  		input: "C3010203",
   640  		ptr:   new([]io.Reader),
   641  		error: "rlp: type io.Reader is not RLP-serializable",
   642  	},
   643  
   644  	// fuzzer crashes
   645  	{
   646  		input: "c330f9c030f93030ce3030303030303030bd303030303030",
   647  		ptr:   new(interface{}),
   648  		error: "rlp: element is larger than containing list",
   649  	},
   650  }
   651  
   652  func uintp(i uint) *uint { return &i }
   653  
   654  func runTests(t *testing.T, decode func([]byte, interface{}) error) {
   655  	for i, test := range decodeTests {
   656  		input, err := hex.DecodeString(test.input)
   657  		if err != nil {
   658  			t.Errorf("test %d: invalid hex input %q", i, test.input)
   659  			continue
   660  		}
   661  		err = decode(input, test.ptr)
   662  		if err != nil && test.error == "" {
   663  			t.Errorf("test %d: unexpected Decode error: %v\ndecoding into %T\ninput %q",
   664  				i, err, test.ptr, test.input)
   665  			continue
   666  		}
   667  		if test.error != "" && fmt.Sprint(err) != test.error {
   668  			t.Errorf("test %d: Decode error mismatch\ngot  %v\nwant %v\ndecoding into %T\ninput %q",
   669  				i, err, test.error, test.ptr, test.input)
   670  			continue
   671  		}
   672  		deref := reflect.ValueOf(test.ptr).Elem().Interface()
   673  		if err == nil && !reflect.DeepEqual(deref, test.value) {
   674  			t.Errorf("test %d: value mismatch\ngot  %#v\nwant %#v\ndecoding into %T\ninput %q",
   675  				i, deref, test.value, test.ptr, test.input)
   676  		}
   677  	}
   678  }
   679  
   680  func TestDecodeWithByteReader(t *testing.T) {
   681  	runTests(t, func(input []byte, into interface{}) error {
   682  		return Decode(bytes.NewReader(input), into)
   683  	})
   684  }
   685  
   686  func testDecodeWithEncReader(t *testing.T, n int) {
   687  	s := strings.Repeat("0", n)
   688  	_, r, _ := EncodeToReader(s)
   689  	var decoded string
   690  	err := Decode(r, &decoded)
   691  	if err != nil {
   692  		t.Errorf("Unexpected decode error with n=%v: %v", n, err)
   693  	}
   694  	if decoded != s {
   695  		t.Errorf("Decode mismatch with n=%v", n)
   696  	}
   697  }
   698  
   699  // This is a regression test checking that decoding from encReader
   700  // works for RLP values of size 8192 bytes or more.
   701  func TestDecodeWithEncReader(t *testing.T) {
   702  	testDecodeWithEncReader(t, 8188) // length with header is 8191
   703  	testDecodeWithEncReader(t, 8189) // length with header is 8192
   704  }
   705  
   706  // plainReader reads from a byte slice but does not
   707  // implement ReadByte. It is also not recognized by the
   708  // size validation. This is useful to test how the decoder
   709  // behaves on a non-buffered input stream.
   710  type plainReader []byte
   711  
   712  func newPlainReader(b []byte) io.Reader {
   713  	return (*plainReader)(&b)
   714  }
   715  
   716  func (r *plainReader) Read(buf []byte) (n int, err error) {
   717  	if len(*r) == 0 {
   718  		return 0, io.EOF
   719  	}
   720  	n = copy(buf, *r)
   721  	*r = (*r)[n:]
   722  	return n, nil
   723  }
   724  
   725  func TestDecodeWithNonByteReader(t *testing.T) {
   726  	runTests(t, func(input []byte, into interface{}) error {
   727  		return Decode(newPlainReader(input), into)
   728  	})
   729  }
   730  
   731  func TestDecodeStreamReset(t *testing.T) {
   732  	s := NewStream(nil, 0)
   733  	runTests(t, func(input []byte, into interface{}) error {
   734  		s.Reset(bytes.NewReader(input), 0)
   735  		return s.Decode(into)
   736  	})
   737  }
   738  
   739  type testDecoder struct{ called bool }
   740  
   741  func (t *testDecoder) DecodeRLP(s *Stream) error {
   742  	if _, err := s.Uint(); err != nil {
   743  		return err
   744  	}
   745  	t.called = true
   746  	return nil
   747  }
   748  
   749  func TestDecodeDecoder(t *testing.T) {
   750  	var s struct {
   751  		T1 testDecoder
   752  		T2 *testDecoder
   753  		T3 **testDecoder
   754  	}
   755  	if err := Decode(bytes.NewReader(unhex("C3010203")), &s); err != nil {
   756  		t.Fatalf("Decode error: %v", err)
   757  	}
   758  
   759  	if !s.T1.called {
   760  		t.Errorf("DecodeRLP was not called for (non-pointer) testDecoder")
   761  	}
   762  
   763  	if s.T2 == nil {
   764  		t.Errorf("*testDecoder has not been allocated")
   765  	} else if !s.T2.called {
   766  		t.Errorf("DecodeRLP was not called for *testDecoder")
   767  	}
   768  
   769  	if s.T3 == nil || *s.T3 == nil {
   770  		t.Errorf("**testDecoder has not been allocated")
   771  	} else if !(*s.T3).called {
   772  		t.Errorf("DecodeRLP was not called for **testDecoder")
   773  	}
   774  }
   775  
   776  func TestDecodeDecoderNilPointer(t *testing.T) {
   777  	var s struct {
   778  		T1 *testDecoder `rlp:"nil"`
   779  		T2 *testDecoder
   780  	}
   781  	if err := Decode(bytes.NewReader(unhex("C2C002")), &s); err != nil {
   782  		t.Fatalf("Decode error: %v", err)
   783  	}
   784  	if s.T1 != nil {
   785  		t.Errorf("decoder T1 allocated for empty input (called: %v)", s.T1.called)
   786  	}
   787  	if s.T2 == nil || !s.T2.called {
   788  		t.Errorf("decoder T2 not allocated/called")
   789  	}
   790  }
   791  
   792  type byteDecoder byte
   793  
   794  func (bd *byteDecoder) DecodeRLP(s *Stream) error {
   795  	_, err := s.Uint()
   796  	*bd = 255
   797  	return err
   798  }
   799  
   800  func (bd byteDecoder) called() bool {
   801  	return bd == 255
   802  }
   803  
   804  // This test verifies that the byte slice/byte array logic
   805  // does not kick in for element types implementing Decoder.
   806  func TestDecoderInByteSlice(t *testing.T) {
   807  	var slice []byteDecoder
   808  	if err := Decode(bytes.NewReader(unhex("C101")), &slice); err != nil {
   809  		t.Errorf("unexpected Decode error %v", err)
   810  	} else if !slice[0].called() {
   811  		t.Errorf("DecodeRLP not called for slice element")
   812  	}
   813  
   814  	var array [1]byteDecoder
   815  	if err := Decode(bytes.NewReader(unhex("C101")), &array); err != nil {
   816  		t.Errorf("unexpected Decode error %v", err)
   817  	} else if !array[0].called() {
   818  		t.Errorf("DecodeRLP not called for array element")
   819  	}
   820  }
   821  
   822  type unencodableDecoder func()
   823  
   824  func (f *unencodableDecoder) DecodeRLP(s *Stream) error {
   825  	if _, err := s.List(); err != nil {
   826  		return err
   827  	}
   828  	if err := s.ListEnd(); err != nil {
   829  		return err
   830  	}
   831  	*f = func() {}
   832  	return nil
   833  }
   834  
   835  func TestDecoderFunc(t *testing.T) {
   836  	var x func()
   837  	if err := DecodeBytes([]byte{0xC0}, (*unencodableDecoder)(&x)); err != nil {
   838  		t.Fatal(err)
   839  	}
   840  	x()
   841  }
   842  
   843  func ExampleDecode() {
   844  	input, _ := hex.DecodeString("C90A1486666F6F626172")
   845  
   846  	type example struct {
   847  		A, B   uint
   848  		String string
   849  	}
   850  
   851  	var s example
   852  	err := Decode(bytes.NewReader(input), &s)
   853  	if err != nil {
   854  		fmt.Printf("Error: %v\n", err)
   855  	} else {
   856  		fmt.Printf("Decoded value: %#v\n", s)
   857  	}
   858  	// Output:
   859  	// Decoded value: rlp.example{A:0xa, B:0x14, String:"foobar"}
   860  }
   861  
   862  func ExampleDecode_structTagNil() {
   863  	// In this example, we'll use the "nil" struct tag to change
   864  	// how a pointer-typed field is decoded. The input contains an RLP
   865  	// list of one element, an empty string.
   866  	input := []byte{0xC1, 0x80}
   867  
   868  	// This type uses the normal rules.
   869  	// The empty input string is decoded as a pointer to an empty Go string.
   870  	var normalRules struct {
   871  		String *string
   872  	}
   873  	Decode(bytes.NewReader(input), &normalRules)
   874  	fmt.Printf("normal: String = %q\n", *normalRules.String)
   875  
   876  	// This type uses the struct tag.
   877  	// The empty input string is decoded as a nil pointer.
   878  	var withEmptyOK struct {
   879  		String *string `rlp:"nil"`
   880  	}
   881  	Decode(bytes.NewReader(input), &withEmptyOK)
   882  	fmt.Printf("with nil tag: String = %v\n", withEmptyOK.String)
   883  
   884  	// Output:
   885  	// normal: String = ""
   886  	// with nil tag: String = <nil>
   887  }
   888  
   889  func ExampleStream() {
   890  	input, _ := hex.DecodeString("C90A1486666F6F626172")
   891  	s := NewStream(bytes.NewReader(input), 0)
   892  
   893  	// Check what kind of value lies ahead
   894  	kind, size, _ := s.Kind()
   895  	fmt.Printf("Kind: %v size:%d\n", kind, size)
   896  
   897  	// Enter the list
   898  	if _, err := s.List(); err != nil {
   899  		fmt.Printf("List error: %v\n", err)
   900  		return
   901  	}
   902  
   903  	// Decode elements
   904  	fmt.Println(s.Uint())
   905  	fmt.Println(s.Uint())
   906  	fmt.Println(s.Bytes())
   907  
   908  	// Acknowledge end of list
   909  	if err := s.ListEnd(); err != nil {
   910  		fmt.Printf("ListEnd error: %v\n", err)
   911  	}
   912  	// Output:
   913  	// Kind: List size:9
   914  	// 10 <nil>
   915  	// 20 <nil>
   916  	// [102 111 111 98 97 114] <nil>
   917  }
   918  
   919  func BenchmarkDecodeUints(b *testing.B) {
   920  	enc := encodeTestSlice(90000)
   921  	b.SetBytes(int64(len(enc)))
   922  	b.ReportAllocs()
   923  	b.ResetTimer()
   924  
   925  	for i := 0; i < b.N; i++ {
   926  		var s []uint
   927  		r := bytes.NewReader(enc)
   928  		if err := Decode(r, &s); err != nil {
   929  			b.Fatalf("Decode error: %v", err)
   930  		}
   931  	}
   932  }
   933  
   934  func BenchmarkDecodeUintsReused(b *testing.B) {
   935  	enc := encodeTestSlice(100000)
   936  	b.SetBytes(int64(len(enc)))
   937  	b.ReportAllocs()
   938  	b.ResetTimer()
   939  
   940  	var s []uint
   941  	for i := 0; i < b.N; i++ {
   942  		r := bytes.NewReader(enc)
   943  		if err := Decode(r, &s); err != nil {
   944  			b.Fatalf("Decode error: %v", err)
   945  		}
   946  	}
   947  }
   948  
   949  func BenchmarkDecodeByteArrayStruct(b *testing.B) {
   950  	enc, err := EncodeToBytes(&byteArrayStruct{})
   951  	if err != nil {
   952  		b.Fatal(err)
   953  	}
   954  	b.SetBytes(int64(len(enc)))
   955  	b.ReportAllocs()
   956  	b.ResetTimer()
   957  
   958  	var out byteArrayStruct
   959  	for i := 0; i < b.N; i++ {
   960  		if err := DecodeBytes(enc, &out); err != nil {
   961  			b.Fatal(err)
   962  		}
   963  	}
   964  }
   965  
   966  func BenchmarkDecodeBigInts(b *testing.B) {
   967  	ints := make([]*big.Int, 200)
   968  	for i := range ints {
   969  		ints[i] = math.BigPow(2, int64(i))
   970  	}
   971  	enc, err := EncodeToBytes(ints)
   972  	if err != nil {
   973  		b.Fatal(err)
   974  	}
   975  	b.SetBytes(int64(len(enc)))
   976  	b.ReportAllocs()
   977  	b.ResetTimer()
   978  
   979  	var out []*big.Int
   980  	for i := 0; i < b.N; i++ {
   981  		if err := DecodeBytes(enc, &out); err != nil {
   982  			b.Fatal(err)
   983  		}
   984  	}
   985  }
   986  
   987  func encodeTestSlice(n uint) []byte {
   988  	s := make([]uint, n)
   989  	for i := uint(0); i < n; i++ {
   990  		s[i] = i
   991  	}
   992  	b, err := EncodeToBytes(s)
   993  	if err != nil {
   994  		panic(fmt.Sprintf("encode error: %v", err))
   995  	}
   996  	return b
   997  }
   998  
   999  func unhex(str string) []byte {
  1000  	b, err := hex.DecodeString(strings.Replace(str, " ", "", -1))
  1001  	if err != nil {
  1002  		panic(fmt.Sprintf("invalid hex string: %q", str))
  1003  	}
  1004  	return b
  1005  }