decode.go 28 KB

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