decode.go 28 KB

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