encode.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. "fmt"
  19. "io"
  20. "math/big"
  21. "reflect"
  22. "sync"
  23. )
  24. var (
  25. // Common encoded values.
  26. // These are useful when implementing EncodeRLP.
  27. EmptyString = []byte{0x80}
  28. EmptyList = []byte{0xC0}
  29. )
  30. // Encoder is implemented by types that require custom
  31. // encoding rules or want to encode private fields.
  32. type Encoder interface {
  33. // EncodeRLP should write the RLP encoding of its receiver to w.
  34. // If the implementation is a pointer method, it may also be
  35. // called for nil pointers.
  36. //
  37. // Implementations should generate valid RLP. The data written is
  38. // not verified at the moment, but a future version might. It is
  39. // recommended to write only a single value but writing multiple
  40. // values or no value at all is also permitted.
  41. EncodeRLP(io.Writer) error
  42. }
  43. // Encode writes the RLP encoding of val to w. Note that Encode may
  44. // perform many small writes in some cases. Consider making w
  45. // buffered.
  46. //
  47. // Encode uses the following type-dependent encoding rules:
  48. //
  49. // If the type implements the Encoder interface, Encode calls
  50. // EncodeRLP. This is true even for nil pointers, please see the
  51. // documentation for Encoder.
  52. //
  53. // To encode a pointer, the value being pointed to is encoded. For nil
  54. // pointers, Encode will encode the zero value of the type. A nil
  55. // pointer to a struct type always encodes as an empty RLP list.
  56. // A nil pointer to an array encodes as an empty list (or empty string
  57. // if the array has element type byte).
  58. //
  59. // Struct values are encoded as an RLP list of all their encoded
  60. // public fields. Recursive struct types are supported.
  61. //
  62. // To encode slices and arrays, the elements are encoded as an RLP
  63. // list of the value's elements. Note that arrays and slices with
  64. // element type uint8 or byte are always encoded as an RLP string.
  65. //
  66. // A Go string is encoded as an RLP string.
  67. //
  68. // An unsigned integer value is encoded as an RLP string. Zero always
  69. // encodes as an empty RLP string. Encode also supports *big.Int.
  70. //
  71. // An interface value encodes as the value contained in the interface.
  72. //
  73. // Boolean values are not supported, nor are signed integers, floating
  74. // point numbers, maps, channels and functions.
  75. func Encode(w io.Writer, val interface{}) error {
  76. if outer, ok := w.(*encbuf); ok {
  77. // Encode was called by some type's EncodeRLP.
  78. // Avoid copying by writing to the outer encbuf directly.
  79. return outer.encode(val)
  80. }
  81. eb := encbufPool.Get().(*encbuf)
  82. defer encbufPool.Put(eb)
  83. eb.reset()
  84. if err := eb.encode(val); err != nil {
  85. return err
  86. }
  87. return eb.toWriter(w)
  88. }
  89. // EncodeToBytes returns the RLP encoding of val.
  90. // Please see the documentation of Encode for the encoding rules.
  91. func EncodeToBytes(val interface{}) ([]byte, error) {
  92. eb := encbufPool.Get().(*encbuf)
  93. defer encbufPool.Put(eb)
  94. eb.reset()
  95. if err := eb.encode(val); err != nil {
  96. return nil, err
  97. }
  98. return eb.toBytes(), nil
  99. }
  100. // EncodeToReader returns a reader from which the RLP encoding of val
  101. // can be read. The returned size is the total size of the encoded
  102. // data.
  103. //
  104. // Please see the documentation of Encode for the encoding rules.
  105. func EncodeToReader(val interface{}) (size int, r io.Reader, err error) {
  106. eb := encbufPool.Get().(*encbuf)
  107. eb.reset()
  108. if err := eb.encode(val); err != nil {
  109. return 0, nil, err
  110. }
  111. return eb.size(), &encReader{buf: eb}, nil
  112. }
  113. type encbuf struct {
  114. str []byte // string data, contains everything except list headers
  115. lheads []*listhead // all list headers
  116. lhsize int // sum of sizes of all encoded list headers
  117. sizebuf []byte // 9-byte auxiliary buffer for uint encoding
  118. }
  119. type listhead struct {
  120. offset int // index of this header in string data
  121. size int // total size of encoded data (including list headers)
  122. }
  123. // encode writes head to the given buffer, which must be at least
  124. // 9 bytes long. It returns the encoded bytes.
  125. func (head *listhead) encode(buf []byte) []byte {
  126. return buf[:puthead(buf, 0xC0, 0xF7, uint64(head.size))]
  127. }
  128. // headsize returns the size of a list or string header
  129. // for a value of the given size.
  130. func headsize(size uint64) int {
  131. if size < 56 {
  132. return 1
  133. }
  134. return 1 + intsize(size)
  135. }
  136. // puthead writes a list or string header to buf.
  137. // buf must be at least 9 bytes long.
  138. func puthead(buf []byte, smalltag, largetag byte, size uint64) int {
  139. if size < 56 {
  140. buf[0] = smalltag + byte(size)
  141. return 1
  142. }
  143. sizesize := putint(buf[1:], size)
  144. buf[0] = largetag + byte(sizesize)
  145. return sizesize + 1
  146. }
  147. // encbufs are pooled.
  148. var encbufPool = sync.Pool{
  149. New: func() interface{} { return &encbuf{sizebuf: make([]byte, 9)} },
  150. }
  151. func (w *encbuf) reset() {
  152. w.lhsize = 0
  153. if w.str != nil {
  154. w.str = w.str[:0]
  155. }
  156. if w.lheads != nil {
  157. w.lheads = w.lheads[:0]
  158. }
  159. }
  160. // encbuf implements io.Writer so it can be passed it into EncodeRLP.
  161. func (w *encbuf) Write(b []byte) (int, error) {
  162. w.str = append(w.str, b...)
  163. return len(b), nil
  164. }
  165. func (w *encbuf) encode(val interface{}) error {
  166. rval := reflect.ValueOf(val)
  167. ti, err := cachedTypeInfo(rval.Type(), tags{})
  168. if err != nil {
  169. return err
  170. }
  171. return ti.writer(rval, w)
  172. }
  173. func (w *encbuf) encodeStringHeader(size int) {
  174. if size < 56 {
  175. w.str = append(w.str, 0x80+byte(size))
  176. } else {
  177. // TODO: encode to w.str directly
  178. sizesize := putint(w.sizebuf[1:], uint64(size))
  179. w.sizebuf[0] = 0xB7 + byte(sizesize)
  180. w.str = append(w.str, w.sizebuf[:sizesize+1]...)
  181. }
  182. }
  183. func (w *encbuf) encodeString(b []byte) {
  184. if len(b) == 1 && b[0] <= 0x7F {
  185. // fits single byte, no string header
  186. w.str = append(w.str, b[0])
  187. } else {
  188. w.encodeStringHeader(len(b))
  189. w.str = append(w.str, b...)
  190. }
  191. }
  192. func (w *encbuf) list() *listhead {
  193. lh := &listhead{offset: len(w.str), size: w.lhsize}
  194. w.lheads = append(w.lheads, lh)
  195. return lh
  196. }
  197. func (w *encbuf) listEnd(lh *listhead) {
  198. lh.size = w.size() - lh.offset - lh.size
  199. if lh.size < 56 {
  200. w.lhsize++ // length encoded into kind tag
  201. } else {
  202. w.lhsize += 1 + intsize(uint64(lh.size))
  203. }
  204. }
  205. func (w *encbuf) size() int {
  206. return len(w.str) + w.lhsize
  207. }
  208. func (w *encbuf) toBytes() []byte {
  209. out := make([]byte, w.size())
  210. strpos := 0
  211. pos := 0
  212. for _, head := range w.lheads {
  213. // write string data before header
  214. n := copy(out[pos:], w.str[strpos:head.offset])
  215. pos += n
  216. strpos += n
  217. // write the header
  218. enc := head.encode(out[pos:])
  219. pos += len(enc)
  220. }
  221. // copy string data after the last list header
  222. copy(out[pos:], w.str[strpos:])
  223. return out
  224. }
  225. func (w *encbuf) toWriter(out io.Writer) (err error) {
  226. strpos := 0
  227. for _, head := range w.lheads {
  228. // write string data before header
  229. if head.offset-strpos > 0 {
  230. n, err := out.Write(w.str[strpos:head.offset])
  231. strpos += n
  232. if err != nil {
  233. return err
  234. }
  235. }
  236. // write the header
  237. enc := head.encode(w.sizebuf)
  238. if _, err = out.Write(enc); err != nil {
  239. return err
  240. }
  241. }
  242. if strpos < len(w.str) {
  243. // write string data after the last list header
  244. _, err = out.Write(w.str[strpos:])
  245. }
  246. return err
  247. }
  248. // encReader is the io.Reader returned by EncodeToReader.
  249. // It releases its encbuf at EOF.
  250. type encReader struct {
  251. buf *encbuf // the buffer we're reading from. this is nil when we're at EOF.
  252. lhpos int // index of list header that we're reading
  253. strpos int // current position in string buffer
  254. piece []byte // next piece to be read
  255. }
  256. func (r *encReader) Read(b []byte) (n int, err error) {
  257. for {
  258. if r.piece = r.next(); r.piece == nil {
  259. // Put the encode buffer back into the pool at EOF when it
  260. // is first encountered. Subsequent calls still return EOF
  261. // as the error but the buffer is no longer valid.
  262. if r.buf != nil {
  263. encbufPool.Put(r.buf)
  264. r.buf = nil
  265. }
  266. return n, io.EOF
  267. }
  268. nn := copy(b[n:], r.piece)
  269. n += nn
  270. if nn < len(r.piece) {
  271. // piece didn't fit, see you next time.
  272. r.piece = r.piece[nn:]
  273. return n, nil
  274. }
  275. r.piece = nil
  276. }
  277. }
  278. // next returns the next piece of data to be read.
  279. // it returns nil at EOF.
  280. func (r *encReader) next() []byte {
  281. switch {
  282. case r.buf == nil:
  283. return nil
  284. case r.piece != nil:
  285. // There is still data available for reading.
  286. return r.piece
  287. case r.lhpos < len(r.buf.lheads):
  288. // We're before the last list header.
  289. head := r.buf.lheads[r.lhpos]
  290. sizebefore := head.offset - r.strpos
  291. if sizebefore > 0 {
  292. // String data before header.
  293. p := r.buf.str[r.strpos:head.offset]
  294. r.strpos += sizebefore
  295. return p
  296. }
  297. r.lhpos++
  298. return head.encode(r.buf.sizebuf)
  299. case r.strpos < len(r.buf.str):
  300. // String data at the end, after all list headers.
  301. p := r.buf.str[r.strpos:]
  302. r.strpos = len(r.buf.str)
  303. return p
  304. default:
  305. return nil
  306. }
  307. }
  308. var (
  309. encoderInterface = reflect.TypeOf(new(Encoder)).Elem()
  310. big0 = big.NewInt(0)
  311. )
  312. // makeWriter creates a writer function for the given type.
  313. func makeWriter(typ reflect.Type, ts tags) (writer, error) {
  314. kind := typ.Kind()
  315. switch {
  316. case typ == rawValueType:
  317. return writeRawValue, nil
  318. case typ.Implements(encoderInterface):
  319. return writeEncoder, nil
  320. case kind != reflect.Ptr && reflect.PtrTo(typ).Implements(encoderInterface):
  321. return writeEncoderNoPtr, nil
  322. case kind == reflect.Interface:
  323. return writeInterface, nil
  324. case typ.AssignableTo(reflect.PtrTo(bigInt)):
  325. return writeBigIntPtr, nil
  326. case typ.AssignableTo(bigInt):
  327. return writeBigIntNoPtr, nil
  328. case isUint(kind):
  329. return writeUint, nil
  330. case kind == reflect.Bool:
  331. return writeBool, nil
  332. case kind == reflect.String:
  333. return writeString, nil
  334. case kind == reflect.Slice && isByte(typ.Elem()):
  335. return writeBytes, nil
  336. case kind == reflect.Array && isByte(typ.Elem()):
  337. return writeByteArray, nil
  338. case kind == reflect.Slice || kind == reflect.Array:
  339. return makeSliceWriter(typ, ts)
  340. case kind == reflect.Struct:
  341. return makeStructWriter(typ)
  342. case kind == reflect.Ptr:
  343. return makePtrWriter(typ)
  344. default:
  345. return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ)
  346. }
  347. }
  348. func isByte(typ reflect.Type) bool {
  349. return typ.Kind() == reflect.Uint8 && !typ.Implements(encoderInterface)
  350. }
  351. func writeRawValue(val reflect.Value, w *encbuf) error {
  352. w.str = append(w.str, val.Bytes()...)
  353. return nil
  354. }
  355. func writeUint(val reflect.Value, w *encbuf) error {
  356. i := val.Uint()
  357. if i == 0 {
  358. w.str = append(w.str, 0x80)
  359. } else if i < 128 {
  360. // fits single byte
  361. w.str = append(w.str, byte(i))
  362. } else {
  363. // TODO: encode int to w.str directly
  364. s := putint(w.sizebuf[1:], i)
  365. w.sizebuf[0] = 0x80 + byte(s)
  366. w.str = append(w.str, w.sizebuf[:s+1]...)
  367. }
  368. return nil
  369. }
  370. func writeBool(val reflect.Value, w *encbuf) error {
  371. if val.Bool() {
  372. w.str = append(w.str, 0x01)
  373. } else {
  374. w.str = append(w.str, 0x80)
  375. }
  376. return nil
  377. }
  378. func writeBigIntPtr(val reflect.Value, w *encbuf) error {
  379. ptr := val.Interface().(*big.Int)
  380. if ptr == nil {
  381. w.str = append(w.str, 0x80)
  382. return nil
  383. }
  384. return writeBigInt(ptr, w)
  385. }
  386. func writeBigIntNoPtr(val reflect.Value, w *encbuf) error {
  387. i := val.Interface().(big.Int)
  388. return writeBigInt(&i, w)
  389. }
  390. func writeBigInt(i *big.Int, w *encbuf) error {
  391. if cmp := i.Cmp(big0); cmp == -1 {
  392. return fmt.Errorf("rlp: cannot encode negative *big.Int")
  393. } else if cmp == 0 {
  394. w.str = append(w.str, 0x80)
  395. } else {
  396. w.encodeString(i.Bytes())
  397. }
  398. return nil
  399. }
  400. func writeBytes(val reflect.Value, w *encbuf) error {
  401. w.encodeString(val.Bytes())
  402. return nil
  403. }
  404. func writeByteArray(val reflect.Value, w *encbuf) error {
  405. if !val.CanAddr() {
  406. // Slice requires the value to be addressable.
  407. // Make it addressable by copying.
  408. copy := reflect.New(val.Type()).Elem()
  409. copy.Set(val)
  410. val = copy
  411. }
  412. size := val.Len()
  413. slice := val.Slice(0, size).Bytes()
  414. w.encodeString(slice)
  415. return nil
  416. }
  417. func writeString(val reflect.Value, w *encbuf) error {
  418. s := val.String()
  419. if len(s) == 1 && s[0] <= 0x7f {
  420. // fits single byte, no string header
  421. w.str = append(w.str, s[0])
  422. } else {
  423. w.encodeStringHeader(len(s))
  424. w.str = append(w.str, s...)
  425. }
  426. return nil
  427. }
  428. func writeEncoder(val reflect.Value, w *encbuf) error {
  429. return val.Interface().(Encoder).EncodeRLP(w)
  430. }
  431. // writeEncoderNoPtr handles non-pointer values that implement Encoder
  432. // with a pointer receiver.
  433. func writeEncoderNoPtr(val reflect.Value, w *encbuf) error {
  434. if !val.CanAddr() {
  435. // We can't get the address. It would be possible to make the
  436. // value addressable by creating a shallow copy, but this
  437. // creates other problems so we're not doing it (yet).
  438. //
  439. // package json simply doesn't call MarshalJSON for cases like
  440. // this, but encodes the value as if it didn't implement the
  441. // interface. We don't want to handle it that way.
  442. return fmt.Errorf("rlp: game over: unadressable value of type %v, EncodeRLP is pointer method", val.Type())
  443. }
  444. return val.Addr().Interface().(Encoder).EncodeRLP(w)
  445. }
  446. func writeInterface(val reflect.Value, w *encbuf) error {
  447. if val.IsNil() {
  448. // Write empty list. This is consistent with the previous RLP
  449. // encoder that we had and should therefore avoid any
  450. // problems.
  451. w.str = append(w.str, 0xC0)
  452. return nil
  453. }
  454. eval := val.Elem()
  455. ti, err := cachedTypeInfo(eval.Type(), tags{})
  456. if err != nil {
  457. return err
  458. }
  459. return ti.writer(eval, w)
  460. }
  461. func makeSliceWriter(typ reflect.Type, ts tags) (writer, error) {
  462. etypeinfo, err := cachedTypeInfo1(typ.Elem(), tags{})
  463. if err != nil {
  464. return nil, err
  465. }
  466. writer := func(val reflect.Value, w *encbuf) error {
  467. if !ts.tail {
  468. defer w.listEnd(w.list())
  469. }
  470. vlen := val.Len()
  471. for i := 0; i < vlen; i++ {
  472. if err := etypeinfo.writer(val.Index(i), w); err != nil {
  473. return err
  474. }
  475. }
  476. return nil
  477. }
  478. return writer, nil
  479. }
  480. func makeStructWriter(typ reflect.Type) (writer, error) {
  481. fields, err := structFields(typ)
  482. if err != nil {
  483. return nil, err
  484. }
  485. writer := func(val reflect.Value, w *encbuf) error {
  486. lh := w.list()
  487. for _, f := range fields {
  488. if err := f.info.writer(val.Field(f.index), w); err != nil {
  489. return err
  490. }
  491. }
  492. w.listEnd(lh)
  493. return nil
  494. }
  495. return writer, nil
  496. }
  497. func makePtrWriter(typ reflect.Type) (writer, error) {
  498. etypeinfo, err := cachedTypeInfo1(typ.Elem(), tags{})
  499. if err != nil {
  500. return nil, err
  501. }
  502. // determine nil pointer handler
  503. var nilfunc func(*encbuf) error
  504. kind := typ.Elem().Kind()
  505. switch {
  506. case kind == reflect.Array && isByte(typ.Elem().Elem()):
  507. nilfunc = func(w *encbuf) error {
  508. w.str = append(w.str, 0x80)
  509. return nil
  510. }
  511. case kind == reflect.Struct || kind == reflect.Array:
  512. nilfunc = func(w *encbuf) error {
  513. // encoding the zero value of a struct/array could trigger
  514. // infinite recursion, avoid that.
  515. w.listEnd(w.list())
  516. return nil
  517. }
  518. default:
  519. zero := reflect.Zero(typ.Elem())
  520. nilfunc = func(w *encbuf) error {
  521. return etypeinfo.writer(zero, w)
  522. }
  523. }
  524. writer := func(val reflect.Value, w *encbuf) error {
  525. if val.IsNil() {
  526. return nilfunc(w)
  527. }
  528. return etypeinfo.writer(val.Elem(), w)
  529. }
  530. return writer, err
  531. }
  532. // putint writes i to the beginning of b in big endian byte
  533. // order, using the least number of bytes needed to represent i.
  534. func putint(b []byte, i uint64) (size int) {
  535. switch {
  536. case i < (1 << 8):
  537. b[0] = byte(i)
  538. return 1
  539. case i < (1 << 16):
  540. b[0] = byte(i >> 8)
  541. b[1] = byte(i)
  542. return 2
  543. case i < (1 << 24):
  544. b[0] = byte(i >> 16)
  545. b[1] = byte(i >> 8)
  546. b[2] = byte(i)
  547. return 3
  548. case i < (1 << 32):
  549. b[0] = byte(i >> 24)
  550. b[1] = byte(i >> 16)
  551. b[2] = byte(i >> 8)
  552. b[3] = byte(i)
  553. return 4
  554. case i < (1 << 40):
  555. b[0] = byte(i >> 32)
  556. b[1] = byte(i >> 24)
  557. b[2] = byte(i >> 16)
  558. b[3] = byte(i >> 8)
  559. b[4] = byte(i)
  560. return 5
  561. case i < (1 << 48):
  562. b[0] = byte(i >> 40)
  563. b[1] = byte(i >> 32)
  564. b[2] = byte(i >> 24)
  565. b[3] = byte(i >> 16)
  566. b[4] = byte(i >> 8)
  567. b[5] = byte(i)
  568. return 6
  569. case i < (1 << 56):
  570. b[0] = byte(i >> 48)
  571. b[1] = byte(i >> 40)
  572. b[2] = byte(i >> 32)
  573. b[3] = byte(i >> 24)
  574. b[4] = byte(i >> 16)
  575. b[5] = byte(i >> 8)
  576. b[6] = byte(i)
  577. return 7
  578. default:
  579. b[0] = byte(i >> 56)
  580. b[1] = byte(i >> 48)
  581. b[2] = byte(i >> 40)
  582. b[3] = byte(i >> 32)
  583. b[4] = byte(i >> 24)
  584. b[5] = byte(i >> 16)
  585. b[6] = byte(i >> 8)
  586. b[7] = byte(i)
  587. return 8
  588. }
  589. }
  590. // intsize computes the minimum number of bytes required to store i.
  591. func intsize(i uint64) (size int) {
  592. for size = 1; ; size++ {
  593. if i >>= 8; i == 0 {
  594. return size
  595. }
  596. }
  597. }