decode.go 28 KB

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