decode_test.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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. "bytes"
  19. "encoding/hex"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "math/big"
  24. "reflect"
  25. "strings"
  26. "testing"
  27. "github.com/ethereum/go-ethereum/common/math"
  28. )
  29. func TestStreamKind(t *testing.T) {
  30. tests := []struct {
  31. input string
  32. wantKind Kind
  33. wantLen uint64
  34. }{
  35. {"00", Byte, 0},
  36. {"01", Byte, 0},
  37. {"7F", Byte, 0},
  38. {"80", String, 0},
  39. {"B7", String, 55},
  40. {"B90400", String, 1024},
  41. {"BFFFFFFFFFFFFFFFFF", String, ^uint64(0)},
  42. {"C0", List, 0},
  43. {"C8", List, 8},
  44. {"F7", List, 55},
  45. {"F90400", List, 1024},
  46. {"FFFFFFFFFFFFFFFFFF", List, ^uint64(0)},
  47. }
  48. for i, test := range tests {
  49. // using plainReader to inhibit input limit errors.
  50. s := NewStream(newPlainReader(unhex(test.input)), 0)
  51. kind, len, err := s.Kind()
  52. if err != nil {
  53. t.Errorf("test %d: Kind returned error: %v", i, err)
  54. continue
  55. }
  56. if kind != test.wantKind {
  57. t.Errorf("test %d: kind mismatch: got %d, want %d", i, kind, test.wantKind)
  58. }
  59. if len != test.wantLen {
  60. t.Errorf("test %d: len mismatch: got %d, want %d", i, len, test.wantLen)
  61. }
  62. }
  63. }
  64. func TestNewListStream(t *testing.T) {
  65. ls := NewListStream(bytes.NewReader(unhex("0101010101")), 3)
  66. if k, size, err := ls.Kind(); k != List || size != 3 || err != nil {
  67. t.Errorf("Kind() returned (%v, %d, %v), expected (List, 3, nil)", k, size, err)
  68. }
  69. if size, err := ls.List(); size != 3 || err != nil {
  70. t.Errorf("List() returned (%d, %v), expected (3, nil)", size, err)
  71. }
  72. for i := 0; i < 3; i++ {
  73. if val, err := ls.Uint(); val != 1 || err != nil {
  74. t.Errorf("Uint() returned (%d, %v), expected (1, nil)", val, err)
  75. }
  76. }
  77. if err := ls.ListEnd(); err != nil {
  78. t.Errorf("ListEnd() returned %v, expected (3, nil)", err)
  79. }
  80. }
  81. func TestStreamErrors(t *testing.T) {
  82. withoutInputLimit := func(b []byte) *Stream {
  83. return NewStream(newPlainReader(b), 0)
  84. }
  85. withCustomInputLimit := func(limit uint64) func([]byte) *Stream {
  86. return func(b []byte) *Stream {
  87. return NewStream(bytes.NewReader(b), limit)
  88. }
  89. }
  90. type calls []string
  91. tests := []struct {
  92. string
  93. calls
  94. newStream func([]byte) *Stream // uses bytes.Reader if nil
  95. error error
  96. }{
  97. {"C0", calls{"Bytes"}, nil, ErrExpectedString},
  98. {"C0", calls{"Uint"}, nil, ErrExpectedString},
  99. {"89000000000000000001", calls{"Uint"}, nil, errUintOverflow},
  100. {"00", calls{"List"}, nil, ErrExpectedList},
  101. {"80", calls{"List"}, nil, ErrExpectedList},
  102. {"C0", calls{"List", "Uint"}, nil, EOL},
  103. {"C8C9010101010101010101", calls{"List", "Kind"}, nil, ErrElemTooLarge},
  104. {"C3C2010201", calls{"List", "List", "Uint", "Uint", "ListEnd", "Uint"}, nil, EOL},
  105. {"00", calls{"ListEnd"}, nil, errNotInList},
  106. {"C401020304", calls{"List", "Uint", "ListEnd"}, nil, errNotAtEOL},
  107. // Non-canonical integers (e.g. leading zero bytes).
  108. {"00", calls{"Uint"}, nil, ErrCanonInt},
  109. {"820002", calls{"Uint"}, nil, ErrCanonInt},
  110. {"8133", calls{"Uint"}, nil, ErrCanonSize},
  111. {"817F", calls{"Uint"}, nil, ErrCanonSize},
  112. {"8180", calls{"Uint"}, nil, nil},
  113. // Non-valid boolean
  114. {"02", calls{"Bool"}, nil, errors.New("rlp: invalid boolean value: 2")},
  115. // Size tags must use the smallest possible encoding.
  116. // Leading zero bytes in the size tag are also rejected.
  117. {"8100", calls{"Uint"}, nil, ErrCanonSize},
  118. {"8100", calls{"Bytes"}, nil, ErrCanonSize},
  119. {"8101", calls{"Bytes"}, nil, ErrCanonSize},
  120. {"817F", calls{"Bytes"}, nil, ErrCanonSize},
  121. {"8180", calls{"Bytes"}, nil, nil},
  122. {"B800", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
  123. {"B90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
  124. {"B90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
  125. {"BA0002FFFF", calls{"Bytes"}, withoutInputLimit, ErrCanonSize},
  126. {"F800", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
  127. {"F90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
  128. {"F90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
  129. {"FA0002FFFF", calls{"List"}, withoutInputLimit, ErrCanonSize},
  130. // Expected EOF
  131. {"", calls{"Kind"}, nil, io.EOF},
  132. {"", calls{"Uint"}, nil, io.EOF},
  133. {"", calls{"List"}, nil, io.EOF},
  134. {"8180", calls{"Uint", "Uint"}, nil, io.EOF},
  135. {"C0", calls{"List", "ListEnd", "List"}, nil, io.EOF},
  136. {"", calls{"List"}, withoutInputLimit, io.EOF},
  137. {"8180", calls{"Uint", "Uint"}, withoutInputLimit, io.EOF},
  138. {"C0", calls{"List", "ListEnd", "List"}, withoutInputLimit, io.EOF},
  139. // Input limit errors.
  140. {"81", calls{"Bytes"}, nil, ErrValueTooLarge},
  141. {"81", calls{"Uint"}, nil, ErrValueTooLarge},
  142. {"81", calls{"Raw"}, nil, ErrValueTooLarge},
  143. {"BFFFFFFFFFFFFFFFFFFF", calls{"Bytes"}, nil, ErrValueTooLarge},
  144. {"C801", calls{"List"}, nil, ErrValueTooLarge},
  145. // Test for list element size check overflow.
  146. {"CD04040404FFFFFFFFFFFFFFFFFF0303", calls{"List", "Uint", "Uint", "Uint", "Uint", "List"}, nil, ErrElemTooLarge},
  147. // Test for input limit overflow. Since we are counting the limit
  148. // down toward zero in Stream.remaining, reading too far can overflow
  149. // remaining to a large value, effectively disabling the limit.
  150. {"C40102030401", calls{"Raw", "Uint"}, withCustomInputLimit(5), io.EOF},
  151. {"C4010203048180", calls{"Raw", "Uint"}, withCustomInputLimit(6), ErrValueTooLarge},
  152. // Check that the same calls are fine without a limit.
  153. {"C40102030401", calls{"Raw", "Uint"}, withoutInputLimit, nil},
  154. {"C4010203048180", calls{"Raw", "Uint"}, withoutInputLimit, nil},
  155. // Unexpected EOF. This only happens when there is
  156. // no input limit, so the reader needs to be 'dumbed down'.
  157. {"81", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF},
  158. {"81", calls{"Uint"}, withoutInputLimit, io.ErrUnexpectedEOF},
  159. {"BFFFFFFFFFFFFFFF", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF},
  160. {"C801", calls{"List", "Uint", "Uint"}, withoutInputLimit, io.ErrUnexpectedEOF},
  161. // This test verifies that the input position is advanced
  162. // correctly when calling Bytes for empty strings. Kind can be called
  163. // any number of times in between and doesn't advance.
  164. {"C3808080", calls{
  165. "List", // enter the list
  166. "Bytes", // past first element
  167. "Kind", "Kind", "Kind", // this shouldn't advance
  168. "Bytes", // past second element
  169. "Kind", "Kind", // can't hurt to try
  170. "Bytes", // past final element
  171. "Bytes", // this one should fail
  172. }, nil, EOL},
  173. }
  174. testfor:
  175. for i, test := range tests {
  176. if test.newStream == nil {
  177. test.newStream = func(b []byte) *Stream { return NewStream(bytes.NewReader(b), 0) }
  178. }
  179. s := test.newStream(unhex(test.string))
  180. rs := reflect.ValueOf(s)
  181. for j, call := range test.calls {
  182. fval := rs.MethodByName(call)
  183. ret := fval.Call(nil)
  184. err := "<nil>"
  185. if lastret := ret[len(ret)-1].Interface(); lastret != nil {
  186. err = lastret.(error).Error()
  187. }
  188. if j == len(test.calls)-1 {
  189. want := "<nil>"
  190. if test.error != nil {
  191. want = test.error.Error()
  192. }
  193. if err != want {
  194. t.Log(test)
  195. t.Errorf("test %d: last call (%s) error mismatch\ngot: %s\nwant: %s",
  196. i, call, err, test.error)
  197. }
  198. } else if err != "<nil>" {
  199. t.Log(test)
  200. t.Errorf("test %d: call %d (%s) unexpected error: %q", i, j, call, err)
  201. continue testfor
  202. }
  203. }
  204. }
  205. }
  206. func TestStreamList(t *testing.T) {
  207. s := NewStream(bytes.NewReader(unhex("C80102030405060708")), 0)
  208. len, err := s.List()
  209. if err != nil {
  210. t.Fatalf("List error: %v", err)
  211. }
  212. if len != 8 {
  213. t.Fatalf("List returned invalid length, got %d, want 8", len)
  214. }
  215. for i := uint64(1); i <= 8; i++ {
  216. v, err := s.Uint()
  217. if err != nil {
  218. t.Fatalf("Uint error: %v", err)
  219. }
  220. if i != v {
  221. t.Errorf("Uint returned wrong value, got %d, want %d", v, i)
  222. }
  223. }
  224. if _, err := s.Uint(); err != EOL {
  225. t.Errorf("Uint error mismatch, got %v, want %v", err, EOL)
  226. }
  227. if err = s.ListEnd(); err != nil {
  228. t.Fatalf("ListEnd error: %v", err)
  229. }
  230. }
  231. func TestStreamRaw(t *testing.T) {
  232. tests := []struct {
  233. input string
  234. output string
  235. }{
  236. {
  237. "C58401010101",
  238. "8401010101",
  239. },
  240. {
  241. "F842B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
  242. "B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101",
  243. },
  244. }
  245. for i, tt := range tests {
  246. s := NewStream(bytes.NewReader(unhex(tt.input)), 0)
  247. s.List()
  248. want := unhex(tt.output)
  249. raw, err := s.Raw()
  250. if err != nil {
  251. t.Fatal(err)
  252. }
  253. if !bytes.Equal(want, raw) {
  254. t.Errorf("test %d: raw mismatch: got %x, want %x", i, raw, want)
  255. }
  256. }
  257. }
  258. func TestDecodeErrors(t *testing.T) {
  259. r := bytes.NewReader(nil)
  260. if err := Decode(r, nil); err != errDecodeIntoNil {
  261. t.Errorf("Decode(r, nil) error mismatch, got %q, want %q", err, errDecodeIntoNil)
  262. }
  263. var nilptr *struct{}
  264. if err := Decode(r, nilptr); err != errDecodeIntoNil {
  265. t.Errorf("Decode(r, nilptr) error mismatch, got %q, want %q", err, errDecodeIntoNil)
  266. }
  267. if err := Decode(r, struct{}{}); err != errNoPointer {
  268. t.Errorf("Decode(r, struct{}{}) error mismatch, got %q, want %q", err, errNoPointer)
  269. }
  270. expectErr := "rlp: type chan bool is not RLP-serializable"
  271. if err := Decode(r, new(chan bool)); err == nil || err.Error() != expectErr {
  272. t.Errorf("Decode(r, new(chan bool)) error mismatch, got %q, want %q", err, expectErr)
  273. }
  274. if err := Decode(r, new(uint)); err != io.EOF {
  275. t.Errorf("Decode(r, new(int)) error mismatch, got %q, want %q", err, io.EOF)
  276. }
  277. }
  278. type decodeTest struct {
  279. input string
  280. ptr interface{}
  281. value interface{}
  282. error string
  283. }
  284. type simplestruct struct {
  285. A uint
  286. B string
  287. }
  288. type recstruct struct {
  289. I uint
  290. Child *recstruct `rlp:"nil"`
  291. }
  292. type bigIntStruct struct {
  293. I *big.Int
  294. B string
  295. }
  296. type invalidNilTag struct {
  297. X []byte `rlp:"nil"`
  298. }
  299. type invalidTail1 struct {
  300. A uint `rlp:"tail"`
  301. B string
  302. }
  303. type invalidTail2 struct {
  304. A uint
  305. B string `rlp:"tail"`
  306. }
  307. type tailRaw struct {
  308. A uint
  309. Tail []RawValue `rlp:"tail"`
  310. }
  311. type tailUint struct {
  312. A uint
  313. Tail []uint `rlp:"tail"`
  314. }
  315. type tailPrivateFields struct {
  316. A uint
  317. Tail []uint `rlp:"tail"`
  318. x, y bool //lint:ignore U1000 unused fields required for testing purposes.
  319. }
  320. type nilListUint struct {
  321. X *uint `rlp:"nilList"`
  322. }
  323. type nilStringSlice struct {
  324. X *[]uint `rlp:"nilString"`
  325. }
  326. type intField struct {
  327. X int
  328. }
  329. var (
  330. veryBigInt = new(big.Int).Add(
  331. big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16),
  332. big.NewInt(0xFFFF),
  333. )
  334. veryVeryBigInt = new(big.Int).Exp(veryBigInt, big.NewInt(8), nil)
  335. )
  336. type hasIgnoredField struct {
  337. A uint
  338. B uint `rlp:"-"`
  339. C uint
  340. }
  341. var decodeTests = []decodeTest{
  342. // booleans
  343. {input: "01", ptr: new(bool), value: true},
  344. {input: "80", ptr: new(bool), value: false},
  345. {input: "02", ptr: new(bool), error: "rlp: invalid boolean value: 2"},
  346. // integers
  347. {input: "05", ptr: new(uint32), value: uint32(5)},
  348. {input: "80", ptr: new(uint32), value: uint32(0)},
  349. {input: "820505", ptr: new(uint32), value: uint32(0x0505)},
  350. {input: "83050505", ptr: new(uint32), value: uint32(0x050505)},
  351. {input: "8405050505", ptr: new(uint32), value: uint32(0x05050505)},
  352. {input: "850505050505", ptr: new(uint32), error: "rlp: input string too long for uint32"},
  353. {input: "C0", ptr: new(uint32), error: "rlp: expected input string or byte for uint32"},
  354. {input: "00", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"},
  355. {input: "8105", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"},
  356. {input: "820004", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"},
  357. {input: "B8020004", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"},
  358. // slices
  359. {input: "C0", ptr: new([]uint), value: []uint{}},
  360. {input: "C80102030405060708", ptr: new([]uint), value: []uint{1, 2, 3, 4, 5, 6, 7, 8}},
  361. {input: "F8020004", ptr: new([]uint), error: "rlp: non-canonical size information for []uint"},
  362. // arrays
  363. {input: "C50102030405", ptr: new([5]uint), value: [5]uint{1, 2, 3, 4, 5}},
  364. {input: "C0", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"},
  365. {input: "C102", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"},
  366. {input: "C6010203040506", ptr: new([5]uint), error: "rlp: input list has too many elements for [5]uint"},
  367. {input: "F8020004", ptr: new([5]uint), error: "rlp: non-canonical size information for [5]uint"},
  368. // zero sized arrays
  369. {input: "C0", ptr: new([0]uint), value: [0]uint{}},
  370. {input: "C101", ptr: new([0]uint), error: "rlp: input list has too many elements for [0]uint"},
  371. // byte slices
  372. {input: "01", ptr: new([]byte), value: []byte{1}},
  373. {input: "80", ptr: new([]byte), value: []byte{}},
  374. {input: "8D6162636465666768696A6B6C6D", ptr: new([]byte), value: []byte("abcdefghijklm")},
  375. {input: "C0", ptr: new([]byte), error: "rlp: expected input string or byte for []uint8"},
  376. {input: "8105", ptr: new([]byte), error: "rlp: non-canonical size information for []uint8"},
  377. // byte arrays
  378. {input: "02", ptr: new([1]byte), value: [1]byte{2}},
  379. {input: "8180", ptr: new([1]byte), value: [1]byte{128}},
  380. {input: "850102030405", ptr: new([5]byte), value: [5]byte{1, 2, 3, 4, 5}},
  381. // byte array errors
  382. {input: "02", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"},
  383. {input: "80", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"},
  384. {input: "820000", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"},
  385. {input: "C0", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"},
  386. {input: "C3010203", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"},
  387. {input: "86010203040506", ptr: new([5]byte), error: "rlp: input string too long for [5]uint8"},
  388. {input: "8105", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"},
  389. {input: "817F", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"},
  390. // zero sized byte arrays
  391. {input: "80", ptr: new([0]byte), value: [0]byte{}},
  392. {input: "01", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"},
  393. {input: "8101", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"},
  394. // strings
  395. {input: "00", ptr: new(string), value: "\000"},
  396. {input: "8D6162636465666768696A6B6C6D", ptr: new(string), value: "abcdefghijklm"},
  397. {input: "C0", ptr: new(string), error: "rlp: expected input string or byte for string"},
  398. // big ints
  399. {input: "80", ptr: new(*big.Int), value: big.NewInt(0)},
  400. {input: "01", ptr: new(*big.Int), value: big.NewInt(1)},
  401. {input: "89FFFFFFFFFFFFFFFFFF", ptr: new(*big.Int), value: veryBigInt},
  402. {input: "B848FFFFFFFFFFFFFFFFF800000000000000001BFFFFFFFFFFFFFFFFC8000000000000000045FFFFFFFFFFFFFFFFC800000000000000001BFFFFFFFFFFFFFFFFF8000000000000000001", ptr: new(*big.Int), value: veryVeryBigInt},
  403. {input: "10", ptr: new(big.Int), value: *big.NewInt(16)}, // non-pointer also works
  404. {input: "C0", ptr: new(*big.Int), error: "rlp: expected input string or byte for *big.Int"},
  405. {input: "00", ptr: new(*big.Int), error: "rlp: non-canonical integer (leading zero bytes) for *big.Int"},
  406. {input: "820001", ptr: new(*big.Int), error: "rlp: non-canonical integer (leading zero bytes) for *big.Int"},
  407. {input: "8105", ptr: new(*big.Int), error: "rlp: non-canonical size information for *big.Int"},
  408. // structs
  409. {
  410. input: "C50583343434",
  411. ptr: new(simplestruct),
  412. value: simplestruct{5, "444"},
  413. },
  414. {
  415. input: "C601C402C203C0",
  416. ptr: new(recstruct),
  417. value: recstruct{1, &recstruct{2, &recstruct{3, nil}}},
  418. },
  419. {
  420. // This checks that empty big.Int works correctly in struct context. It's easy to
  421. // miss the update of s.kind for this case, so it needs its own test.
  422. input: "C58083343434",
  423. ptr: new(bigIntStruct),
  424. value: bigIntStruct{new(big.Int), "444"},
  425. },
  426. // struct errors
  427. {
  428. input: "C0",
  429. ptr: new(simplestruct),
  430. error: "rlp: too few elements for rlp.simplestruct",
  431. },
  432. {
  433. input: "C105",
  434. ptr: new(simplestruct),
  435. error: "rlp: too few elements for rlp.simplestruct",
  436. },
  437. {
  438. input: "C7C50583343434C0",
  439. ptr: new([]*simplestruct),
  440. error: "rlp: too few elements for rlp.simplestruct, decoding into ([]*rlp.simplestruct)[1]",
  441. },
  442. {
  443. input: "83222222",
  444. ptr: new(simplestruct),
  445. error: "rlp: expected input list for rlp.simplestruct",
  446. },
  447. {
  448. input: "C3010101",
  449. ptr: new(simplestruct),
  450. error: "rlp: input list has too many elements for rlp.simplestruct",
  451. },
  452. {
  453. input: "C501C3C00000",
  454. ptr: new(recstruct),
  455. error: "rlp: expected input string or byte for uint, decoding into (rlp.recstruct).Child.I",
  456. },
  457. {
  458. input: "C103",
  459. ptr: new(intField),
  460. error: "rlp: type int is not RLP-serializable (struct field rlp.intField.X)",
  461. },
  462. {
  463. input: "C50102C20102",
  464. ptr: new(tailUint),
  465. error: "rlp: expected input string or byte for uint, decoding into (rlp.tailUint).Tail[1]",
  466. },
  467. {
  468. input: "C0",
  469. ptr: new(invalidNilTag),
  470. error: `rlp: invalid struct tag "nil" for rlp.invalidNilTag.X (field is not a pointer)`,
  471. },
  472. // struct tag "tail"
  473. {
  474. input: "C3010203",
  475. ptr: new(tailRaw),
  476. value: tailRaw{A: 1, Tail: []RawValue{unhex("02"), unhex("03")}},
  477. },
  478. {
  479. input: "C20102",
  480. ptr: new(tailRaw),
  481. value: tailRaw{A: 1, Tail: []RawValue{unhex("02")}},
  482. },
  483. {
  484. input: "C101",
  485. ptr: new(tailRaw),
  486. value: tailRaw{A: 1, Tail: []RawValue{}},
  487. },
  488. {
  489. input: "C3010203",
  490. ptr: new(tailPrivateFields),
  491. value: tailPrivateFields{A: 1, Tail: []uint{2, 3}},
  492. },
  493. {
  494. input: "C0",
  495. ptr: new(invalidTail1),
  496. error: `rlp: invalid struct tag "tail" for rlp.invalidTail1.A (must be on last field)`,
  497. },
  498. {
  499. input: "C0",
  500. ptr: new(invalidTail2),
  501. error: `rlp: invalid struct tag "tail" for rlp.invalidTail2.B (field type is not slice)`,
  502. },
  503. // struct tag "-"
  504. {
  505. input: "C20102",
  506. ptr: new(hasIgnoredField),
  507. value: hasIgnoredField{A: 1, C: 2},
  508. },
  509. // struct tag "nilList"
  510. {
  511. input: "C180",
  512. ptr: new(nilListUint),
  513. error: "rlp: wrong kind of empty value (got String, want List) for *uint, decoding into (rlp.nilListUint).X",
  514. },
  515. {
  516. input: "C1C0",
  517. ptr: new(nilListUint),
  518. value: nilListUint{},
  519. },
  520. {
  521. input: "C103",
  522. ptr: new(nilListUint),
  523. value: func() interface{} {
  524. v := uint(3)
  525. return nilListUint{X: &v}
  526. }(),
  527. },
  528. // struct tag "nilString"
  529. {
  530. input: "C1C0",
  531. ptr: new(nilStringSlice),
  532. error: "rlp: wrong kind of empty value (got List, want String) for *[]uint, decoding into (rlp.nilStringSlice).X",
  533. },
  534. {
  535. input: "C180",
  536. ptr: new(nilStringSlice),
  537. value: nilStringSlice{},
  538. },
  539. {
  540. input: "C2C103",
  541. ptr: new(nilStringSlice),
  542. value: nilStringSlice{X: &[]uint{3}},
  543. },
  544. // RawValue
  545. {input: "01", ptr: new(RawValue), value: RawValue(unhex("01"))},
  546. {input: "82FFFF", ptr: new(RawValue), value: RawValue(unhex("82FFFF"))},
  547. {input: "C20102", ptr: new([]RawValue), value: []RawValue{unhex("01"), unhex("02")}},
  548. // pointers
  549. {input: "00", ptr: new(*[]byte), value: &[]byte{0}},
  550. {input: "80", ptr: new(*uint), value: uintp(0)},
  551. {input: "C0", ptr: new(*uint), error: "rlp: expected input string or byte for uint"},
  552. {input: "07", ptr: new(*uint), value: uintp(7)},
  553. {input: "817F", ptr: new(*uint), error: "rlp: non-canonical size information for uint"},
  554. {input: "8180", ptr: new(*uint), value: uintp(0x80)},
  555. {input: "C109", ptr: new(*[]uint), value: &[]uint{9}},
  556. {input: "C58403030303", ptr: new(*[][]byte), value: &[][]byte{{3, 3, 3, 3}}},
  557. // check that input position is advanced also for empty values.
  558. {input: "C3808005", ptr: new([]*uint), value: []*uint{uintp(0), uintp(0), uintp(5)}},
  559. // interface{}
  560. {input: "00", ptr: new(interface{}), value: []byte{0}},
  561. {input: "01", ptr: new(interface{}), value: []byte{1}},
  562. {input: "80", ptr: new(interface{}), value: []byte{}},
  563. {input: "850505050505", ptr: new(interface{}), value: []byte{5, 5, 5, 5, 5}},
  564. {input: "C0", ptr: new(interface{}), value: []interface{}{}},
  565. {input: "C50183040404", ptr: new(interface{}), value: []interface{}{[]byte{1}, []byte{4, 4, 4}}},
  566. {
  567. input: "C3010203",
  568. ptr: new([]io.Reader),
  569. error: "rlp: type io.Reader is not RLP-serializable",
  570. },
  571. // fuzzer crashes
  572. {
  573. input: "c330f9c030f93030ce3030303030303030bd303030303030",
  574. ptr: new(interface{}),
  575. error: "rlp: element is larger than containing list",
  576. },
  577. }
  578. func uintp(i uint) *uint { return &i }
  579. func runTests(t *testing.T, decode func([]byte, interface{}) error) {
  580. for i, test := range decodeTests {
  581. input, err := hex.DecodeString(test.input)
  582. if err != nil {
  583. t.Errorf("test %d: invalid hex input %q", i, test.input)
  584. continue
  585. }
  586. err = decode(input, test.ptr)
  587. if err != nil && test.error == "" {
  588. t.Errorf("test %d: unexpected Decode error: %v\ndecoding into %T\ninput %q",
  589. i, err, test.ptr, test.input)
  590. continue
  591. }
  592. if test.error != "" && fmt.Sprint(err) != test.error {
  593. t.Errorf("test %d: Decode error mismatch\ngot %v\nwant %v\ndecoding into %T\ninput %q",
  594. i, err, test.error, test.ptr, test.input)
  595. continue
  596. }
  597. deref := reflect.ValueOf(test.ptr).Elem().Interface()
  598. if err == nil && !reflect.DeepEqual(deref, test.value) {
  599. t.Errorf("test %d: value mismatch\ngot %#v\nwant %#v\ndecoding into %T\ninput %q",
  600. i, deref, test.value, test.ptr, test.input)
  601. }
  602. }
  603. }
  604. func TestDecodeWithByteReader(t *testing.T) {
  605. runTests(t, func(input []byte, into interface{}) error {
  606. return Decode(bytes.NewReader(input), into)
  607. })
  608. }
  609. func testDecodeWithEncReader(t *testing.T, n int) {
  610. s := strings.Repeat("0", n)
  611. _, r, _ := EncodeToReader(s)
  612. var decoded string
  613. err := Decode(r, &decoded)
  614. if err != nil {
  615. t.Errorf("Unexpected decode error with n=%v: %v", n, err)
  616. }
  617. if decoded != s {
  618. t.Errorf("Decode mismatch with n=%v", n)
  619. }
  620. }
  621. // This is a regression test checking that decoding from encReader
  622. // works for RLP values of size 8192 bytes or more.
  623. func TestDecodeWithEncReader(t *testing.T) {
  624. testDecodeWithEncReader(t, 8188) // length with header is 8191
  625. testDecodeWithEncReader(t, 8189) // length with header is 8192
  626. }
  627. // plainReader reads from a byte slice but does not
  628. // implement ReadByte. It is also not recognized by the
  629. // size validation. This is useful to test how the decoder
  630. // behaves on a non-buffered input stream.
  631. type plainReader []byte
  632. func newPlainReader(b []byte) io.Reader {
  633. return (*plainReader)(&b)
  634. }
  635. func (r *plainReader) Read(buf []byte) (n int, err error) {
  636. if len(*r) == 0 {
  637. return 0, io.EOF
  638. }
  639. n = copy(buf, *r)
  640. *r = (*r)[n:]
  641. return n, nil
  642. }
  643. func TestDecodeWithNonByteReader(t *testing.T) {
  644. runTests(t, func(input []byte, into interface{}) error {
  645. return Decode(newPlainReader(input), into)
  646. })
  647. }
  648. func TestDecodeStreamReset(t *testing.T) {
  649. s := NewStream(nil, 0)
  650. runTests(t, func(input []byte, into interface{}) error {
  651. s.Reset(bytes.NewReader(input), 0)
  652. return s.Decode(into)
  653. })
  654. }
  655. type testDecoder struct{ called bool }
  656. func (t *testDecoder) DecodeRLP(s *Stream) error {
  657. if _, err := s.Uint(); err != nil {
  658. return err
  659. }
  660. t.called = true
  661. return nil
  662. }
  663. func TestDecodeDecoder(t *testing.T) {
  664. var s struct {
  665. T1 testDecoder
  666. T2 *testDecoder
  667. T3 **testDecoder
  668. }
  669. if err := Decode(bytes.NewReader(unhex("C3010203")), &s); err != nil {
  670. t.Fatalf("Decode error: %v", err)
  671. }
  672. if !s.T1.called {
  673. t.Errorf("DecodeRLP was not called for (non-pointer) testDecoder")
  674. }
  675. if s.T2 == nil {
  676. t.Errorf("*testDecoder has not been allocated")
  677. } else if !s.T2.called {
  678. t.Errorf("DecodeRLP was not called for *testDecoder")
  679. }
  680. if s.T3 == nil || *s.T3 == nil {
  681. t.Errorf("**testDecoder has not been allocated")
  682. } else if !(*s.T3).called {
  683. t.Errorf("DecodeRLP was not called for **testDecoder")
  684. }
  685. }
  686. func TestDecodeDecoderNilPointer(t *testing.T) {
  687. var s struct {
  688. T1 *testDecoder `rlp:"nil"`
  689. T2 *testDecoder
  690. }
  691. if err := Decode(bytes.NewReader(unhex("C2C002")), &s); err != nil {
  692. t.Fatalf("Decode error: %v", err)
  693. }
  694. if s.T1 != nil {
  695. t.Errorf("decoder T1 allocated for empty input (called: %v)", s.T1.called)
  696. }
  697. if s.T2 == nil || !s.T2.called {
  698. t.Errorf("decoder T2 not allocated/called")
  699. }
  700. }
  701. type byteDecoder byte
  702. func (bd *byteDecoder) DecodeRLP(s *Stream) error {
  703. _, err := s.Uint()
  704. *bd = 255
  705. return err
  706. }
  707. func (bd byteDecoder) called() bool {
  708. return bd == 255
  709. }
  710. // This test verifies that the byte slice/byte array logic
  711. // does not kick in for element types implementing Decoder.
  712. func TestDecoderInByteSlice(t *testing.T) {
  713. var slice []byteDecoder
  714. if err := Decode(bytes.NewReader(unhex("C101")), &slice); err != nil {
  715. t.Errorf("unexpected Decode error %v", err)
  716. } else if !slice[0].called() {
  717. t.Errorf("DecodeRLP not called for slice element")
  718. }
  719. var array [1]byteDecoder
  720. if err := Decode(bytes.NewReader(unhex("C101")), &array); err != nil {
  721. t.Errorf("unexpected Decode error %v", err)
  722. } else if !array[0].called() {
  723. t.Errorf("DecodeRLP not called for array element")
  724. }
  725. }
  726. type unencodableDecoder func()
  727. func (f *unencodableDecoder) DecodeRLP(s *Stream) error {
  728. if _, err := s.List(); err != nil {
  729. return err
  730. }
  731. if err := s.ListEnd(); err != nil {
  732. return err
  733. }
  734. *f = func() {}
  735. return nil
  736. }
  737. func TestDecoderFunc(t *testing.T) {
  738. var x func()
  739. if err := DecodeBytes([]byte{0xC0}, (*unencodableDecoder)(&x)); err != nil {
  740. t.Fatal(err)
  741. }
  742. x()
  743. }
  744. func ExampleDecode() {
  745. input, _ := hex.DecodeString("C90A1486666F6F626172")
  746. type example struct {
  747. A, B uint
  748. String string
  749. }
  750. var s example
  751. err := Decode(bytes.NewReader(input), &s)
  752. if err != nil {
  753. fmt.Printf("Error: %v\n", err)
  754. } else {
  755. fmt.Printf("Decoded value: %#v\n", s)
  756. }
  757. // Output:
  758. // Decoded value: rlp.example{A:0xa, B:0x14, String:"foobar"}
  759. }
  760. func ExampleDecode_structTagNil() {
  761. // In this example, we'll use the "nil" struct tag to change
  762. // how a pointer-typed field is decoded. The input contains an RLP
  763. // list of one element, an empty string.
  764. input := []byte{0xC1, 0x80}
  765. // This type uses the normal rules.
  766. // The empty input string is decoded as a pointer to an empty Go string.
  767. var normalRules struct {
  768. String *string
  769. }
  770. Decode(bytes.NewReader(input), &normalRules)
  771. fmt.Printf("normal: String = %q\n", *normalRules.String)
  772. // This type uses the struct tag.
  773. // The empty input string is decoded as a nil pointer.
  774. var withEmptyOK struct {
  775. String *string `rlp:"nil"`
  776. }
  777. Decode(bytes.NewReader(input), &withEmptyOK)
  778. fmt.Printf("with nil tag: String = %v\n", withEmptyOK.String)
  779. // Output:
  780. // normal: String = ""
  781. // with nil tag: String = <nil>
  782. }
  783. func ExampleStream() {
  784. input, _ := hex.DecodeString("C90A1486666F6F626172")
  785. s := NewStream(bytes.NewReader(input), 0)
  786. // Check what kind of value lies ahead
  787. kind, size, _ := s.Kind()
  788. fmt.Printf("Kind: %v size:%d\n", kind, size)
  789. // Enter the list
  790. if _, err := s.List(); err != nil {
  791. fmt.Printf("List error: %v\n", err)
  792. return
  793. }
  794. // Decode elements
  795. fmt.Println(s.Uint())
  796. fmt.Println(s.Uint())
  797. fmt.Println(s.Bytes())
  798. // Acknowledge end of list
  799. if err := s.ListEnd(); err != nil {
  800. fmt.Printf("ListEnd error: %v\n", err)
  801. }
  802. // Output:
  803. // Kind: List size:9
  804. // 10 <nil>
  805. // 20 <nil>
  806. // [102 111 111 98 97 114] <nil>
  807. }
  808. func BenchmarkDecodeUints(b *testing.B) {
  809. enc := encodeTestSlice(90000)
  810. b.SetBytes(int64(len(enc)))
  811. b.ReportAllocs()
  812. b.ResetTimer()
  813. for i := 0; i < b.N; i++ {
  814. var s []uint
  815. r := bytes.NewReader(enc)
  816. if err := Decode(r, &s); err != nil {
  817. b.Fatalf("Decode error: %v", err)
  818. }
  819. }
  820. }
  821. func BenchmarkDecodeUintsReused(b *testing.B) {
  822. enc := encodeTestSlice(100000)
  823. b.SetBytes(int64(len(enc)))
  824. b.ReportAllocs()
  825. b.ResetTimer()
  826. var s []uint
  827. for i := 0; i < b.N; i++ {
  828. r := bytes.NewReader(enc)
  829. if err := Decode(r, &s); err != nil {
  830. b.Fatalf("Decode error: %v", err)
  831. }
  832. }
  833. }
  834. func BenchmarkDecodeByteArrayStruct(b *testing.B) {
  835. enc, err := EncodeToBytes(&byteArrayStruct{})
  836. if err != nil {
  837. b.Fatal(err)
  838. }
  839. b.SetBytes(int64(len(enc)))
  840. b.ReportAllocs()
  841. b.ResetTimer()
  842. var out byteArrayStruct
  843. for i := 0; i < b.N; i++ {
  844. if err := DecodeBytes(enc, &out); err != nil {
  845. b.Fatal(err)
  846. }
  847. }
  848. }
  849. func BenchmarkDecodeBigInts(b *testing.B) {
  850. ints := make([]*big.Int, 200)
  851. for i := range ints {
  852. ints[i] = math.BigPow(2, int64(i))
  853. }
  854. enc, err := EncodeToBytes(ints)
  855. if err != nil {
  856. b.Fatal(err)
  857. }
  858. b.SetBytes(int64(len(enc)))
  859. b.ReportAllocs()
  860. b.ResetTimer()
  861. var out []*big.Int
  862. for i := 0; i < b.N; i++ {
  863. if err := DecodeBytes(enc, &out); err != nil {
  864. b.Fatal(err)
  865. }
  866. }
  867. }
  868. func encodeTestSlice(n uint) []byte {
  869. s := make([]uint, n)
  870. for i := uint(0); i < n; i++ {
  871. s[i] = i
  872. }
  873. b, err := EncodeToBytes(s)
  874. if err != nil {
  875. panic(fmt.Sprintf("encode error: %v", err))
  876. }
  877. return b
  878. }
  879. func unhex(str string) []byte {
  880. b, err := hex.DecodeString(strings.Replace(str, " ", "", -1))
  881. if err != nil {
  882. panic(fmt.Sprintf("invalid hex string: %q", str))
  883. }
  884. return b
  885. }