decode.go 28 KB

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