github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/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/sixexorg/magnetic-ring/common"
    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 invalidTail1 struct {
   333  	A uint `rlp:"tail"`
   334  	B string
   335  }
   336  
   337  type invalidTail2 struct {
   338  	A uint
   339  	B string `rlp:"tail"`
   340  }
   341  
   342  type tailRaw struct {
   343  	A    uint
   344  	Tail []RawValue `rlp:"tail"`
   345  }
   346  
   347  type tailUint struct {
   348  	A    uint
   349  	Tail []uint `rlp:"tail"`
   350  }
   351  
   352  var (
   353  	veryBigInt = big.NewInt(0).Add(
   354  		big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16),
   355  		big.NewInt(0xFFFF),
   356  	)
   357  )
   358  
   359  type hasIgnoredField struct {
   360  	A uint
   361  	B uint `rlp:"-"`
   362  	C uint
   363  }
   364  
   365  var decodeTests = []decodeTest{
   366  	// booleans
   367  	{input: "01", ptr: new(bool), value: true},
   368  	{input: "80", ptr: new(bool), value: false},
   369  	{input: "02", ptr: new(bool), error: "rlp: invalid boolean value: 2"},
   370  
   371  	// integers
   372  	{input: "05", ptr: new(uint32), value: uint32(5)},
   373  	{input: "80", ptr: new(uint32), value: uint32(0)},
   374  	{input: "820505", ptr: new(uint32), value: uint32(0x0505)},
   375  	{input: "83050505", ptr: new(uint32), value: uint32(0x050505)},
   376  	{input: "8405050505", ptr: new(uint32), value: uint32(0x05050505)},
   377  	{input: "850505050505", ptr: new(uint32), error: "rlp: input string too long for uint32"},
   378  	{input: "C0", ptr: new(uint32), error: "rlp: expected input string or byte for uint32"},
   379  	{input: "00", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"},
   380  	{input: "8105", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"},
   381  	{input: "820004", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"},
   382  	{input: "B8020004", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"},
   383  
   384  	// slices
   385  	{input: "C0", ptr: new([]uint), value: []uint{}},
   386  	{input: "C80102030405060708", ptr: new([]uint), value: []uint{1, 2, 3, 4, 5, 6, 7, 8}},
   387  	{input: "F8020004", ptr: new([]uint), error: "rlp: non-canonical size information for []uint"},
   388  
   389  	// arrays
   390  	{input: "C50102030405", ptr: new([5]uint), value: [5]uint{1, 2, 3, 4, 5}},
   391  	{input: "C0", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"},
   392  	{input: "C102", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"},
   393  	{input: "C6010203040506", ptr: new([5]uint), error: "rlp: input list has too many elements for [5]uint"},
   394  	{input: "F8020004", ptr: new([5]uint), error: "rlp: non-canonical size information for [5]uint"},
   395  
   396  	// zero sized arrays
   397  	{input: "C0", ptr: new([0]uint), value: [0]uint{}},
   398  	{input: "C101", ptr: new([0]uint), error: "rlp: input list has too many elements for [0]uint"},
   399  
   400  	// byte slices
   401  	{input: "01", ptr: new([]byte), value: []byte{1}},
   402  	{input: "80", ptr: new([]byte), value: []byte{}},
   403  	{input: "8D6162636465666768696A6B6C6D", ptr: new([]byte), value: []byte("abcdefghijklm")},
   404  	{input: "C0", ptr: new([]byte), error: "rlp: expected input string or byte for []uint8"},
   405  	{input: "8105", ptr: new([]byte), error: "rlp: non-canonical size information for []uint8"},
   406  
   407  	// byte arrays
   408  	{input: "02", ptr: new([1]byte), value: [1]byte{2}},
   409  	{input: "8180", ptr: new([1]byte), value: [1]byte{128}},
   410  	{input: "850102030405", ptr: new([5]byte), value: [5]byte{1, 2, 3, 4, 5}},
   411  
   412  	// byte array errors
   413  	{input: "02", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"},
   414  	{input: "80", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"},
   415  	{input: "820000", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"},
   416  	{input: "C0", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"},
   417  	{input: "C3010203", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"},
   418  	{input: "86010203040506", ptr: new([5]byte), error: "rlp: input string too long for [5]uint8"},
   419  	{input: "8105", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"},
   420  	{input: "817F", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"},
   421  
   422  	// zero sized byte arrays
   423  	{input: "80", ptr: new([0]byte), value: [0]byte{}},
   424  	{input: "01", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"},
   425  	{input: "8101", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"},
   426  
   427  	// strings
   428  	{input: "00", ptr: new(string), value: "\000"},
   429  	{input: "8D6162636465666768696A6B6C6D", ptr: new(string), value: "abcdefghijklm"},
   430  	{input: "C0", ptr: new(string), error: "rlp: expected input string or byte for string"},
   431  
   432  	// big ints
   433  	{input: "01", ptr: new(*big.Int), value: big.NewInt(1)},
   434  	{input: "89FFFFFFFFFFFFFFFFFF", ptr: new(*big.Int), value: veryBigInt},
   435  	{input: "10", ptr: new(big.Int), value: *big.NewInt(16)}, // non-pointer also works
   436  	{input: "C0", ptr: new(*big.Int), error: "rlp: expected input string or byte for *big.Int"},
   437  	{input: "820001", ptr: new(big.Int), error: "rlp: non-canonical integer (leading zero bytes) for *big.Int"},
   438  	{input: "8105", ptr: new(big.Int), error: "rlp: non-canonical size information for *big.Int"},
   439  
   440  	// structs
   441  	{
   442  		input: "C50583343434",
   443  		ptr:   new(simplestruct),
   444  		value: simplestruct{5, "444"},
   445  	},
   446  	{
   447  		input: "C601C402C203C0",
   448  		ptr:   new(recstruct),
   449  		value: recstruct{1, &recstruct{2, &recstruct{3, nil}}},
   450  	},
   451  
   452  	// struct errors
   453  	{
   454  		input: "C0",
   455  		ptr:   new(simplestruct),
   456  		error: "rlp: too few elements for rlp.simplestruct",
   457  	},
   458  	{
   459  		input: "C105",
   460  		ptr:   new(simplestruct),
   461  		error: "rlp: too few elements for rlp.simplestruct",
   462  	},
   463  	{
   464  		input: "C7C50583343434C0",
   465  		ptr:   new([]*simplestruct),
   466  		error: "rlp: too few elements for rlp.simplestruct, decoding into ([]*rlp.simplestruct)[1]",
   467  	},
   468  	{
   469  		input: "83222222",
   470  		ptr:   new(simplestruct),
   471  		error: "rlp: expected input list for rlp.simplestruct",
   472  	},
   473  	{
   474  		input: "C3010101",
   475  		ptr:   new(simplestruct),
   476  		error: "rlp: input list has too many elements for rlp.simplestruct",
   477  	},
   478  	{
   479  		input: "C501C3C00000",
   480  		ptr:   new(recstruct),
   481  		error: "rlp: expected input string or byte for uint, decoding into (rlp.recstruct).Child.I",
   482  	},
   483  	{
   484  		input: "C0",
   485  		ptr:   new(invalidTail1),
   486  		error: "rlp: invalid struct tag \"tail\" for rlp.invalidTail1.A (must be on last field)",
   487  	},
   488  	{
   489  		input: "C0",
   490  		ptr:   new(invalidTail2),
   491  		error: "rlp: invalid struct tag \"tail\" for rlp.invalidTail2.B (field type is not slice)",
   492  	},
   493  	{
   494  		input: "C50102C20102",
   495  		ptr:   new(tailUint),
   496  		error: "rlp: expected input string or byte for uint, decoding into (rlp.tailUint).Tail[1]",
   497  	},
   498  
   499  	// struct tag "tail"
   500  	{
   501  		input: "C3010203",
   502  		ptr:   new(tailRaw),
   503  		value: tailRaw{A: 1, Tail: []RawValue{unhex("02"), unhex("03")}},
   504  	},
   505  	{
   506  		input: "C20102",
   507  		ptr:   new(tailRaw),
   508  		value: tailRaw{A: 1, Tail: []RawValue{unhex("02")}},
   509  	},
   510  	{
   511  		input: "C101",
   512  		ptr:   new(tailRaw),
   513  		value: tailRaw{A: 1, Tail: []RawValue{}},
   514  	},
   515  
   516  	// struct tag "-"
   517  	{
   518  		input: "C20102",
   519  		ptr:   new(hasIgnoredField),
   520  		value: hasIgnoredField{A: 1, C: 2},
   521  	},
   522  
   523  	// RawValue
   524  	{input: "01", ptr: new(RawValue), value: RawValue(unhex("01"))},
   525  	{input: "82FFFF", ptr: new(RawValue), value: RawValue(unhex("82FFFF"))},
   526  	{input: "C20102", ptr: new([]RawValue), value: []RawValue{unhex("01"), unhex("02")}},
   527  
   528  	// pointers
   529  	{input: "00", ptr: new(*[]byte), value: &[]byte{0}},
   530  	{input: "80", ptr: new(*uint), value: uintp(0)},
   531  	{input: "C0", ptr: new(*uint), error: "rlp: expected input string or byte for uint"},
   532  	{input: "07", ptr: new(*uint), value: uintp(7)},
   533  	{input: "817F", ptr: new(*uint), error: "rlp: non-canonical size information for uint"},
   534  	{input: "8180", ptr: new(*uint), value: uintp(0x80)},
   535  	{input: "C109", ptr: new(*[]uint), value: &[]uint{9}},
   536  	{input: "C58403030303", ptr: new(*[][]byte), value: &[][]byte{{3, 3, 3, 3}}},
   537  
   538  	// check that input position is advanced also for empty values.
   539  	{input: "C3808005", ptr: new([]*uint), value: []*uint{uintp(0), uintp(0), uintp(5)}},
   540  
   541  	// interface{}
   542  	{input: "00", ptr: new(interface{}), value: []byte{0}},
   543  	{input: "01", ptr: new(interface{}), value: []byte{1}},
   544  	{input: "80", ptr: new(interface{}), value: []byte{}},
   545  	{input: "850505050505", ptr: new(interface{}), value: []byte{5, 5, 5, 5, 5}},
   546  	{input: "C0", ptr: new(interface{}), value: []interface{}{}},
   547  	{input: "C50183040404", ptr: new(interface{}), value: []interface{}{[]byte{1}, []byte{4, 4, 4}}},
   548  	{
   549  		input: "C3010203",
   550  		ptr:   new([]io.Reader),
   551  		error: "rlp: type io.Reader is not RLP-serializable",
   552  	},
   553  
   554  	// fuzzer crashes
   555  	{
   556  		input: "c330f9c030f93030ce3030303030303030bd303030303030",
   557  		ptr:   new(interface{}),
   558  		error: "rlp: element is larger than containing list",
   559  	},
   560  }
   561  
   562  func uintp(i uint) *uint { return &i }
   563  
   564  func runTests(t *testing.T, decode func([]byte, interface{}) error) {
   565  	for i, test := range decodeTests {
   566  		input, err := hex.DecodeString(test.input)
   567  		if err != nil {
   568  			t.Errorf("test %d: invalid hex input %q", i, test.input)
   569  			continue
   570  		}
   571  		err = decode(input, test.ptr)
   572  		if err != nil && test.error == "" {
   573  			t.Errorf("test %d: unexpected Decode error: %v\ndecoding into %T\ninput %q",
   574  				i, err, test.ptr, test.input)
   575  			continue
   576  		}
   577  		if test.error != "" && fmt.Sprint(err) != test.error {
   578  			t.Errorf("test %d: Decode error mismatch\ngot  %v\nwant %v\ndecoding into %T\ninput %q",
   579  				i, err, test.error, test.ptr, test.input)
   580  			continue
   581  		}
   582  		deref := reflect.ValueOf(test.ptr).Elem().Interface()
   583  		if err == nil && !reflect.DeepEqual(deref, test.value) {
   584  			t.Errorf("test %d: value mismatch\ngot  %#v\nwant %#v\ndecoding into %T\ninput %q",
   585  				i, deref, test.value, test.ptr, test.input)
   586  		}
   587  	}
   588  }
   589  
   590  func TestDecodeWithByteReader(t *testing.T) {
   591  	runTests(t, func(input []byte, into interface{}) error {
   592  		return Decode(bytes.NewReader(input), into)
   593  	})
   594  }
   595  
   596  // plainReader reads from a byte slice but does not
   597  // implement ReadByte. It is also not recognized by the
   598  // size validation. This is useful to test how the decoder
   599  // behaves on a non-buffered input stream.
   600  type plainReader []byte
   601  
   602  func newPlainReader(b []byte) io.Reader {
   603  	return (*plainReader)(&b)
   604  }
   605  
   606  func (r *plainReader) Read(buf []byte) (n int, err error) {
   607  	if len(*r) == 0 {
   608  		return 0, io.EOF
   609  	}
   610  	n = copy(buf, *r)
   611  	*r = (*r)[n:]
   612  	return n, nil
   613  }
   614  
   615  func TestDecodeWithNonByteReader(t *testing.T) {
   616  	runTests(t, func(input []byte, into interface{}) error {
   617  		return Decode(newPlainReader(input), into)
   618  	})
   619  }
   620  
   621  func TestDecodeStreamReset(t *testing.T) {
   622  	s := NewStream(nil, 0)
   623  	runTests(t, func(input []byte, into interface{}) error {
   624  		s.Reset(bytes.NewReader(input), 0)
   625  		return s.Decode(into)
   626  	})
   627  }
   628  
   629  type testDecoder struct{ called bool }
   630  
   631  func (t *testDecoder) DecodeRLP(s *Stream) error {
   632  	if _, err := s.Uint(); err != nil {
   633  		return err
   634  	}
   635  	t.called = true
   636  	return nil
   637  }
   638  
   639  func TestDecodeDecoder(t *testing.T) {
   640  	var s struct {
   641  		T1 testDecoder
   642  		T2 *testDecoder
   643  		T3 **testDecoder
   644  	}
   645  	if err := Decode(bytes.NewReader(unhex("C3010203")), &s); err != nil {
   646  		t.Fatalf("Decode error: %v", err)
   647  	}
   648  
   649  	if !s.T1.called {
   650  		t.Errorf("DecodeRLP was not called for (non-pointer) testDecoder")
   651  	}
   652  
   653  	if s.T2 == nil {
   654  		t.Errorf("*testDecoder has not been allocated")
   655  	} else if !s.T2.called {
   656  		t.Errorf("DecodeRLP was not called for *testDecoder")
   657  	}
   658  
   659  	if s.T3 == nil || *s.T3 == nil {
   660  		t.Errorf("**testDecoder has not been allocated")
   661  	} else if !(*s.T3).called {
   662  		t.Errorf("DecodeRLP was not called for **testDecoder")
   663  	}
   664  }
   665  
   666  type byteDecoder byte
   667  
   668  func (bd *byteDecoder) DecodeRLP(s *Stream) error {
   669  	_, err := s.Uint()
   670  	*bd = 255
   671  	return err
   672  }
   673  
   674  func (bd byteDecoder) called() bool {
   675  	return bd == 255
   676  }
   677  
   678  // This test verifies that the byte slice/byte array logic
   679  // does not kick in for element types implementing Decoder.
   680  func TestDecoderInByteSlice(t *testing.T) {
   681  	var slice []byteDecoder
   682  	if err := Decode(bytes.NewReader(unhex("C101")), &slice); err != nil {
   683  		t.Errorf("unexpected Decode error %v", err)
   684  	} else if !slice[0].called() {
   685  		t.Errorf("DecodeRLP not called for slice element")
   686  	}
   687  
   688  	var array [1]byteDecoder
   689  	if err := Decode(bytes.NewReader(unhex("C101")), &array); err != nil {
   690  		t.Errorf("unexpected Decode error %v", err)
   691  	} else if !array[0].called() {
   692  		t.Errorf("DecodeRLP not called for array element")
   693  	}
   694  }
   695  
   696  func ExampleDecode() {
   697  	input, _ := hex.DecodeString("C90A1486666F6F626172")
   698  
   699  	type example struct {
   700  		A, B    uint
   701  		private uint // private fields are ignored
   702  		String  string
   703  	}
   704  
   705  	var s example
   706  	err := Decode(bytes.NewReader(input), &s)
   707  	if err != nil {
   708  		fmt.Printf("Error: %v\n", err)
   709  	} else {
   710  		fmt.Printf("Decoded value: %#v\n", s)
   711  	}
   712  	// Output:
   713  	// Decoded value: rlp.example{A:0xa, B:0x14, private:0x0, String:"foobar"}
   714  }
   715  
   716  func ExampleDecode_structTagNil() {
   717  	// In this example, we'll use the "nil" struct tag to change
   718  	// how a pointer-typed field is decoded. The input contains an RLP
   719  	// list of one element, an empty string.
   720  	input := []byte{0xC1, 0x80}
   721  
   722  	// This type uses the normal rules.
   723  	// The empty input string is decoded as a pointer to an empty Go string.
   724  	var normalRules struct {
   725  		String *string
   726  	}
   727  	Decode(bytes.NewReader(input), &normalRules)
   728  	fmt.Printf("normal: String = %q\n", *normalRules.String)
   729  
   730  	// This type uses the struct tag.
   731  	// The empty input string is decoded as a nil pointer.
   732  	var withEmptyOK struct {
   733  		String *string `rlp:"nil"`
   734  	}
   735  	Decode(bytes.NewReader(input), &withEmptyOK)
   736  	fmt.Printf("with nil tag: String = %v\n", withEmptyOK.String)
   737  
   738  	// Output:
   739  	// normal: String = ""
   740  	// with nil tag: String = <nil>
   741  }
   742  
   743  func ExampleStream() {
   744  	input, _ := hex.DecodeString("C90A1486666F6F626172")
   745  	s := NewStream(bytes.NewReader(input), 0)
   746  
   747  	// Check what kind of value lies ahead
   748  	kind, size, _ := s.Kind()
   749  	fmt.Printf("Kind: %v size:%d\n", kind, size)
   750  
   751  	// Enter the list
   752  	if _, err := s.List(); err != nil {
   753  		fmt.Printf("List error: %v\n", err)
   754  		return
   755  	}
   756  
   757  	// Decode elements
   758  	fmt.Println(s.Uint())
   759  	fmt.Println(s.Uint())
   760  	fmt.Println(s.Bytes())
   761  
   762  	// Acknowledge end of list
   763  	if err := s.ListEnd(); err != nil {
   764  		fmt.Printf("ListEnd error: %v\n", err)
   765  	}
   766  	// Output:
   767  	// Kind: List size:9
   768  	// 10 <nil>
   769  	// 20 <nil>
   770  	// [102 111 111 98 97 114] <nil>
   771  }
   772  func TestNewStream(t *testing.T) {
   773  
   774  	s := strings.NewReader("ABCDEFG")
   775  	buff := new(bytes.Buffer)
   776  	buff.ReadFrom(s)
   777  	fmt.Println(buff.Bytes())
   778  
   779  	s.Seek(0, 0)
   780  	buff.ReadFrom(s)
   781  	fmt.Println(buff.Bytes())
   782  
   783  }
   784  
   785  func Reset(r io.Reader) []byte {
   786  	var r2 io.Reader
   787  	common.DeepCopy(r2, r)
   788  	buff := new(bytes.Buffer)
   789  	buff.ReadFrom(r)
   790  	r = r2
   791  	io.ReadAtLeast()
   792  	return buff.Bytes()
   793  }
   794  func BenchmarkDecode(b *testing.B) {
   795  	enc := encodeTestSlice(90000)
   796  	b.SetBytes(int64(len(enc)))
   797  	b.ReportAllocs()
   798  	b.ResetTimer()
   799  
   800  	for i := 0; i < b.N; i++ {
   801  		var s []uint
   802  		r := bytes.NewReader(enc)
   803  		if err := Decode(r, &s); err != nil {
   804  			b.Fatalf("Decode error: %v", err)
   805  		}
   806  	}
   807  }
   808  
   809  func BenchmarkDecodeIntSliceReuse(b *testing.B) {
   810  	enc := encodeTestSlice(100000)
   811  	b.SetBytes(int64(len(enc)))
   812  	b.ReportAllocs()
   813  	b.ResetTimer()
   814  
   815  	var s []uint
   816  	for i := 0; i < b.N; i++ {
   817  		r := bytes.NewReader(enc)
   818  		if err := Decode(r, &s); err != nil {
   819  			b.Fatalf("Decode error: %v", err)
   820  		}
   821  	}
   822  }
   823  
   824  func encodeTestSlice(n uint) []byte {
   825  	s := make([]uint, n)
   826  	for i := uint(0); i < n; i++ {
   827  		s[i] = i
   828  	}
   829  	b, err := EncodeToBytes(s)
   830  	if err != nil {
   831  		panic(fmt.Sprintf("encode error: %v", err))
   832  	}
   833  	return b
   834  }
   835  
   836  func unhex(str string) []byte {
   837  	b, err := hex.DecodeString(strings.Replace(str, " ", "", -1))
   838  	if err != nil {
   839  		panic(fmt.Sprintf("invalid hex string: %q", str))
   840  	}
   841  	return b
   842  }