github.com/cheng762/platon-go@v1.8.17-0.20190529111256-7deff2d7be26/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  
    31  func TestStreamKind(t *testing.T) {
    32  	tests := []struct {
    33  		input    string
    34  		wantKind Kind
    35  		wantLen  uint64
    36  	}{
    37  		{"00", Byte, 0},
    38  		{"01", Byte, 0},
    39  		{"7F", Byte, 0},
    40  		{"80", String, 0},
    41  		{"B7", String, 55},
    42  		{"B90400", String, 1024},
    43  		{"BFFFFFFFFFFFFFFFFF", String, ^uint64(0)},
    44  		{"C0", List, 0},
    45  		{"C8", List, 8},
    46  		{"F7", List, 55},
    47  		{"F90400", List, 1024},
    48  		{"FFFFFFFFFFFFFFFFFF", List, ^uint64(0)},
    49  	}
    50  
    51  	for i, test := range tests {
    52  		// using plainReader to inhibit input limit errors.
    53  		s := NewStream(newPlainReader(unhex(test.input)), 0)
    54  		kind, len, err := s.Kind()
    55  		if err != nil {
    56  			t.Errorf("test %d: Kind returned error: %v", i, err)
    57  			continue
    58  		}
    59  		if kind != test.wantKind {
    60  			t.Errorf("test %d: kind mismatch: got %d, want %d", i, kind, test.wantKind)
    61  		}
    62  		if len != test.wantLen {
    63  			t.Errorf("test %d: len mismatch: got %d, want %d", i, len, test.wantLen)
    64  		}
    65  	}
    66  }
    67  
    68  func TestNewListStream(t *testing.T) {
    69  	ls := NewListStream(bytes.NewReader(unhex("0101010101")), 3)
    70  	if k, size, err := ls.Kind(); k != List || size != 3 || err != nil {
    71  		t.Errorf("Kind() returned (%v, %d, %v), expected (List, 3, nil)", k, size, err)
    72  	}
    73  	if size, err := ls.List(); size != 3 || err != nil {
    74  		t.Errorf("List() returned (%d, %v), expected (3, nil)", size, err)
    75  	}
    76  	for i := 0; i < 3; i++ {
    77  		if val, err := ls.Uint(); val != 1 || err != nil {
    78  			t.Errorf("Uint() returned (%d, %v), expected (1, nil)", val, err)
    79  		}
    80  	}
    81  	if err := ls.ListEnd(); err != nil {
    82  		t.Errorf("ListEnd() returned %v, expected (3, nil)", err)
    83  	}
    84  }
    85  
    86  func TestStreamErrors(t *testing.T) {
    87  	withoutInputLimit := func(b []byte) *Stream {
    88  		return NewStream(newPlainReader(b), 0)
    89  	}
    90  	withCustomInputLimit := func(limit uint64) func([]byte) *Stream {
    91  		return func(b []byte) *Stream {
    92  			return NewStream(bytes.NewReader(b), limit)
    93  		}
    94  	}
    95  
    96  	type calls []string
    97  	tests := []struct {
    98  		string
    99  		calls
   100  		newStream func([]byte) *Stream // uses bytes.Reader if nil
   101  		error     error
   102  	}{
   103  		{"C0", calls{"Bytes"}, nil, ErrExpectedString},
   104  		{"C0", calls{"Uint"}, nil, ErrExpectedString},
   105  		{"89000000000000000001", calls{"Uint"}, nil, errUintOverflow},
   106  		{"00", calls{"List"}, nil, ErrExpectedList},
   107  		{"80", calls{"List"}, nil, ErrExpectedList},
   108  		{"C0", calls{"List", "Uint"}, nil, EOL},
   109  		{"C8C9010101010101010101", calls{"List", "Kind"}, nil, ErrElemTooLarge},
   110  		{"C3C2010201", calls{"List", "List", "Uint", "Uint", "ListEnd", "Uint"}, nil, EOL},
   111  		{"00", calls{"ListEnd"}, nil, errNotInList},
   112  		{"C401020304", calls{"List", "Uint", "ListEnd"}, nil, errNotAtEOL},
   113  
   114  		// Non-canonical integers (e.g. leading zero bytes).
   115  		{"00", calls{"Uint"}, nil, ErrCanonInt},
   116  		{"820002", calls{"Uint"}, nil, ErrCanonInt},
   117  		{"8133", calls{"Uint"}, nil, ErrCanonSize},
   118  		{"817F", calls{"Uint"}, nil, ErrCanonSize},
   119  		{"8180", calls{"Uint"}, nil, nil},
   120  
   121  		// Non-valid boolean
   122  		{"02", calls{"Bool"}, nil, errors.New("rlp: invalid boolean value: 2")},
   123  
   124  		// Size tags must use the smallest possible encoding.
   125  		// Leading zero bytes in the size tag are also rejected.
   126  		{"8100", calls{"Uint"}, nil, ErrCanonSize},
   127  		{"8100", calls{"Bytes"}, nil, ErrCanonSize},
   128  		{"8101", calls{"Bytes"}, nil, ErrCanonSize},
   129  		{"817F", calls{"Bytes"}, nil, ErrCanonSize},
   130  		{"8180", calls{"Bytes"}, nil, nil},
   131  		{"B800", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
   132  		{"B90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
   133  		{"B90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
   134  		{"BA0002FFFF", calls{"Bytes"}, withoutInputLimit, ErrCanonSize},
   135  		{"F800", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
   136  		{"F90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
   137  		{"F90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
   138  		{"FA0002FFFF", calls{"List"}, withoutInputLimit, ErrCanonSize},
   139  
   140  		// Expected EOF
   141  		{"", calls{"Kind"}, nil, io.EOF},
   142  		{"", calls{"Uint"}, nil, io.EOF},
   143  		{"", calls{"List"}, nil, io.EOF},
   144  		{"8180", calls{"Uint", "Uint"}, nil, io.EOF},
   145  		{"C0", calls{"List", "ListEnd", "List"}, nil, io.EOF},
   146  
   147  		{"", calls{"List"}, withoutInputLimit, io.EOF},
   148  		{"8180", calls{"Uint", "Uint"}, withoutInputLimit, io.EOF},
   149  		{"C0", calls{"List", "ListEnd", "List"}, withoutInputLimit, io.EOF},
   150  
   151  		// Input limit errors.
   152  		{"81", calls{"Bytes"}, nil, ErrValueTooLarge},
   153  		{"81", calls{"Uint"}, nil, ErrValueTooLarge},
   154  		{"81", calls{"Raw"}, nil, ErrValueTooLarge},
   155  		{"BFFFFFFFFFFFFFFFFFFF", calls{"Bytes"}, nil, ErrValueTooLarge},
   156  		{"C801", calls{"List"}, nil, ErrValueTooLarge},
   157  
   158  		// Test for list element size check overflow.
   159  		{"CD04040404FFFFFFFFFFFFFFFFFF0303", calls{"List", "Uint", "Uint", "Uint", "Uint", "List"}, nil, ErrElemTooLarge},
   160  
   161  		// Test for input limit overflow. Since we are counting the limit
   162  		// down toward zero in Stream.remaining, reading too far can overflow
   163  		// remaining to a large value, effectively disabling the limit.
   164  		{"C40102030401", calls{"Raw", "Uint"}, withCustomInputLimit(5), io.EOF},
   165  		{"C4010203048180", calls{"Raw", "Uint"}, withCustomInputLimit(6), ErrValueTooLarge},
   166  
   167  		// Check that the same calls are fine without a limit.
   168  		{"C40102030401", calls{"Raw", "Uint"}, withoutInputLimit, nil},
   169  		{"C4010203048180", calls{"Raw", "Uint"}, withoutInputLimit, nil},
   170  
   171  		// Unexpected EOF. This only happens when there is
   172  		// no input limit, so the reader needs to be 'dumbed down'.
   173  		{"81", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF},
   174  		{"81", calls{"Uint"}, withoutInputLimit, io.ErrUnexpectedEOF},
   175  		{"BFFFFFFFFFFFFFFF", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF},
   176  		{"C801", calls{"List", "Uint", "Uint"}, withoutInputLimit, io.ErrUnexpectedEOF},
   177  
   178  		// This test verifies that the input position is advanced
   179  		// correctly when calling Bytes for empty strings. Kind can be called
   180  		// any number of times in between and doesn't advance.
   181  		{"C3808080", calls{
   182  			"List",  // enter the list
   183  			"Bytes", // past first element
   184  
   185  			"Kind", "Kind", "Kind", // this shouldn't advance
   186  
   187  			"Bytes", // past second element
   188  
   189  			"Kind", "Kind", // can't hurt to try
   190  
   191  			"Bytes", // past final element
   192  			"Bytes", // this one should fail
   193  		}, nil, EOL},
   194  	}
   195  
   196  testfor:
   197  	for i, test := range tests {
   198  		if test.newStream == nil {
   199  			test.newStream = func(b []byte) *Stream { return NewStream(bytes.NewReader(b), 0) }
   200  		}
   201  		s := test.newStream(unhex(test.string))
   202  		rs := reflect.ValueOf(s)
   203  		for j, call := range test.calls {
   204  			fval := rs.MethodByName(call)
   205  			ret := fval.Call(nil)
   206  			err := "<nil>"
   207  			if lastret := ret[len(ret)-1].Interface(); lastret != nil {
   208  				err = lastret.(error).Error()
   209  			}
   210  			if j == len(test.calls)-1 {
   211  				want := "<nil>"
   212  				if test.error != nil {
   213  					want = test.error.Error()
   214  				}
   215  				if err != want {
   216  					t.Log(test)
   217  					t.Errorf("test %d: last call (%s) error mismatch\ngot:  %s\nwant: %s",
   218  						i, call, err, test.error)
   219  				}
   220  			} else if err != "<nil>" {
   221  				t.Log(test)
   222  				t.Errorf("test %d: call %d (%s) unexpected error: %q", i, j, call, err)
   223  				continue testfor
   224  			}
   225  		}
   226  	}
   227  }
   228  
   229  func TestStreamList(t *testing.T) {
   230  	s := NewStream(bytes.NewReader(unhex("C80102030405060708")), 0)
   231  
   232  	len, err := s.List()
   233  	if err != nil {
   234  		t.Fatalf("List error: %v", err)
   235  	}
   236  	if len != 8 {
   237  		t.Fatalf("List returned invalid length, got %d, want 8", len)
   238  	}
   239  
   240  	for i := uint64(1); i <= 8; i++ {
   241  		v, err := s.Uint()
   242  		if err != nil {
   243  			t.Fatalf("Uint error: %v", err)
   244  		}
   245  		if i != v {
   246  			t.Errorf("Uint returned wrong value, got %d, want %d", v, i)
   247  		}
   248  	}
   249  
   250  	if _, err := s.Uint(); err != EOL {
   251  		t.Errorf("Uint error mismatch, got %v, want %v", err, EOL)
   252  	}
   253  	if err = s.ListEnd(); err != nil {
   254  		t.Fatalf("ListEnd error: %v", err)
   255  	}
   256  }
   257  
   258  func TestStreamRaw(t *testing.T) {
   259  	tests := []struct {
   260  		input  string
   261  		output string
   262  	}{
   263  		{
   264  			"C58401010101",
   265  			"8401010101",
   266  		},
   267  		{
   268  			"F842B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
   269  			"B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
   270  		},
   271  	}
   272  	for i, tt := range tests {
   273  		s := NewStream(bytes.NewReader(unhex(tt.input)), 0)
   274  		s.List()
   275  
   276  		want := unhex(tt.output)
   277  		raw, err := s.Raw()
   278  		if err != nil {
   279  			t.Fatal(err)
   280  		}
   281  		if !bytes.Equal(want, raw) {
   282  			t.Errorf("test %d: raw mismatch: got %x, want %x", i, raw, want)
   283  		}
   284  	}
   285  }
   286  
   287  func TestStreamRaw2(t *testing.T) {
   288  	tests := []struct {
   289  		input  string
   290  		output string
   291  	}{
   292  		{
   293  			"C58401010101",
   294  			"8401010101",
   295  		},
   296  		{
   297  			"F842B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
   298  			"B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
   299  		},
   300  	}
   301  	for i, tt := range tests {
   302  		s := NewStream(bytes.NewReader(unhex(tt.input)), 0)
   303  		s.List()
   304  
   305  		want := unhex(tt.output)
   306  		raw, err := s.Raw()
   307  		println("want: ", want, " raw ", raw)
   308  		if err != nil {
   309  			t.Fatal(err)
   310  		}
   311  		if !bytes.Equal(want, raw) {
   312  			t.Errorf("test %d: raw mismatch: got %x, want %x", i, raw, want)
   313  		}
   314  	}
   315  }
   316  
   317  func TestDecodeErrors(t *testing.T) {
   318  	r := bytes.NewReader(nil)
   319  
   320  	if err := Decode(r, nil); err != errDecodeIntoNil {
   321  		t.Errorf("Decode(r, nil) error mismatch, got %q, want %q", err, errDecodeIntoNil)
   322  	}
   323  
   324  	var nilptr *struct{}
   325  	if err := Decode(r, nilptr); err != errDecodeIntoNil {
   326  		t.Errorf("Decode(r, nilptr) error mismatch, got %q, want %q", err, errDecodeIntoNil)
   327  	}
   328  
   329  	if err := Decode(r, struct{}{}); err != errNoPointer {
   330  		t.Errorf("Decode(r, struct{}{}) error mismatch, got %q, want %q", err, errNoPointer)
   331  	}
   332  
   333  	expectErr := "rlp: type chan bool is not RLP-serializable"
   334  	if err := Decode(r, new(chan bool)); err == nil || err.Error() != expectErr {
   335  		t.Errorf("Decode(r, new(chan bool)) error mismatch, got %q, want %q", err, expectErr)
   336  	}
   337  
   338  	if err := Decode(r, new(uint)); err != io.EOF {
   339  		t.Errorf("Decode(r, new(int)) error mismatch, got %q, want %q", err, io.EOF)
   340  	}
   341  }
   342  
   343  type decodeTest struct {
   344  	input string
   345  	ptr   interface{}
   346  	value interface{}
   347  	error string
   348  }
   349  
   350  type simplestruct struct {
   351  	A uint
   352  	B string
   353  }
   354  
   355  type recstruct struct {
   356  	I     uint
   357  	Child *recstruct `rlp:"nil"`
   358  }
   359  
   360  type invalidTail1 struct {
   361  	A uint `rlp:"tail"`
   362  	B string
   363  }
   364  
   365  type invalidTail2 struct {
   366  	A uint
   367  	B string `rlp:"tail"`
   368  }
   369  
   370  type tailRaw struct {
   371  	A    uint
   372  	Tail []RawValue `rlp:"tail"`
   373  }
   374  
   375  type tailUint struct {
   376  	A    uint
   377  	Tail []uint `rlp:"tail"`
   378  }
   379  
   380  var (
   381  	veryBigInt = big.NewInt(0).Add(
   382  		big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16),
   383  		big.NewInt(0xFFFF),
   384  	)
   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: "01", ptr: new(*big.Int), value: big.NewInt(1)},
   462  	{input: "89FFFFFFFFFFFFFFFFFF", ptr: new(*big.Int), value: veryBigInt},
   463  	{input: "10", ptr: new(big.Int), value: *big.NewInt(16)}, // non-pointer also works
   464  	{input: "C0", ptr: new(*big.Int), error: "rlp: expected input string or byte for *big.Int"},
   465  	{input: "820001", ptr: new(big.Int), error: "rlp: non-canonical integer (leading zero bytes) for *big.Int"},
   466  	{input: "8105", ptr: new(big.Int), error: "rlp: non-canonical size information for *big.Int"},
   467  
   468  	// structs
   469  	{
   470  		input: "C50583343434",
   471  		ptr:   new(simplestruct),
   472  		value: simplestruct{5, "444"},
   473  	},
   474  	{
   475  		input: "C601C402C203C0",
   476  		ptr:   new(recstruct),
   477  		value: recstruct{1, &recstruct{2, &recstruct{3, nil}}},
   478  	},
   479  
   480  	// struct errors
   481  	{
   482  		input: "C0",
   483  		ptr:   new(simplestruct),
   484  		error: "rlp: too few elements for rlp.simplestruct",
   485  	},
   486  	{
   487  		input: "C105",
   488  		ptr:   new(simplestruct),
   489  		error: "rlp: too few elements for rlp.simplestruct",
   490  	},
   491  	{
   492  		input: "C7C50583343434C0",
   493  		ptr:   new([]*simplestruct),
   494  		error: "rlp: too few elements for rlp.simplestruct, decoding into ([]*rlp.simplestruct)[1]",
   495  	},
   496  	{
   497  		input: "83222222",
   498  		ptr:   new(simplestruct),
   499  		error: "rlp: expected input list for rlp.simplestruct",
   500  	},
   501  	{
   502  		input: "C3010101",
   503  		ptr:   new(simplestruct),
   504  		error: "rlp: input list has too many elements for rlp.simplestruct",
   505  	},
   506  	{
   507  		input: "C501C3C00000",
   508  		ptr:   new(recstruct),
   509  		error: "rlp: expected input string or byte for uint, decoding into (rlp.recstruct).Child.I",
   510  	},
   511  	{
   512  		input: "C0",
   513  		ptr:   new(invalidTail1),
   514  		error: "rlp: invalid struct tag \"tail\" for rlp.invalidTail1.A (must be on last field)",
   515  	},
   516  	{
   517  		input: "C0",
   518  		ptr:   new(invalidTail2),
   519  		error: "rlp: invalid struct tag \"tail\" for rlp.invalidTail2.B (field type is not slice)",
   520  	},
   521  	{
   522  		input: "C50102C20102",
   523  		ptr:   new(tailUint),
   524  		error: "rlp: expected input string or byte for uint, decoding into (rlp.tailUint).Tail[1]",
   525  	},
   526  
   527  	// struct tag "tail"
   528  	{
   529  		input: "C3010203",
   530  		ptr:   new(tailRaw),
   531  		value: tailRaw{A: 1, Tail: []RawValue{unhex("02"), unhex("03")}},
   532  	},
   533  	{
   534  		input: "C20102",
   535  		ptr:   new(tailRaw),
   536  		value: tailRaw{A: 1, Tail: []RawValue{unhex("02")}},
   537  	},
   538  	{
   539  		input: "C101",
   540  		ptr:   new(tailRaw),
   541  		value: tailRaw{A: 1, Tail: []RawValue{}},
   542  	},
   543  
   544  	// struct tag "-"
   545  	{
   546  		input: "C20102",
   547  		ptr:   new(hasIgnoredField),
   548  		value: hasIgnoredField{A: 1, C: 2},
   549  	},
   550  
   551  	// RawValue
   552  	{input: "01", ptr: new(RawValue), value: RawValue(unhex("01"))},
   553  	{input: "82FFFF", ptr: new(RawValue), value: RawValue(unhex("82FFFF"))},
   554  	{input: "C20102", ptr: new([]RawValue), value: []RawValue{unhex("01"), unhex("02")}},
   555  
   556  	// pointers
   557  	{input: "00", ptr: new(*[]byte), value: &[]byte{0}},
   558  	{input: "80", ptr: new(*uint), value: uintp(0)},
   559  	{input: "C0", ptr: new(*uint), error: "rlp: expected input string or byte for uint"},
   560  	{input: "07", ptr: new(*uint), value: uintp(7)},
   561  	{input: "817F", ptr: new(*uint), error: "rlp: non-canonical size information for uint"},
   562  	{input: "8180", ptr: new(*uint), value: uintp(0x80)},
   563  	{input: "C109", ptr: new(*[]uint), value: &[]uint{9}},
   564  	{input: "C58403030303", ptr: new(*[][]byte), value: &[][]byte{{3, 3, 3, 3}}},
   565  
   566  	// check that input position is advanced also for empty values.
   567  	{input: "C3808005", ptr: new([]*uint), value: []*uint{uintp(0), uintp(0), uintp(5)}},
   568  
   569  	// interface{}
   570  	{input: "00", ptr: new(interface{}), value: []byte{0}},
   571  	{input: "01", ptr: new(interface{}), value: []byte{1}},
   572  	{input: "80", ptr: new(interface{}), value: []byte{}},
   573  	{input: "850505050505", ptr: new(interface{}), value: []byte{5, 5, 5, 5, 5}},
   574  	{input: "C0", ptr: new(interface{}), value: []interface{}{}},
   575  	{input: "C50183040404", ptr: new(interface{}), value: []interface{}{[]byte{1}, []byte{4, 4, 4}}},
   576  	{
   577  		input: "C3010203",
   578  		ptr:   new([]io.Reader),
   579  		error: "rlp: type io.Reader is not RLP-serializable",
   580  	},
   581  
   582  	// fuzzer crashes
   583  	{
   584  		input: "c330f9c030f93030ce3030303030303030bd303030303030",
   585  		ptr:   new(interface{}),
   586  		error: "rlp: element is larger than containing list",
   587  	},
   588  }
   589  
   590  func uintp(i uint) *uint { return &i }
   591  
   592  func runTests(t *testing.T, decode func([]byte, interface{}) error) {
   593  	for i, test := range decodeTests {
   594  		input, err := hex.DecodeString(test.input)
   595  		if err != nil {
   596  			t.Errorf("test %d: invalid hex input %q", i, test.input)
   597  			continue
   598  		}
   599  		err = decode(input, test.ptr)
   600  		if err != nil && test.error == "" {
   601  			t.Errorf("test %d: unexpected Decode error: %v\ndecoding into %T\ninput %q",
   602  				i, err, test.ptr, test.input)
   603  			continue
   604  		}
   605  		if test.error != "" && fmt.Sprint(err) != test.error {
   606  			t.Errorf("test %d: Decode error mismatch\ngot  %v\nwant %v\ndecoding into %T\ninput %q",
   607  				i, err, test.error, test.ptr, test.input)
   608  			continue
   609  		}
   610  		deref := reflect.ValueOf(test.ptr).Elem().Interface()
   611  		if err == nil && !reflect.DeepEqual(deref, test.value) {
   612  			t.Errorf("test %d: value mismatch\ngot  %#v\nwant %#v\ndecoding into %T\ninput %q",
   613  				i, deref, test.value, test.ptr, test.input)
   614  		}
   615  	}
   616  }
   617  
   618  func TestDecodeWithByteReader(t *testing.T) {
   619  	runTests(t, func(input []byte, into interface{}) error {
   620  		return Decode(bytes.NewReader(input), into)
   621  	})
   622  }
   623  
   624  // plainReader reads from a byte slice but does not
   625  // implement ReadByte. It is also not recognized by the
   626  // size validation. This is useful to test how the decoder
   627  // behaves on a non-buffered input stream.
   628  type plainReader []byte
   629  
   630  func newPlainReader(b []byte) io.Reader {
   631  	return (*plainReader)(&b)
   632  }
   633  
   634  func (r *plainReader) Read(buf []byte) (n int, err error) {
   635  	if len(*r) == 0 {
   636  		return 0, io.EOF
   637  	}
   638  	n = copy(buf, *r)
   639  	*r = (*r)[n:]
   640  	return n, nil
   641  }
   642  
   643  func TestDecodeWithNonByteReader(t *testing.T) {
   644  	runTests(t, func(input []byte, into interface{}) error {
   645  		return Decode(newPlainReader(input), into)
   646  	})
   647  }
   648  
   649  func TestDecodeStreamReset(t *testing.T) {
   650  	s := NewStream(nil, 0)
   651  	runTests(t, func(input []byte, into interface{}) error {
   652  		s.Reset(bytes.NewReader(input), 0)
   653  		return s.Decode(into)
   654  	})
   655  }
   656  
   657  type testDecoder struct{ called bool }
   658  
   659  func (t *testDecoder) DecodeRLP(s *Stream) error {
   660  	if _, err := s.Uint(); err != nil {
   661  		return err
   662  	}
   663  	t.called = true
   664  	return nil
   665  }
   666  
   667  func TestDecodeDecoder(t *testing.T) {
   668  	var s struct {
   669  		T1 testDecoder
   670  		T2 *testDecoder
   671  		T3 **testDecoder
   672  	}
   673  	if err := Decode(bytes.NewReader(unhex("C3010203")), &s); err != nil {
   674  		t.Fatalf("Decode error: %v", err)
   675  	}
   676  
   677  	if !s.T1.called {
   678  		t.Errorf("DecodeRLP was not called for (non-pointer) testDecoder")
   679  	}
   680  
   681  	if s.T2 == nil {
   682  		t.Errorf("*testDecoder has not been allocated")
   683  	} else if !s.T2.called {
   684  		t.Errorf("DecodeRLP was not called for *testDecoder")
   685  	}
   686  
   687  	if s.T3 == nil || *s.T3 == nil {
   688  		t.Errorf("**testDecoder has not been allocated")
   689  	} else if !(*s.T3).called {
   690  		t.Errorf("DecodeRLP was not called for **testDecoder")
   691  	}
   692  }
   693  
   694  type byteDecoder byte
   695  
   696  func (bd *byteDecoder) DecodeRLP(s *Stream) error {
   697  	_, err := s.Uint()
   698  	*bd = 255
   699  	return err
   700  }
   701  
   702  func (bd byteDecoder) called() bool {
   703  	return bd == 255
   704  }
   705  
   706  // This test verifies that the byte slice/byte array logic
   707  // does not kick in for element types implementing Decoder.
   708  func TestDecoderInByteSlice(t *testing.T) {
   709  	var slice []byteDecoder
   710  	if err := Decode(bytes.NewReader(unhex("C101")), &slice); err != nil {
   711  		t.Errorf("unexpected Decode error %v", err)
   712  	} else if !slice[0].called() {
   713  		t.Errorf("DecodeRLP not called for slice element")
   714  	}
   715  
   716  	var array [1]byteDecoder
   717  	if err := Decode(bytes.NewReader(unhex("C101")), &array); err != nil {
   718  		t.Errorf("unexpected Decode error %v", err)
   719  	} else if !array[0].called() {
   720  		t.Errorf("DecodeRLP not called for array element")
   721  	}
   722  }
   723  
   724  func ExampleDecode() {
   725  	input, _ := hex.DecodeString("C90A1486666F6F626172")
   726  
   727  	type example struct {
   728  		A, B    uint
   729  		private uint // private fields are ignored
   730  		String  string
   731  	}
   732  
   733  	var s example
   734  	err := Decode(bytes.NewReader(input), &s)
   735  	if err != nil {
   736  		fmt.Printf("Error: %v\n", err)
   737  	} else {
   738  		fmt.Printf("Decoded value: %#v\n", s)
   739  	}
   740  	// Output:
   741  	// Decoded value: rlp.example{A:0xa, B:0x14, private:0x0, String:"foobar"}
   742  }
   743  
   744  func ExampleDecode_structTagNil() {
   745  	// In this example, we'll use the "nil" struct tag to change
   746  	// how a pointer-typed field is decoded. The input contains an RLP
   747  	// list of one element, an empty string.
   748  	input := []byte{0xC1, 0x80}
   749  
   750  	// This type uses the normal rules.
   751  	// The empty input string is decoded as a pointer to an empty Go string.
   752  	var normalRules struct {
   753  		String *string
   754  	}
   755  	Decode(bytes.NewReader(input), &normalRules)
   756  	fmt.Printf("normal: String = %q\n", *normalRules.String)
   757  
   758  	// This type uses the struct tag.
   759  	// The empty input string is decoded as a nil pointer.
   760  	var withEmptyOK struct {
   761  		String *string `rlp:"nil"`
   762  	}
   763  	Decode(bytes.NewReader(input), &withEmptyOK)
   764  	fmt.Printf("with nil tag: String = %v\n", withEmptyOK.String)
   765  
   766  	// Output:
   767  	// normal: String = ""
   768  	// with nil tag: String = <nil>
   769  }
   770  
   771  func ExampleStream() {
   772  	input, _ := hex.DecodeString("C90A1486666F6F626172")
   773  	s := NewStream(bytes.NewReader(input), 0)
   774  
   775  	// Check what kind of value lies ahead
   776  	kind, size, _ := s.Kind()
   777  	//fmt.Println(kind)
   778  	fmt.Printf("Kind: %v size:%d\n", kind, size)
   779  
   780  	// Enter the list
   781  	if _, err := s.List(); err != nil {
   782  		fmt.Printf("List error: %v\n", err)
   783  		return
   784  	}
   785  
   786  	// Decode elements
   787  	fmt.Println(s.Uint())
   788  	fmt.Println(s.Uint())
   789  	fmt.Println(s.Bytes())
   790  
   791  	// Acknowledge end of list
   792  	if err := s.ListEnd(); err != nil {
   793  		fmt.Printf("ListEnd error: %v\n", err)
   794  	}
   795  	// Output:
   796  	// Kind: List size:9
   797  	// 10 <nil>
   798  	// 20 <nil>
   799  	// [102 111 111 98 97 114] <nil>
   800  }
   801  
   802  func BenchmarkDecode(b *testing.B) {
   803  	enc := encodeTestSlice(90000)
   804  	b.SetBytes(int64(len(enc)))
   805  	b.ReportAllocs()
   806  	b.ResetTimer()
   807  
   808  	for i := 0; i < b.N; i++ {
   809  		var s []uint
   810  		r := bytes.NewReader(enc)
   811  		if err := Decode(r, &s); err != nil {
   812  			b.Fatalf("Decode error: %v", err)
   813  		}
   814  	}
   815  }
   816  
   817  func BenchmarkDecodeIntSliceReuse(b *testing.B) {
   818  	enc := encodeTestSlice(100000)
   819  	b.SetBytes(int64(len(enc)))
   820  	b.ReportAllocs()
   821  	b.ResetTimer()
   822  
   823  	var s []uint
   824  	for i := 0; i < b.N; i++ {
   825  		r := bytes.NewReader(enc)
   826  		if err := Decode(r, &s); err != nil {
   827  			b.Fatalf("Decode error: %v", err)
   828  		}
   829  	}
   830  }
   831  
   832  func encodeTestSlice(n uint) []byte {
   833  	s := make([]uint, n)
   834  	for i := uint(0); i < n; i++ {
   835  		s[i] = i
   836  	}
   837  	b, err := EncodeToBytes(s)
   838  	if err != nil {
   839  		panic(fmt.Sprintf("encode error: %v", err))
   840  	}
   841  	return b
   842  }
   843  
   844  func unhex(str string) []byte {
   845  	b, err := hex.DecodeString(strings.Replace(str, " ", "", -1))
   846  	if err != nil {
   847  		panic(fmt.Sprintf("invalid hex string: %q", str))
   848  	}
   849  	return b
   850  }