decode.go 28 KB

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