decode.go 29 KB

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