decode.go 28 KB

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