github.com/jeffallen/go-ethereum@v1.1.4-0.20150910155051-571d3236c49c/rlp/decode.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  	"bufio"
    21  	"bytes"
    22  	"encoding/binary"
    23  	"errors"
    24  	"fmt"
    25  	"io"
    26  	"math/big"
    27  	"reflect"
    28  	"strings"
    29  )
    30  
    31  var (
    32  	errNoPointer     = errors.New("rlp: interface given to Decode must be a pointer")
    33  	errDecodeIntoNil = errors.New("rlp: pointer given to Decode must not be nil")
    34  )
    35  
    36  // Decoder is implemented by types that require custom RLP
    37  // decoding rules or need to decode into private fields.
    38  //
    39  // The DecodeRLP method should read one value from the given
    40  // Stream. It is not forbidden to read less or more, but it might
    41  // be confusing.
    42  type Decoder interface {
    43  	DecodeRLP(*Stream) error
    44  }
    45  
    46  // Decode parses RLP-encoded data from r and stores the result in the
    47  // value pointed to by val. Val must be a non-nil pointer. If r does
    48  // not implement ByteReader, Decode will do its own buffering.
    49  //
    50  // Decode uses the following type-dependent decoding rules:
    51  //
    52  // If the type implements the Decoder interface, decode calls
    53  // DecodeRLP.
    54  //
    55  // To decode into a pointer, Decode will decode into the value pointed
    56  // to. If the pointer is nil, a new value of the pointer's element
    57  // type is allocated. If the pointer is non-nil, the existing value
    58  // will reused.
    59  //
    60  // To decode into a struct, Decode expects the input to be an RLP
    61  // list. The decoded elements of the list are assigned to each public
    62  // field in the order given by the struct's definition. The input list
    63  // must contain an element for each decoded field. Decode returns an
    64  // error if there are too few or too many elements.
    65  //
    66  // The decoding of struct fields honours one particular struct tag,
    67  // "nil". This tag applies to pointer-typed fields and changes the
    68  // decoding rules for the field such that input values of size zero
    69  // decode as a nil pointer. This tag can be useful when decoding recursive
    70  // types.
    71  //
    72  //     type StructWithEmptyOK struct {
    73  //         Foo *[20]byte `rlp:"nil"`
    74  //     }
    75  //
    76  // To decode into a slice, the input must be a list and the resulting
    77  // slice will contain the input elements in order. For byte slices,
    78  // the input must be an RLP string. Array types decode similarly, with
    79  // the additional restriction that the number of input elements (or
    80  // bytes) must match the array's length.
    81  //
    82  // To decode into a Go string, the input must be an RLP string. The
    83  // input bytes are taken as-is and will not necessarily be valid UTF-8.
    84  //
    85  // To decode into an unsigned integer type, the input must also be an RLP
    86  // string. The bytes are interpreted as a big endian representation of
    87  // the integer. If the RLP string is larger than the bit size of the
    88  // type, Decode will return an error. Decode also supports *big.Int.
    89  // There is no size limit for big integers.
    90  //
    91  // To decode into an interface value, Decode stores one of these
    92  // in the value:
    93  //
    94  //	  []interface{}, for RLP lists
    95  //	  []byte, for RLP strings
    96  //
    97  // Non-empty interface types are not supported, nor are booleans,
    98  // signed integers, floating point numbers, maps, channels and
    99  // functions.
   100  //
   101  // Note that Decode does not set an input limit for all readers
   102  // and may be vulnerable to panics cause by huge value sizes. If
   103  // you need an input limit, use
   104  //
   105  //     NewStream(r, limit).Decode(val)
   106  func Decode(r io.Reader, val interface{}) error {
   107  	// TODO: this could use a Stream from a pool.
   108  	return NewStream(r, 0).Decode(val)
   109  }
   110  
   111  // DecodeBytes parses RLP data from b into val.
   112  // Please see the documentation of Decode for the decoding rules.
   113  // The input must contain exactly one value and no trailing data.
   114  func DecodeBytes(b []byte, val interface{}) error {
   115  	// TODO: this could use a Stream from a pool.
   116  	r := bytes.NewReader(b)
   117  	if err := NewStream(r, uint64(len(b))).Decode(val); err != nil {
   118  		return err
   119  	}
   120  	if r.Len() > 0 {
   121  		return ErrMoreThanOneValue
   122  	}
   123  	return nil
   124  }
   125  
   126  type decodeError struct {
   127  	msg string
   128  	typ reflect.Type
   129  	ctx []string
   130  }
   131  
   132  func (err *decodeError) Error() string {
   133  	ctx := ""
   134  	if len(err.ctx) > 0 {
   135  		ctx = ", decoding into "
   136  		for i := len(err.ctx) - 1; i >= 0; i-- {
   137  			ctx += err.ctx[i]
   138  		}
   139  	}
   140  	return fmt.Sprintf("rlp: %s for %v%s", err.msg, err.typ, ctx)
   141  }
   142  
   143  func wrapStreamError(err error, typ reflect.Type) error {
   144  	switch err {
   145  	case ErrCanonInt:
   146  		return &decodeError{msg: "non-canonical integer (leading zero bytes)", typ: typ}
   147  	case ErrCanonSize:
   148  		return &decodeError{msg: "non-canonical size information", typ: typ}
   149  	case ErrExpectedList:
   150  		return &decodeError{msg: "expected input list", typ: typ}
   151  	case ErrExpectedString:
   152  		return &decodeError{msg: "expected input string or byte", typ: typ}
   153  	case errUintOverflow:
   154  		return &decodeError{msg: "input string too long", typ: typ}
   155  	case errNotAtEOL:
   156  		return &decodeError{msg: "input list has too many elements", typ: typ}
   157  	}
   158  	return err
   159  }
   160  
   161  func addErrorContext(err error, ctx string) error {
   162  	if decErr, ok := err.(*decodeError); ok {
   163  		decErr.ctx = append(decErr.ctx, ctx)
   164  	}
   165  	return err
   166  }
   167  
   168  var (
   169  	decoderInterface = reflect.TypeOf(new(Decoder)).Elem()
   170  	bigInt           = reflect.TypeOf(big.Int{})
   171  )
   172  
   173  func makeDecoder(typ reflect.Type, tags tags) (dec decoder, err error) {
   174  	kind := typ.Kind()
   175  	switch {
   176  	case typ.Implements(decoderInterface):
   177  		return decodeDecoder, nil
   178  	case kind != reflect.Ptr && reflect.PtrTo(typ).Implements(decoderInterface):
   179  		return decodeDecoderNoPtr, nil
   180  	case typ.AssignableTo(reflect.PtrTo(bigInt)):
   181  		return decodeBigInt, nil
   182  	case typ.AssignableTo(bigInt):
   183  		return decodeBigIntNoPtr, nil
   184  	case isUint(kind):
   185  		return decodeUint, nil
   186  	case kind == reflect.Bool:
   187  		return decodeBool, nil
   188  	case kind == reflect.String:
   189  		return decodeString, nil
   190  	case kind == reflect.Slice || kind == reflect.Array:
   191  		return makeListDecoder(typ)
   192  	case kind == reflect.Struct:
   193  		return makeStructDecoder(typ)
   194  	case kind == reflect.Ptr:
   195  		if tags.nilOK {
   196  			return makeOptionalPtrDecoder(typ)
   197  		}
   198  		return makePtrDecoder(typ)
   199  	case kind == reflect.Interface:
   200  		return decodeInterface, nil
   201  	default:
   202  		return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ)
   203  	}
   204  }
   205  
   206  func decodeUint(s *Stream, val reflect.Value) error {
   207  	typ := val.Type()
   208  	num, err := s.uint(typ.Bits())
   209  	if err != nil {
   210  		return wrapStreamError(err, val.Type())
   211  	}
   212  	val.SetUint(num)
   213  	return nil
   214  }
   215  
   216  func decodeBool(s *Stream, val reflect.Value) error {
   217  	b, err := s.Bool()
   218  	if err != nil {
   219  		return wrapStreamError(err, val.Type())
   220  	}
   221  	val.SetBool(b)
   222  	return nil
   223  }
   224  
   225  func decodeString(s *Stream, val reflect.Value) error {
   226  	b, err := s.Bytes()
   227  	if err != nil {
   228  		return wrapStreamError(err, val.Type())
   229  	}
   230  	val.SetString(string(b))
   231  	return nil
   232  }
   233  
   234  func decodeBigIntNoPtr(s *Stream, val reflect.Value) error {
   235  	return decodeBigInt(s, val.Addr())
   236  }
   237  
   238  func decodeBigInt(s *Stream, val reflect.Value) error {
   239  	b, err := s.Bytes()
   240  	if err != nil {
   241  		return wrapStreamError(err, val.Type())
   242  	}
   243  	i := val.Interface().(*big.Int)
   244  	if i == nil {
   245  		i = new(big.Int)
   246  		val.Set(reflect.ValueOf(i))
   247  	}
   248  	// Reject leading zero bytes
   249  	if len(b) > 0 && b[0] == 0 {
   250  		return wrapStreamError(ErrCanonInt, val.Type())
   251  	}
   252  	i.SetBytes(b)
   253  	return nil
   254  }
   255  
   256  func makeListDecoder(typ reflect.Type) (decoder, error) {
   257  	etype := typ.Elem()
   258  	if etype.Kind() == reflect.Uint8 && !reflect.PtrTo(etype).Implements(decoderInterface) {
   259  		if typ.Kind() == reflect.Array {
   260  			return decodeByteArray, nil
   261  		} else {
   262  			return decodeByteSlice, nil
   263  		}
   264  	}
   265  	etypeinfo, err := cachedTypeInfo1(etype, tags{})
   266  	if err != nil {
   267  		return nil, err
   268  	}
   269  
   270  	isArray := typ.Kind() == reflect.Array
   271  	return func(s *Stream, val reflect.Value) error {
   272  		if isArray {
   273  			return decodeListArray(s, val, etypeinfo.decoder)
   274  		} else {
   275  			return decodeListSlice(s, val, etypeinfo.decoder)
   276  		}
   277  	}, nil
   278  }
   279  
   280  func decodeListSlice(s *Stream, val reflect.Value, elemdec decoder) error {
   281  	size, err := s.List()
   282  	if err != nil {
   283  		return wrapStreamError(err, val.Type())
   284  	}
   285  	if size == 0 {
   286  		val.Set(reflect.MakeSlice(val.Type(), 0, 0))
   287  		return s.ListEnd()
   288  	}
   289  
   290  	i := 0
   291  	for ; ; i++ {
   292  		// grow slice if necessary
   293  		if i >= val.Cap() {
   294  			newcap := val.Cap() + val.Cap()/2
   295  			if newcap < 4 {
   296  				newcap = 4
   297  			}
   298  			newv := reflect.MakeSlice(val.Type(), val.Len(), newcap)
   299  			reflect.Copy(newv, val)
   300  			val.Set(newv)
   301  		}
   302  		if i >= val.Len() {
   303  			val.SetLen(i + 1)
   304  		}
   305  		// decode into element
   306  		if err := elemdec(s, val.Index(i)); err == EOL {
   307  			break
   308  		} else if err != nil {
   309  			return addErrorContext(err, fmt.Sprint("[", i, "]"))
   310  		}
   311  	}
   312  	if i < val.Len() {
   313  		val.SetLen(i)
   314  	}
   315  	return s.ListEnd()
   316  }
   317  
   318  func decodeListArray(s *Stream, val reflect.Value, elemdec decoder) error {
   319  	_, err := s.List()
   320  	if err != nil {
   321  		return wrapStreamError(err, val.Type())
   322  	}
   323  	vlen := val.Len()
   324  	i := 0
   325  	for ; i < vlen; i++ {
   326  		if err := elemdec(s, val.Index(i)); err == EOL {
   327  			break
   328  		} else if err != nil {
   329  			return addErrorContext(err, fmt.Sprint("[", i, "]"))
   330  		}
   331  	}
   332  	if i < vlen {
   333  		return &decodeError{msg: "input list has too few elements", typ: val.Type()}
   334  	}
   335  	return wrapStreamError(s.ListEnd(), val.Type())
   336  }
   337  
   338  func decodeByteSlice(s *Stream, val reflect.Value) error {
   339  	b, err := s.Bytes()
   340  	if err != nil {
   341  		return wrapStreamError(err, val.Type())
   342  	}
   343  	val.SetBytes(b)
   344  	return nil
   345  }
   346  
   347  func decodeByteArray(s *Stream, val reflect.Value) error {
   348  	kind, size, err := s.Kind()
   349  	if err != nil {
   350  		return err
   351  	}
   352  	vlen := val.Len()
   353  	switch kind {
   354  	case Byte:
   355  		if vlen == 0 {
   356  			return &decodeError{msg: "input string too long", typ: val.Type()}
   357  		}
   358  		if vlen > 1 {
   359  			return &decodeError{msg: "input string too short", typ: val.Type()}
   360  		}
   361  		bv, _ := s.Uint()
   362  		val.Index(0).SetUint(bv)
   363  	case String:
   364  		if uint64(vlen) < size {
   365  			return &decodeError{msg: "input string too long", typ: val.Type()}
   366  		}
   367  		if uint64(vlen) > size {
   368  			return &decodeError{msg: "input string too short", typ: val.Type()}
   369  		}
   370  		slice := val.Slice(0, vlen).Interface().([]byte)
   371  		if err := s.readFull(slice); err != nil {
   372  			return err
   373  		}
   374  		// Reject cases where single byte encoding should have been used.
   375  		if size == 1 && slice[0] < 128 {
   376  			return wrapStreamError(ErrCanonSize, val.Type())
   377  		}
   378  	case List:
   379  		return wrapStreamError(ErrExpectedString, val.Type())
   380  	}
   381  	return nil
   382  }
   383  
   384  func makeStructDecoder(typ reflect.Type) (decoder, error) {
   385  	fields, err := structFields(typ)
   386  	if err != nil {
   387  		return nil, err
   388  	}
   389  	dec := func(s *Stream, val reflect.Value) (err error) {
   390  		if _, err = s.List(); err != nil {
   391  			return wrapStreamError(err, typ)
   392  		}
   393  		for _, f := range fields {
   394  			err = f.info.decoder(s, val.Field(f.index))
   395  			if err == EOL {
   396  				return &decodeError{msg: "too few elements", typ: typ}
   397  			} else if err != nil {
   398  				return addErrorContext(err, "."+typ.Field(f.index).Name)
   399  			}
   400  		}
   401  		return wrapStreamError(s.ListEnd(), typ)
   402  	}
   403  	return dec, nil
   404  }
   405  
   406  // makePtrDecoder creates a decoder that decodes into
   407  // the pointer's element type.
   408  func makePtrDecoder(typ reflect.Type) (decoder, error) {
   409  	etype := typ.Elem()
   410  	etypeinfo, err := cachedTypeInfo1(etype, tags{})
   411  	if err != nil {
   412  		return nil, err
   413  	}
   414  	dec := func(s *Stream, val reflect.Value) (err error) {
   415  		newval := val
   416  		if val.IsNil() {
   417  			newval = reflect.New(etype)
   418  		}
   419  		if err = etypeinfo.decoder(s, newval.Elem()); err == nil {
   420  			val.Set(newval)
   421  		}
   422  		return err
   423  	}
   424  	return dec, nil
   425  }
   426  
   427  // makeOptionalPtrDecoder creates a decoder that decodes empty values
   428  // as nil. Non-empty values are decoded into a value of the element type,
   429  // just like makePtrDecoder does.
   430  //
   431  // This decoder is used for pointer-typed struct fields with struct tag "nil".
   432  func makeOptionalPtrDecoder(typ reflect.Type) (decoder, error) {
   433  	etype := typ.Elem()
   434  	etypeinfo, err := cachedTypeInfo1(etype, tags{})
   435  	if err != nil {
   436  		return nil, err
   437  	}
   438  	dec := func(s *Stream, val reflect.Value) (err error) {
   439  		kind, size, err := s.Kind()
   440  		if err != nil || size == 0 && kind != Byte {
   441  			// rearm s.Kind. This is important because the input
   442  			// position must advance to the next value even though
   443  			// we don't read anything.
   444  			s.kind = -1
   445  			// set the pointer to nil.
   446  			val.Set(reflect.Zero(typ))
   447  			return err
   448  		}
   449  		newval := val
   450  		if val.IsNil() {
   451  			newval = reflect.New(etype)
   452  		}
   453  		if err = etypeinfo.decoder(s, newval.Elem()); err == nil {
   454  			val.Set(newval)
   455  		}
   456  		return err
   457  	}
   458  	return dec, nil
   459  }
   460  
   461  var ifsliceType = reflect.TypeOf([]interface{}{})
   462  
   463  func decodeInterface(s *Stream, val reflect.Value) error {
   464  	if val.Type().NumMethod() != 0 {
   465  		return fmt.Errorf("rlp: type %v is not RLP-serializable", val.Type())
   466  	}
   467  	kind, _, err := s.Kind()
   468  	if err != nil {
   469  		return err
   470  	}
   471  	if kind == List {
   472  		slice := reflect.New(ifsliceType).Elem()
   473  		if err := decodeListSlice(s, slice, decodeInterface); err != nil {
   474  			return err
   475  		}
   476  		val.Set(slice)
   477  	} else {
   478  		b, err := s.Bytes()
   479  		if err != nil {
   480  			return err
   481  		}
   482  		val.Set(reflect.ValueOf(b))
   483  	}
   484  	return nil
   485  }
   486  
   487  // This decoder is used for non-pointer values of types
   488  // that implement the Decoder interface using a pointer receiver.
   489  func decodeDecoderNoPtr(s *Stream, val reflect.Value) error {
   490  	return val.Addr().Interface().(Decoder).DecodeRLP(s)
   491  }
   492  
   493  func decodeDecoder(s *Stream, val reflect.Value) error {
   494  	// Decoder instances are not handled using the pointer rule if the type
   495  	// implements Decoder with pointer receiver (i.e. always)
   496  	// because it might handle empty values specially.
   497  	// We need to allocate one here in this case, like makePtrDecoder does.
   498  	if val.Kind() == reflect.Ptr && val.IsNil() {
   499  		val.Set(reflect.New(val.Type().Elem()))
   500  	}
   501  	return val.Interface().(Decoder).DecodeRLP(s)
   502  }
   503  
   504  // Kind represents the kind of value contained in an RLP stream.
   505  type Kind int
   506  
   507  const (
   508  	Byte Kind = iota
   509  	String
   510  	List
   511  )
   512  
   513  func (k Kind) String() string {
   514  	switch k {
   515  	case Byte:
   516  		return "Byte"
   517  	case String:
   518  		return "String"
   519  	case List:
   520  		return "List"
   521  	default:
   522  		return fmt.Sprintf("Unknown(%d)", k)
   523  	}
   524  }
   525  
   526  var (
   527  	// EOL is returned when the end of the current list
   528  	// has been reached during streaming.
   529  	EOL = errors.New("rlp: end of list")
   530  
   531  	// Actual Errors
   532  	ErrExpectedString = errors.New("rlp: expected String or Byte")
   533  	ErrExpectedList   = errors.New("rlp: expected List")
   534  	ErrCanonInt       = errors.New("rlp: non-canonical integer format")
   535  	ErrCanonSize      = errors.New("rlp: non-canonical size information")
   536  	ErrElemTooLarge   = errors.New("rlp: element is larger than containing list")
   537  	ErrValueTooLarge  = errors.New("rlp: value size exceeds available input length")
   538  
   539  	// This error is reported by DecodeBytes if the slice contains
   540  	// additional data after the first RLP value.
   541  	ErrMoreThanOneValue = errors.New("rlp: input contains more than one value")
   542  
   543  	// internal errors
   544  	errNotInList    = errors.New("rlp: call of ListEnd outside of any list")
   545  	errNotAtEOL     = errors.New("rlp: call of ListEnd not positioned at EOL")
   546  	errUintOverflow = errors.New("rlp: uint overflow")
   547  )
   548  
   549  // ByteReader must be implemented by any input reader for a Stream. It
   550  // is implemented by e.g. bufio.Reader and bytes.Reader.
   551  type ByteReader interface {
   552  	io.Reader
   553  	io.ByteReader
   554  }
   555  
   556  // Stream can be used for piecemeal decoding of an input stream. This
   557  // is useful if the input is very large or if the decoding rules for a
   558  // type depend on the input structure. Stream does not keep an
   559  // internal buffer. After decoding a value, the input reader will be
   560  // positioned just before the type information for the next value.
   561  //
   562  // When decoding a list and the input position reaches the declared
   563  // length of the list, all operations will return error EOL.
   564  // The end of the list must be acknowledged using ListEnd to continue
   565  // reading the enclosing list.
   566  //
   567  // Stream is not safe for concurrent use.
   568  type Stream struct {
   569  	r ByteReader
   570  
   571  	// number of bytes remaining to be read from r.
   572  	remaining uint64
   573  	limited   bool
   574  
   575  	// auxiliary buffer for integer decoding
   576  	uintbuf []byte
   577  
   578  	kind    Kind   // kind of value ahead
   579  	size    uint64 // size of value ahead
   580  	byteval byte   // value of single byte in type tag
   581  	kinderr error  // error from last readKind
   582  	stack   []listpos
   583  }
   584  
   585  type listpos struct{ pos, size uint64 }
   586  
   587  // NewStream creates a new decoding stream reading from r.
   588  //
   589  // If r implements the ByteReader interface, Stream will
   590  // not introduce any buffering.
   591  //
   592  // For non-toplevel values, Stream returns ErrElemTooLarge
   593  // for values that do not fit into the enclosing list.
   594  //
   595  // Stream supports an optional input limit. If a limit is set, the
   596  // size of any toplevel value will be checked against the remaining
   597  // input length. Stream operations that encounter a value exceeding
   598  // the remaining input length will return ErrValueTooLarge. The limit
   599  // can be set by passing a non-zero value for inputLimit.
   600  //
   601  // If r is a bytes.Reader or strings.Reader, the input limit is set to
   602  // the length of r's underlying data unless an explicit limit is
   603  // provided.
   604  func NewStream(r io.Reader, inputLimit uint64) *Stream {
   605  	s := new(Stream)
   606  	s.Reset(r, inputLimit)
   607  	return s
   608  }
   609  
   610  // NewListStream creates a new stream that pretends to be positioned
   611  // at an encoded list of the given length.
   612  func NewListStream(r io.Reader, len uint64) *Stream {
   613  	s := new(Stream)
   614  	s.Reset(r, len)
   615  	s.kind = List
   616  	s.size = len
   617  	return s
   618  }
   619  
   620  // Bytes reads an RLP string and returns its contents as a byte slice.
   621  // If the input does not contain an RLP string, the returned
   622  // error will be ErrExpectedString.
   623  func (s *Stream) Bytes() ([]byte, error) {
   624  	kind, size, err := s.Kind()
   625  	if err != nil {
   626  		return nil, err
   627  	}
   628  	switch kind {
   629  	case Byte:
   630  		s.kind = -1 // rearm Kind
   631  		return []byte{s.byteval}, nil
   632  	case String:
   633  		b := make([]byte, size)
   634  		if err = s.readFull(b); err != nil {
   635  			return nil, err
   636  		}
   637  		if size == 1 && b[0] < 128 {
   638  			return nil, ErrCanonSize
   639  		}
   640  		return b, nil
   641  	default:
   642  		return nil, ErrExpectedString
   643  	}
   644  }
   645  
   646  // Raw reads a raw encoded value including RLP type information.
   647  func (s *Stream) Raw() ([]byte, error) {
   648  	kind, size, err := s.Kind()
   649  	if err != nil {
   650  		return nil, err
   651  	}
   652  	if kind == Byte {
   653  		s.kind = -1 // rearm Kind
   654  		return []byte{s.byteval}, nil
   655  	}
   656  	// the original header has already been read and is no longer
   657  	// available. read content and put a new header in front of it.
   658  	start := headsize(size)
   659  	buf := make([]byte, uint64(start)+size)
   660  	if err := s.readFull(buf[start:]); err != nil {
   661  		return nil, err
   662  	}
   663  	if kind == String {
   664  		puthead(buf, 0x80, 0xB8, size)
   665  	} else {
   666  		puthead(buf, 0xC0, 0xF7, size)
   667  	}
   668  	return buf, nil
   669  }
   670  
   671  // Uint reads an RLP string of up to 8 bytes and returns its contents
   672  // as an unsigned integer. If the input does not contain an RLP string, the
   673  // returned error will be ErrExpectedString.
   674  func (s *Stream) Uint() (uint64, error) {
   675  	return s.uint(64)
   676  }
   677  
   678  func (s *Stream) uint(maxbits int) (uint64, error) {
   679  	kind, size, err := s.Kind()
   680  	if err != nil {
   681  		return 0, err
   682  	}
   683  	switch kind {
   684  	case Byte:
   685  		if s.byteval == 0 {
   686  			return 0, ErrCanonInt
   687  		}
   688  		s.kind = -1 // rearm Kind
   689  		return uint64(s.byteval), nil
   690  	case String:
   691  		if size > uint64(maxbits/8) {
   692  			return 0, errUintOverflow
   693  		}
   694  		v, err := s.readUint(byte(size))
   695  		switch {
   696  		case err == ErrCanonSize:
   697  			// Adjust error because we're not reading a size right now.
   698  			return 0, ErrCanonInt
   699  		case err != nil:
   700  			return 0, err
   701  		case size > 0 && v < 128:
   702  			return 0, ErrCanonSize
   703  		default:
   704  			return v, nil
   705  		}
   706  	default:
   707  		return 0, ErrExpectedString
   708  	}
   709  }
   710  
   711  // Bool reads an RLP string of up to 1 byte and returns its contents
   712  // as an boolean. If the input does not contain an RLP string, the
   713  // returned error will be ErrExpectedString.
   714  func (s *Stream) Bool() (bool, error) {
   715  	num, err := s.uint(8)
   716  	if err != nil {
   717  		return false, err
   718  	}
   719  	switch num {
   720  	case 0:
   721  		return false, nil
   722  	case 1:
   723  		return true, nil
   724  	default:
   725  		return false, fmt.Errorf("rlp: invalid boolean value: %d", num)
   726  	}
   727  }
   728  
   729  // List starts decoding an RLP list. If the input does not contain a
   730  // list, the returned error will be ErrExpectedList. When the list's
   731  // end has been reached, any Stream operation will return EOL.
   732  func (s *Stream) List() (size uint64, err error) {
   733  	kind, size, err := s.Kind()
   734  	if err != nil {
   735  		return 0, err
   736  	}
   737  	if kind != List {
   738  		return 0, ErrExpectedList
   739  	}
   740  	s.stack = append(s.stack, listpos{0, size})
   741  	s.kind = -1
   742  	s.size = 0
   743  	return size, nil
   744  }
   745  
   746  // ListEnd returns to the enclosing list.
   747  // The input reader must be positioned at the end of a list.
   748  func (s *Stream) ListEnd() error {
   749  	if len(s.stack) == 0 {
   750  		return errNotInList
   751  	}
   752  	tos := s.stack[len(s.stack)-1]
   753  	if tos.pos != tos.size {
   754  		return errNotAtEOL
   755  	}
   756  	s.stack = s.stack[:len(s.stack)-1] // pop
   757  	if len(s.stack) > 0 {
   758  		s.stack[len(s.stack)-1].pos += tos.size
   759  	}
   760  	s.kind = -1
   761  	s.size = 0
   762  	return nil
   763  }
   764  
   765  // Decode decodes a value and stores the result in the value pointed
   766  // to by val. Please see the documentation for the Decode function
   767  // to learn about the decoding rules.
   768  func (s *Stream) Decode(val interface{}) error {
   769  	if val == nil {
   770  		return errDecodeIntoNil
   771  	}
   772  	rval := reflect.ValueOf(val)
   773  	rtyp := rval.Type()
   774  	if rtyp.Kind() != reflect.Ptr {
   775  		return errNoPointer
   776  	}
   777  	if rval.IsNil() {
   778  		return errDecodeIntoNil
   779  	}
   780  	info, err := cachedTypeInfo(rtyp.Elem(), tags{})
   781  	if err != nil {
   782  		return err
   783  	}
   784  
   785  	err = info.decoder(s, rval.Elem())
   786  	if decErr, ok := err.(*decodeError); ok && len(decErr.ctx) > 0 {
   787  		// add decode target type to error so context has more meaning
   788  		decErr.ctx = append(decErr.ctx, fmt.Sprint("(", rtyp.Elem(), ")"))
   789  	}
   790  	return err
   791  }
   792  
   793  // Reset discards any information about the current decoding context
   794  // and starts reading from r. This method is meant to facilitate reuse
   795  // of a preallocated Stream across many decoding operations.
   796  //
   797  // If r does not also implement ByteReader, Stream will do its own
   798  // buffering.
   799  func (s *Stream) Reset(r io.Reader, inputLimit uint64) {
   800  	if inputLimit > 0 {
   801  		s.remaining = inputLimit
   802  		s.limited = true
   803  	} else {
   804  		// Attempt to automatically discover
   805  		// the limit when reading from a byte slice.
   806  		switch br := r.(type) {
   807  		case *bytes.Reader:
   808  			s.remaining = uint64(br.Len())
   809  			s.limited = true
   810  		case *strings.Reader:
   811  			s.remaining = uint64(br.Len())
   812  			s.limited = true
   813  		default:
   814  			s.limited = false
   815  		}
   816  	}
   817  	// Wrap r with a buffer if it doesn't have one.
   818  	bufr, ok := r.(ByteReader)
   819  	if !ok {
   820  		bufr = bufio.NewReader(r)
   821  	}
   822  	s.r = bufr
   823  	// Reset the decoding context.
   824  	s.stack = s.stack[:0]
   825  	s.size = 0
   826  	s.kind = -1
   827  	s.kinderr = nil
   828  	if s.uintbuf == nil {
   829  		s.uintbuf = make([]byte, 8)
   830  	}
   831  }
   832  
   833  // Kind returns the kind and size of the next value in the
   834  // input stream.
   835  //
   836  // The returned size is the number of bytes that make up the value.
   837  // For kind == Byte, the size is zero because the value is
   838  // contained in the type tag.
   839  //
   840  // The first call to Kind will read size information from the input
   841  // reader and leave it positioned at the start of the actual bytes of
   842  // the value. Subsequent calls to Kind (until the value is decoded)
   843  // will not advance the input reader and return cached information.
   844  func (s *Stream) Kind() (kind Kind, size uint64, err error) {
   845  	var tos *listpos
   846  	if len(s.stack) > 0 {
   847  		tos = &s.stack[len(s.stack)-1]
   848  	}
   849  	if s.kind < 0 {
   850  		s.kinderr = nil
   851  		// Don't read further if we're at the end of the
   852  		// innermost list.
   853  		if tos != nil && tos.pos == tos.size {
   854  			return 0, 0, EOL
   855  		}
   856  		s.kind, s.size, s.kinderr = s.readKind()
   857  		if s.kinderr == nil {
   858  			if tos == nil {
   859  				// At toplevel, check that the value is smaller
   860  				// than the remaining input length.
   861  				if s.limited && s.size > s.remaining {
   862  					s.kinderr = ErrValueTooLarge
   863  				}
   864  			} else {
   865  				// Inside a list, check that the value doesn't overflow the list.
   866  				if s.size > tos.size-tos.pos {
   867  					s.kinderr = ErrElemTooLarge
   868  				}
   869  			}
   870  		}
   871  	}
   872  	// Note: this might return a sticky error generated
   873  	// by an earlier call to readKind.
   874  	return s.kind, s.size, s.kinderr
   875  }
   876  
   877  func (s *Stream) readKind() (kind Kind, size uint64, err error) {
   878  	b, err := s.readByte()
   879  	if err != nil {
   880  		if len(s.stack) == 0 {
   881  			// At toplevel, Adjust the error to actual EOF. io.EOF is
   882  			// used by callers to determine when to stop decoding.
   883  			switch err {
   884  			case io.ErrUnexpectedEOF:
   885  				err = io.EOF
   886  			case ErrValueTooLarge:
   887  				err = io.EOF
   888  			}
   889  		}
   890  		return 0, 0, err
   891  	}
   892  	s.byteval = 0
   893  	switch {
   894  	case b < 0x80:
   895  		// For a single byte whose value is in the [0x00, 0x7F] range, that byte
   896  		// is its own RLP encoding.
   897  		s.byteval = b
   898  		return Byte, 0, nil
   899  	case b < 0xB8:
   900  		// Otherwise, if a string is 0-55 bytes long,
   901  		// the RLP encoding consists of a single byte with value 0x80 plus the
   902  		// length of the string followed by the string. The range of the first
   903  		// byte is thus [0x80, 0xB7].
   904  		return String, uint64(b - 0x80), nil
   905  	case b < 0xC0:
   906  		// If a string is more than 55 bytes long, the
   907  		// RLP encoding consists of a single byte with value 0xB7 plus the length
   908  		// of the length of the string in binary form, followed by the length of
   909  		// the string, followed by the string. For example, a length-1024 string
   910  		// would be encoded as 0xB90400 followed by the string. The range of
   911  		// the first byte is thus [0xB8, 0xBF].
   912  		size, err = s.readUint(b - 0xB7)
   913  		if err == nil && size < 56 {
   914  			err = ErrCanonSize
   915  		}
   916  		return String, size, err
   917  	case b < 0xF8:
   918  		// If the total payload of a list
   919  		// (i.e. the combined length of all its items) is 0-55 bytes long, the
   920  		// RLP encoding consists of a single byte with value 0xC0 plus the length
   921  		// of the list followed by the concatenation of the RLP encodings of the
   922  		// items. The range of the first byte is thus [0xC0, 0xF7].
   923  		return List, uint64(b - 0xC0), nil
   924  	default:
   925  		// If the total payload of a list is more than 55 bytes long,
   926  		// the RLP encoding consists of a single byte with value 0xF7
   927  		// plus the length of the length of the payload in binary
   928  		// form, followed by the length of the payload, followed by
   929  		// the concatenation of the RLP encodings of the items. The
   930  		// range of the first byte is thus [0xF8, 0xFF].
   931  		size, err = s.readUint(b - 0xF7)
   932  		if err == nil && size < 56 {
   933  			err = ErrCanonSize
   934  		}
   935  		return List, size, err
   936  	}
   937  }
   938  
   939  func (s *Stream) readUint(size byte) (uint64, error) {
   940  	switch size {
   941  	case 0:
   942  		s.kind = -1 // rearm Kind
   943  		return 0, nil
   944  	case 1:
   945  		b, err := s.readByte()
   946  		return uint64(b), err
   947  	default:
   948  		start := int(8 - size)
   949  		for i := 0; i < start; i++ {
   950  			s.uintbuf[i] = 0
   951  		}
   952  		if err := s.readFull(s.uintbuf[start:]); err != nil {
   953  			return 0, err
   954  		}
   955  		if s.uintbuf[start] == 0 {
   956  			// Note: readUint is also used to decode integer
   957  			// values. The error needs to be adjusted to become
   958  			// ErrCanonInt in this case.
   959  			return 0, ErrCanonSize
   960  		}
   961  		return binary.BigEndian.Uint64(s.uintbuf), nil
   962  	}
   963  }
   964  
   965  func (s *Stream) readFull(buf []byte) (err error) {
   966  	if err := s.willRead(uint64(len(buf))); err != nil {
   967  		return err
   968  	}
   969  	var nn, n int
   970  	for n < len(buf) && err == nil {
   971  		nn, err = s.r.Read(buf[n:])
   972  		n += nn
   973  	}
   974  	if err == io.EOF {
   975  		err = io.ErrUnexpectedEOF
   976  	}
   977  	return err
   978  }
   979  
   980  func (s *Stream) readByte() (byte, error) {
   981  	if err := s.willRead(1); err != nil {
   982  		return 0, err
   983  	}
   984  	b, err := s.r.ReadByte()
   985  	if err == io.EOF {
   986  		err = io.ErrUnexpectedEOF
   987  	}
   988  	return b, err
   989  }
   990  
   991  func (s *Stream) willRead(n uint64) error {
   992  	s.kind = -1 // rearm Kind
   993  
   994  	if len(s.stack) > 0 {
   995  		// check list overflow
   996  		tos := s.stack[len(s.stack)-1]
   997  		if n > tos.size-tos.pos {
   998  			return ErrElemTooLarge
   999  		}
  1000  		s.stack[len(s.stack)-1].pos += n
  1001  	}
  1002  	if s.limited {
  1003  		if n > s.remaining {
  1004  			return ErrValueTooLarge
  1005  		}
  1006  		s.remaining -= n
  1007  	}
  1008  	return nil
  1009  }