decode.go 26.1 KB
Newer Older
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 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
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 13 14
// GNU Lesser General Public License for more details.
//
// 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 18 19
package rlp

import (
20
	"bufio"
Felix Lange's avatar
Felix Lange committed
21
	"bytes"
22 23 24 25 26 27
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"math/big"
	"reflect"
28
	"strings"
29
	"sync"
30 31
)

32 33 34 35 36
//lint:ignore ST1012 EOL is not an error.

// EOL is returned when the end of the current list
// has been reached during streaming.
var EOL = errors.New("rlp: end of list")
37

38
var (
39 40 41 42 43 44 45 46 47 48 49 50
	ErrExpectedString   = errors.New("rlp: expected String or Byte")
	ErrExpectedList     = errors.New("rlp: expected List")
	ErrCanonInt         = errors.New("rlp: non-canonical integer format")
	ErrCanonSize        = errors.New("rlp: non-canonical size information")
	ErrElemTooLarge     = errors.New("rlp: element is larger than containing list")
	ErrValueTooLarge    = errors.New("rlp: value size exceeds available input length")
	ErrMoreThanOneValue = errors.New("rlp: input contains more than one value")

	// internal errors
	errNotInList     = errors.New("rlp: call of ListEnd outside of any list")
	errNotAtEOL      = errors.New("rlp: call of ListEnd not positioned at EOL")
	errUintOverflow  = errors.New("rlp: uint overflow")
51 52
	errNoPointer     = errors.New("rlp: interface given to Decode must be a pointer")
	errDecodeIntoNil = errors.New("rlp: pointer given to Decode must not be nil")
53 54 55 56

	streamPool = sync.Pool{
		New: func() interface{} { return new(Stream) },
	}
57 58
)

59 60
// Decoder is implemented by types that require custom RLP decoding rules or need to decode
// into private fields.
61
//
62 63
// The DecodeRLP method should read one value from the given Stream. It is not forbidden to
// read less or more, but it might be confusing.
64 65 66 67
type Decoder interface {
	DecodeRLP(*Stream) error
}

68 69 70
// Decode parses RLP-encoded data from r and stores the result in the value pointed to by
// val. Please see package-level documentation for the decoding rules. Val must be a
// non-nil pointer.
71
//
72
// If r does not implement ByteReader, Decode will do its own buffering.
73
//
74 75
// Note that Decode does not set an input limit for all readers and may be vulnerable to
// panics cause by huge value sizes. If you need an input limit, use
76 77
//
//     NewStream(r, limit).Decode(val)
78
func Decode(r io.Reader, val interface{}) error {
79 80 81 82 83
	stream := streamPool.Get().(*Stream)
	defer streamPool.Put(stream)

	stream.Reset(r, 0)
	return stream.Decode(val)
84 85
}

86 87
// DecodeBytes parses RLP data from b into val. Please see package-level documentation for
// the decoding rules. The input must contain exactly one value and no trailing data.
Felix Lange's avatar
Felix Lange committed
88
func DecodeBytes(b []byte, val interface{}) error {
89
	r := bytes.NewReader(b)
90 91 92 93 94 95

	stream := streamPool.Get().(*Stream)
	defer streamPool.Put(stream)

	stream.Reset(r, uint64(len(b)))
	if err := stream.Decode(val); err != nil {
96 97 98 99 100 101
		return err
	}
	if r.Len() > 0 {
		return ErrMoreThanOneValue
	}
	return nil
Felix Lange's avatar
Felix Lange committed
102 103
}

104 105 106
type decodeError struct {
	msg string
	typ reflect.Type
obscuren's avatar
obscuren committed
107
	ctx []string
108 109
}

obscuren's avatar
obscuren committed
110 111 112 113 114 115 116 117 118
func (err *decodeError) Error() string {
	ctx := ""
	if len(err.ctx) > 0 {
		ctx = ", decoding into "
		for i := len(err.ctx) - 1; i >= 0; i-- {
			ctx += err.ctx[i]
		}
	}
	return fmt.Sprintf("rlp: %s for %v%s", err.msg, err.typ, ctx)
119 120
}

121 122
func wrapStreamError(err error, typ reflect.Type) error {
	switch err {
123
	case ErrCanonInt:
124 125 126
		return &decodeError{msg: "non-canonical integer (leading zero bytes)", typ: typ}
	case ErrCanonSize:
		return &decodeError{msg: "non-canonical size information", typ: typ}
127
	case ErrExpectedList:
obscuren's avatar
obscuren committed
128
		return &decodeError{msg: "expected input list", typ: typ}
129
	case ErrExpectedString:
obscuren's avatar
obscuren committed
130
		return &decodeError{msg: "expected input string or byte", typ: typ}
131
	case errUintOverflow:
obscuren's avatar
obscuren committed
132
		return &decodeError{msg: "input string too long", typ: typ}
133
	case errNotAtEOL:
obscuren's avatar
obscuren committed
134 135 136 137 138 139 140 141
		return &decodeError{msg: "input list has too many elements", typ: typ}
	}
	return err
}

func addErrorContext(err error, ctx string) error {
	if decErr, ok := err.(*decodeError); ok {
		decErr.ctx = append(decErr.ctx, ctx)
142 143 144 145
	}
	return err
}

146 147 148 149 150
var (
	decoderInterface = reflect.TypeOf(new(Decoder)).Elem()
	bigInt           = reflect.TypeOf(big.Int{})
)

151
func makeDecoder(typ reflect.Type, tags tags) (dec decoder, err error) {
152 153
	kind := typ.Kind()
	switch {
Felix Lange's avatar
Felix Lange committed
154 155
	case typ == rawValueType:
		return decodeRawValue, nil
156 157 158 159
	case typ.AssignableTo(reflect.PtrTo(bigInt)):
		return decodeBigInt, nil
	case typ.AssignableTo(bigInt):
		return decodeBigIntNoPtr, nil
160 161 162 163
	case kind == reflect.Ptr:
		return makePtrDecoder(typ, tags)
	case reflect.PtrTo(typ).Implements(decoderInterface):
		return decodeDecoder, nil
164 165
	case isUint(kind):
		return decodeUint, nil
166 167
	case kind == reflect.Bool:
		return decodeBool, nil
168 169 170
	case kind == reflect.String:
		return decodeString, nil
	case kind == reflect.Slice || kind == reflect.Array:
171
		return makeListDecoder(typ, tags)
172 173
	case kind == reflect.Struct:
		return makeStructDecoder(typ)
174
	case kind == reflect.Interface:
175 176 177 178 179 180
		return decodeInterface, nil
	default:
		return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ)
	}
}

Felix Lange's avatar
Felix Lange committed
181 182 183 184 185 186 187 188 189
func decodeRawValue(s *Stream, val reflect.Value) error {
	r, err := s.Raw()
	if err != nil {
		return err
	}
	val.SetBytes(r)
	return nil
}

190
func decodeUint(s *Stream, val reflect.Value) error {
191 192
	typ := val.Type()
	num, err := s.uint(typ.Bits())
193 194
	if err != nil {
		return wrapStreamError(err, val.Type())
195 196 197 198 199
	}
	val.SetUint(num)
	return nil
}

200 201 202 203 204 205 206 207 208
func decodeBool(s *Stream, val reflect.Value) error {
	b, err := s.Bool()
	if err != nil {
		return wrapStreamError(err, val.Type())
	}
	val.SetBool(b)
	return nil
}

209 210 211
func decodeString(s *Stream, val reflect.Value) error {
	b, err := s.Bytes()
	if err != nil {
212
		return wrapStreamError(err, val.Type())
213 214 215 216 217 218 219 220 221 222 223 224
	}
	val.SetString(string(b))
	return nil
}

func decodeBigIntNoPtr(s *Stream, val reflect.Value) error {
	return decodeBigInt(s, val.Addr())
}

func decodeBigInt(s *Stream, val reflect.Value) error {
	b, err := s.Bytes()
	if err != nil {
225
		return wrapStreamError(err, val.Type())
226 227 228 229 230 231
	}
	i := val.Interface().(*big.Int)
	if i == nil {
		i = new(big.Int)
		val.Set(reflect.ValueOf(i))
	}
232
	// Reject leading zero bytes
233 234 235
	if len(b) > 0 && b[0] == 0 {
		return wrapStreamError(ErrCanonInt, val.Type())
	}
236 237 238 239
	i.SetBytes(b)
	return nil
}

240
func makeListDecoder(typ reflect.Type, tag tags) (decoder, error) {
241 242 243 244 245
	etype := typ.Elem()
	if etype.Kind() == reflect.Uint8 && !reflect.PtrTo(etype).Implements(decoderInterface) {
		if typ.Kind() == reflect.Array {
			return decodeByteArray, nil
		}
246
		return decodeByteSlice, nil
247
	}
248 249 250
	etypeinfo := cachedTypeInfo1(etype, tags{})
	if etypeinfo.decoderErr != nil {
		return nil, etypeinfo.decoderErr
251
	}
252 253 254 255
	var dec decoder
	switch {
	case typ.Kind() == reflect.Array:
		dec = func(s *Stream, val reflect.Value) error {
obscuren's avatar
obscuren committed
256
			return decodeListArray(s, val, etypeinfo.decoder)
257 258 259
		}
	case tag.tail:
		// A slice with "tail" tag can occur as the last field
260
		// of a struct and is supposed to swallow all remaining
261 262 263 264 265 266 267
		// list elements. The struct decoder already called s.List,
		// proceed directly to decoding the elements.
		dec = func(s *Stream, val reflect.Value) error {
			return decodeSliceElems(s, val, etypeinfo.decoder)
		}
	default:
		dec = func(s *Stream, val reflect.Value) error {
obscuren's avatar
obscuren committed
268 269
			return decodeListSlice(s, val, etypeinfo.decoder)
		}
270 271
	}
	return dec, nil
272 273
}

274
func decodeListSlice(s *Stream, val reflect.Value, elemdec decoder) error {
275 276
	size, err := s.List()
	if err != nil {
277
		return wrapStreamError(err, val.Type())
278 279
	}
	if size == 0 {
280
		val.Set(reflect.MakeSlice(val.Type(), 0, 0))
281 282
		return s.ListEnd()
	}
283 284 285 286 287
	if err := decodeSliceElems(s, val, elemdec); err != nil {
		return err
	}
	return s.ListEnd()
}
288

289
func decodeSliceElems(s *Stream, val reflect.Value, elemdec decoder) error {
290
	i := 0
291 292 293 294 295 296
	for ; ; i++ {
		// grow slice if necessary
		if i >= val.Cap() {
			newcap := val.Cap() + val.Cap()/2
			if newcap < 4 {
				newcap = 4
297
			}
298 299 300 301 302 303
			newv := reflect.MakeSlice(val.Type(), val.Len(), newcap)
			reflect.Copy(newv, val)
			val.Set(newv)
		}
		if i >= val.Len() {
			val.SetLen(i + 1)
304 305 306 307 308
		}
		// decode into element
		if err := elemdec(s, val.Index(i)); err == EOL {
			break
		} else if err != nil {
obscuren's avatar
obscuren committed
309
			return addErrorContext(err, fmt.Sprint("[", i, "]"))
310 311 312
		}
	}
	if i < val.Len() {
313
		val.SetLen(i)
314
	}
315
	return nil
316 317
}

318
func decodeListArray(s *Stream, val reflect.Value, elemdec decoder) error {
319
	if _, err := s.List(); err != nil {
320
		return wrapStreamError(err, val.Type())
321 322 323 324 325 326 327
	}
	vlen := val.Len()
	i := 0
	for ; i < vlen; i++ {
		if err := elemdec(s, val.Index(i)); err == EOL {
			break
		} else if err != nil {
obscuren's avatar
obscuren committed
328
			return addErrorContext(err, fmt.Sprint("[", i, "]"))
329 330 331
		}
	}
	if i < vlen {
332
		return &decodeError{msg: "input list has too few elements", typ: val.Type()}
333
	}
334
	return wrapStreamError(s.ListEnd(), val.Type())
335 336
}

337 338
func decodeByteSlice(s *Stream, val reflect.Value) error {
	b, err := s.Bytes()
339 340
	if err != nil {
		return wrapStreamError(err, val.Type())
341
	}
342 343
	val.SetBytes(b)
	return nil
344 345 346 347 348 349 350
}

func decodeByteArray(s *Stream, val reflect.Value) error {
	kind, size, err := s.Kind()
	if err != nil {
		return err
	}
351
	vlen := val.Len()
352 353
	switch kind {
	case Byte:
354
		if vlen == 0 {
obscuren's avatar
obscuren committed
355
			return &decodeError{msg: "input string too long", typ: val.Type()}
356
		}
357 358 359
		if vlen > 1 {
			return &decodeError{msg: "input string too short", typ: val.Type()}
		}
360 361 362
		bv, _ := s.Uint()
		val.Index(0).SetUint(bv)
	case String:
363
		if uint64(vlen) < size {
obscuren's avatar
obscuren committed
364
			return &decodeError{msg: "input string too long", typ: val.Type()}
365
		}
366 367 368 369
		if uint64(vlen) > size {
			return &decodeError{msg: "input string too short", typ: val.Type()}
		}
		slice := val.Slice(0, vlen).Interface().([]byte)
370 371 372
		if err := s.readFull(slice); err != nil {
			return err
		}
373
		// Reject cases where single byte encoding should have been used.
374
		if size == 1 && slice[0] < 128 {
375 376
			return wrapStreamError(ErrCanonSize, val.Type())
		}
377
	case List:
378
		return wrapStreamError(ErrExpectedString, val.Type())
379 380 381 382 383
	}
	return nil
}

func makeStructDecoder(typ reflect.Type) (decoder, error) {
384 385 386
	fields, err := structFields(typ)
	if err != nil {
		return nil, err
387
	}
388 389 390 391 392
	for _, f := range fields {
		if f.info.decoderErr != nil {
			return nil, structFieldError{typ, f.index, f.info.decoderErr}
		}
	}
393
	dec := func(s *Stream, val reflect.Value) (err error) {
394
		if _, err := s.List(); err != nil {
395
			return wrapStreamError(err, typ)
396 397
		}
		for _, f := range fields {
398
			err := f.info.decoder(s, val.Field(f.index))
399
			if err == EOL {
400
				return &decodeError{msg: "too few elements", typ: typ}
401
			} else if err != nil {
obscuren's avatar
obscuren committed
402
				return addErrorContext(err, "."+typ.Field(f.index).Name)
403 404
			}
		}
405
		return wrapStreamError(s.ListEnd(), typ)
406 407 408 409
	}
	return dec, nil
}

410 411
// makePtrDecoder creates a decoder that decodes into the pointer's element type.
func makePtrDecoder(typ reflect.Type, tag tags) (decoder, error) {
412
	etype := typ.Elem()
413
	etypeinfo := cachedTypeInfo1(etype, tags{})
414 415
	switch {
	case etypeinfo.decoderErr != nil:
416
		return nil, etypeinfo.decoderErr
417 418 419 420
	case !tag.nilOK:
		return makeSimplePtrDecoder(etype, etypeinfo), nil
	default:
		return makeNilPtrDecoder(etype, etypeinfo, tag.nilKind), nil
421
	}
422 423 424 425
}

func makeSimplePtrDecoder(etype reflect.Type, etypeinfo *typeinfo) decoder {
	return func(s *Stream, val reflect.Value) (err error) {
426 427 428 429 430 431 432 433 434 435 436
		newval := val
		if val.IsNil() {
			newval = reflect.New(etype)
		}
		if err = etypeinfo.decoder(s, newval.Elem()); err == nil {
			val.Set(newval)
		}
		return err
	}
}

437 438
// makeNilPtrDecoder creates a decoder that decodes empty values as nil. Non-empty
// values are decoded into a value of the element type, just like makePtrDecoder does.
439 440
//
// This decoder is used for pointer-typed struct fields with struct tag "nil".
441 442 443 444
func makeNilPtrDecoder(etype reflect.Type, etypeinfo *typeinfo, nilKind Kind) decoder {
	typ := reflect.PtrTo(etype)
	nilPtr := reflect.Zero(typ)
	return func(s *Stream, val reflect.Value) (err error) {
445
		kind, size, err := s.Kind()
446 447 448 449 450 451 452 453 454 455 456 457
		if err != nil {
			val.Set(nilPtr)
			return wrapStreamError(err, typ)
		}
		// Handle empty values as a nil pointer.
		if kind != Byte && size == 0 {
			if kind != nilKind {
				return &decodeError{
					msg: fmt.Sprintf("wrong kind of empty value (got %v, want %v)", kind, nilKind),
					typ: typ,
				}
			}
458 459 460 461
			// rearm s.Kind. This is important because the input
			// position must advance to the next value even though
			// we don't read anything.
			s.kind = -1
462 463
			val.Set(nilPtr)
			return nil
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
		}
		newval := val
		if val.IsNil() {
			newval = reflect.New(etype)
		}
		if err = etypeinfo.decoder(s, newval.Elem()); err == nil {
			val.Set(newval)
		}
		return err
	}
}

var ifsliceType = reflect.TypeOf([]interface{}{})

func decodeInterface(s *Stream, val reflect.Value) error {
479 480 481
	if val.Type().NumMethod() != 0 {
		return fmt.Errorf("rlp: type %v is not RLP-serializable", val.Type())
	}
482 483 484 485 486 487
	kind, _, err := s.Kind()
	if err != nil {
		return err
	}
	if kind == List {
		slice := reflect.New(ifsliceType).Elem()
488
		if err := decodeListSlice(s, slice, decodeInterface); err != nil {
489 490 491 492 493 494 495 496 497 498 499 500 501 502
			return err
		}
		val.Set(slice)
	} else {
		b, err := s.Bytes()
		if err != nil {
			return err
		}
		val.Set(reflect.ValueOf(b))
	}
	return nil
}

func decodeDecoder(s *Stream, val reflect.Value) error {
503
	return val.Addr().Interface().(Decoder).DecodeRLP(s)
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
}

// Kind represents the kind of value contained in an RLP stream.
type Kind int

const (
	Byte Kind = iota
	String
	List
)

func (k Kind) String() string {
	switch k {
	case Byte:
		return "Byte"
	case String:
		return "String"
	case List:
		return "List"
	default:
		return fmt.Sprintf("Unknown(%d)", k)
	}
}

// ByteReader must be implemented by any input reader for a Stream. It
// is implemented by e.g. bufio.Reader and bytes.Reader.
type ByteReader interface {
	io.Reader
	io.ByteReader
}

// Stream can be used for piecemeal decoding of an input stream. This
// is useful if the input is very large or if the decoding rules for a
// type depend on the input structure. Stream does not keep an
// internal buffer. After decoding a value, the input reader will be
// positioned just before the type information for the next value.
//
// When decoding a list and the input position reaches the declared
// length of the list, all operations will return error EOL.
// The end of the list must be acknowledged using ListEnd to continue
// reading the enclosing list.
//
// Stream is not safe for concurrent use.
type Stream struct {
548 549 550 551 552 553 554
	r ByteReader

	// number of bytes remaining to be read from r.
	remaining uint64
	limited   bool

	// auxiliary buffer for integer decoding
555 556 557 558 559
	uintbuf []byte

	kind    Kind   // kind of value ahead
	size    uint64 // size of value ahead
	byteval byte   // value of single byte in type tag
560
	kinderr error  // error from last readKind
561 562 563 564 565
	stack   []listpos
}

type listpos struct{ pos, size uint64 }

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
// NewStream creates a new decoding stream reading from r.
//
// If r implements the ByteReader interface, Stream will
// not introduce any buffering.
//
// For non-toplevel values, Stream returns ErrElemTooLarge
// for values that do not fit into the enclosing list.
//
// Stream supports an optional input limit. If a limit is set, the
// size of any toplevel value will be checked against the remaining
// input length. Stream operations that encounter a value exceeding
// the remaining input length will return ErrValueTooLarge. The limit
// can be set by passing a non-zero value for inputLimit.
//
// If r is a bytes.Reader or strings.Reader, the input limit is set to
// the length of r's underlying data unless an explicit limit is
// provided.
func NewStream(r io.Reader, inputLimit uint64) *Stream {
584
	s := new(Stream)
585
	s.Reset(r, inputLimit)
586 587
	return s
}
588 589 590 591 592

// NewListStream creates a new stream that pretends to be positioned
// at an encoded list of the given length.
func NewListStream(r io.Reader, len uint64) *Stream {
	s := new(Stream)
593
	s.Reset(r, len)
594 595 596
	s.kind = List
	s.size = len
	return s
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
}

// Bytes reads an RLP string and returns its contents as a byte slice.
// If the input does not contain an RLP string, the returned
// error will be ErrExpectedString.
func (s *Stream) Bytes() ([]byte, error) {
	kind, size, err := s.Kind()
	if err != nil {
		return nil, err
	}
	switch kind {
	case Byte:
		s.kind = -1 // rearm Kind
		return []byte{s.byteval}, nil
	case String:
		b := make([]byte, size)
		if err = s.readFull(b); err != nil {
			return nil, err
		}
616
		if size == 1 && b[0] < 128 {
617 618
			return nil, ErrCanonSize
		}
619 620 621 622 623 624
		return b, nil
	default:
		return nil, ErrExpectedString
	}
}

Felix Lange's avatar
Felix Lange committed
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
// Raw reads a raw encoded value including RLP type information.
func (s *Stream) Raw() ([]byte, error) {
	kind, size, err := s.Kind()
	if err != nil {
		return nil, err
	}
	if kind == Byte {
		s.kind = -1 // rearm Kind
		return []byte{s.byteval}, nil
	}
	// the original header has already been read and is no longer
	// available. read content and put a new header in front of it.
	start := headsize(size)
	buf := make([]byte, uint64(start)+size)
	if err := s.readFull(buf[start:]); err != nil {
		return nil, err
	}
	if kind == String {
643
		puthead(buf, 0x80, 0xB7, size)
Felix Lange's avatar
Felix Lange committed
644 645 646 647 648 649
	} else {
		puthead(buf, 0xC0, 0xF7, size)
	}
	return buf, nil
}

650 651 652 653 654 655 656 657 658 659 660 661 662 663
// Uint reads an RLP string of up to 8 bytes and returns its contents
// as an unsigned integer. If the input does not contain an RLP string, the
// returned error will be ErrExpectedString.
func (s *Stream) Uint() (uint64, error) {
	return s.uint(64)
}

func (s *Stream) uint(maxbits int) (uint64, error) {
	kind, size, err := s.Kind()
	if err != nil {
		return 0, err
	}
	switch kind {
	case Byte:
664 665 666
		if s.byteval == 0 {
			return 0, ErrCanonInt
		}
667 668 669 670
		s.kind = -1 // rearm Kind
		return uint64(s.byteval), nil
	case String:
		if size > uint64(maxbits/8) {
671
			return 0, errUintOverflow
672
		}
673
		v, err := s.readUint(byte(size))
674 675
		switch {
		case err == ErrCanonSize:
676
			// Adjust error because we're not reading a size right now.
677 678 679
			return 0, ErrCanonInt
		case err != nil:
			return 0, err
680
		case size > 0 && v < 128:
681 682 683
			return 0, ErrCanonSize
		default:
			return v, nil
684
		}
685 686 687 688 689
	default:
		return 0, ErrExpectedString
	}
}

690
// Bool reads an RLP string of up to 1 byte and returns its contents
691
// as a boolean. If the input does not contain an RLP string, the
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
// returned error will be ErrExpectedString.
func (s *Stream) Bool() (bool, error) {
	num, err := s.uint(8)
	if err != nil {
		return false, err
	}
	switch num {
	case 0:
		return false, nil
	case 1:
		return true, nil
	default:
		return false, fmt.Errorf("rlp: invalid boolean value: %d", num)
	}
}

708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
// List starts decoding an RLP list. If the input does not contain a
// list, the returned error will be ErrExpectedList. When the list's
// end has been reached, any Stream operation will return EOL.
func (s *Stream) List() (size uint64, err error) {
	kind, size, err := s.Kind()
	if err != nil {
		return 0, err
	}
	if kind != List {
		return 0, ErrExpectedList
	}
	s.stack = append(s.stack, listpos{0, size})
	s.kind = -1
	s.size = 0
	return size, nil
}

// ListEnd returns to the enclosing list.
// The input reader must be positioned at the end of a list.
func (s *Stream) ListEnd() error {
	if len(s.stack) == 0 {
		return errNotInList
	}
	tos := s.stack[len(s.stack)-1]
	if tos.pos != tos.size {
		return errNotAtEOL
	}
	s.stack = s.stack[:len(s.stack)-1] // pop
	if len(s.stack) > 0 {
		s.stack[len(s.stack)-1].pos += tos.size
	}
	s.kind = -1
	s.size = 0
	return nil
}

// Decode decodes a value and stores the result in the value pointed
// to by val. Please see the documentation for the Decode function
// to learn about the decoding rules.
func (s *Stream) Decode(val interface{}) error {
	if val == nil {
		return errDecodeIntoNil
	}
	rval := reflect.ValueOf(val)
	rtyp := rval.Type()
	if rtyp.Kind() != reflect.Ptr {
		return errNoPointer
	}
	if rval.IsNil() {
		return errDecodeIntoNil
	}
759
	decoder, err := cachedDecoder(rtyp.Elem())
760 761 762
	if err != nil {
		return err
	}
obscuren's avatar
obscuren committed
763

764
	err = decoder(s, rval.Elem())
obscuren's avatar
obscuren committed
765 766 767 768 769
	if decErr, ok := err.(*decodeError); ok && len(decErr.ctx) > 0 {
		// add decode target type to error so context has more meaning
		decErr.ctx = append(decErr.ctx, fmt.Sprint("(", rtyp.Elem(), ")"))
	}
	return err
770 771
}

772
// Reset discards any information about the current decoding context
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
// and starts reading from r. This method is meant to facilitate reuse
// of a preallocated Stream across many decoding operations.
//
// If r does not also implement ByteReader, Stream will do its own
// buffering.
func (s *Stream) Reset(r io.Reader, inputLimit uint64) {
	if inputLimit > 0 {
		s.remaining = inputLimit
		s.limited = true
	} else {
		// Attempt to automatically discover
		// the limit when reading from a byte slice.
		switch br := r.(type) {
		case *bytes.Reader:
			s.remaining = uint64(br.Len())
			s.limited = true
		case *strings.Reader:
			s.remaining = uint64(br.Len())
			s.limited = true
		default:
			s.limited = false
		}
	}
	// Wrap r with a buffer if it doesn't have one.
797 798 799 800 801
	bufr, ok := r.(ByteReader)
	if !ok {
		bufr = bufio.NewReader(r)
	}
	s.r = bufr
802
	// Reset the decoding context.
803 804 805
	s.stack = s.stack[:0]
	s.size = 0
	s.kind = -1
806
	s.kinderr = nil
807 808 809
	if s.uintbuf == nil {
		s.uintbuf = make([]byte, 8)
	}
810
	s.byteval = 0
811 812
}

813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
// Kind returns the kind and size of the next value in the
// input stream.
//
// The returned size is the number of bytes that make up the value.
// For kind == Byte, the size is zero because the value is
// contained in the type tag.
//
// The first call to Kind will read size information from the input
// reader and leave it positioned at the start of the actual bytes of
// the value. Subsequent calls to Kind (until the value is decoded)
// will not advance the input reader and return cached information.
func (s *Stream) Kind() (kind Kind, size uint64, err error) {
	var tos *listpos
	if len(s.stack) > 0 {
		tos = &s.stack[len(s.stack)-1]
	}
	if s.kind < 0 {
830
		s.kinderr = nil
831
		// Don't read further if we're at the end of the
832
		// innermost list.
833 834 835
		if tos != nil && tos.pos == tos.size {
			return 0, 0, EOL
		}
836 837 838 839 840 841 842 843 844 845 846 847 848 849
		s.kind, s.size, s.kinderr = s.readKind()
		if s.kinderr == nil {
			if tos == nil {
				// At toplevel, check that the value is smaller
				// than the remaining input length.
				if s.limited && s.size > s.remaining {
					s.kinderr = ErrValueTooLarge
				}
			} else {
				// Inside a list, check that the value doesn't overflow the list.
				if s.size > tos.size-tos.pos {
					s.kinderr = ErrElemTooLarge
				}
			}
850
		}
851
	}
852 853 854
	// Note: this might return a sticky error generated
	// by an earlier call to readKind.
	return s.kind, s.size, s.kinderr
855 856 857 858 859
}

func (s *Stream) readKind() (kind Kind, size uint64, err error) {
	b, err := s.readByte()
	if err != nil {
860 861 862 863 864 865 866 867 868 869
		if len(s.stack) == 0 {
			// At toplevel, Adjust the error to actual EOF. io.EOF is
			// used by callers to determine when to stop decoding.
			switch err {
			case io.ErrUnexpectedEOF:
				err = io.EOF
			case ErrValueTooLarge:
				err = io.EOF
			}
		}
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
		return 0, 0, err
	}
	s.byteval = 0
	switch {
	case b < 0x80:
		// For a single byte whose value is in the [0x00, 0x7F] range, that byte
		// is its own RLP encoding.
		s.byteval = b
		return Byte, 0, nil
	case b < 0xB8:
		// Otherwise, if a string is 0-55 bytes long,
		// the RLP encoding consists of a single byte with value 0x80 plus the
		// length of the string followed by the string. The range of the first
		// byte is thus [0x80, 0xB7].
		return String, uint64(b - 0x80), nil
	case b < 0xC0:
		// If a string is more than 55 bytes long, the
		// RLP encoding consists of a single byte with value 0xB7 plus the length
		// of the length of the string in binary form, followed by the length of
		// the string, followed by the string. For example, a length-1024 string
		// would be encoded as 0xB90400 followed by the string. The range of
		// the first byte is thus [0xB8, 0xBF].
		size, err = s.readUint(b - 0xB7)
893 894 895
		if err == nil && size < 56 {
			err = ErrCanonSize
		}
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
		return String, size, err
	case b < 0xF8:
		// If the total payload of a list
		// (i.e. the combined length of all its items) is 0-55 bytes long, the
		// RLP encoding consists of a single byte with value 0xC0 plus the length
		// of the list followed by the concatenation of the RLP encodings of the
		// items. The range of the first byte is thus [0xC0, 0xF7].
		return List, uint64(b - 0xC0), nil
	default:
		// If the total payload of a list is more than 55 bytes long,
		// the RLP encoding consists of a single byte with value 0xF7
		// plus the length of the length of the payload in binary
		// form, followed by the length of the payload, followed by
		// the concatenation of the RLP encodings of the items. The
		// range of the first byte is thus [0xF8, 0xFF].
		size, err = s.readUint(b - 0xF7)
912 913 914
		if err == nil && size < 56 {
			err = ErrCanonSize
		}
915 916 917 918 919
		return List, size, err
	}
}

func (s *Stream) readUint(size byte) (uint64, error) {
920 921 922 923 924
	switch size {
	case 0:
		s.kind = -1 // rearm Kind
		return 0, nil
	case 1:
925 926
		b, err := s.readByte()
		return uint64(b), err
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
	default:
		start := int(8 - size)
		for i := 0; i < start; i++ {
			s.uintbuf[i] = 0
		}
		if err := s.readFull(s.uintbuf[start:]); err != nil {
			return 0, err
		}
		if s.uintbuf[start] == 0 {
			// Note: readUint is also used to decode integer
			// values. The error needs to be adjusted to become
			// ErrCanonInt in this case.
			return 0, ErrCanonSize
		}
		return binary.BigEndian.Uint64(s.uintbuf), nil
942 943 944 945
	}
}

func (s *Stream) readFull(buf []byte) (err error) {
946 947
	if err := s.willRead(uint64(len(buf))); err != nil {
		return err
948
	}
949 950 951 952 953 954 955 956 957 958 959 960
	var nn, n int
	for n < len(buf) && err == nil {
		nn, err = s.r.Read(buf[n:])
		n += nn
	}
	if err == io.EOF {
		err = io.ErrUnexpectedEOF
	}
	return err
}

func (s *Stream) readByte() (byte, error) {
961 962
	if err := s.willRead(1); err != nil {
		return 0, err
963
	}
964
	b, err := s.r.ReadByte()
965
	if err == io.EOF {
966 967 968 969 970
		err = io.ErrUnexpectedEOF
	}
	return b, err
}

971
func (s *Stream) willRead(n uint64) error {
972
	s.kind = -1 // rearm Kind
973

974
	if len(s.stack) > 0 {
975 976 977 978 979
		// check list overflow
		tos := s.stack[len(s.stack)-1]
		if n > tos.size-tos.pos {
			return ErrElemTooLarge
		}
980 981
		s.stack[len(s.stack)-1].pos += n
	}
982 983 984 985 986 987 988
	if s.limited {
		if n > s.remaining {
			return ErrValueTooLarge
		}
		s.remaining -= n
	}
	return nil
989
}