decode.go 26 KB

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