decode.go 26 KB

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