decode.go 26 KB

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