decode_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package rlp
  17. import (
  18. "bytes"
  19. "encoding/hex"
  20. "fmt"
  21. "io"
  22. "math/big"
  23. "reflect"
  24. "testing"
  25. )
  26. func TestStreamKind(t *testing.T) {
  27. tests := []struct {
  28. input string
  29. wantKind Kind
  30. wantLen uint64
  31. }{
  32. {"00", Byte, 0},
  33. {"01", Byte, 0},
  34. {"7F", Byte, 0},
  35. {"80", String, 0},
  36. {"B7", String, 55},
  37. {"B90400", String, 1024},
  38. {"BFFFFFFFFFFFFFFFFF", String, ^uint64(0)},
  39. {"C0", List, 0},
  40. {"C8", List, 8},
  41. {"F7", List, 55},
  42. {"F90400", List, 1024},
  43. {"FFFFFFFFFFFFFFFFFF", List, ^uint64(0)},
  44. }
  45. for i, test := range tests {
  46. // using plainReader to inhibit input limit errors.
  47. s := NewStream(newPlainReader(unhex(test.input)), 0)
  48. kind, len, err := s.Kind()
  49. if err != nil {
  50. t.Errorf("test %d: Kind returned error: %v", i, err)
  51. continue
  52. }
  53. if kind != test.wantKind {
  54. t.Errorf("test %d: kind mismatch: got %d, want %d", i, kind, test.wantKind)
  55. }
  56. if len != test.wantLen {
  57. t.Errorf("test %d: len mismatch: got %d, want %d", i, len, test.wantLen)
  58. }
  59. }
  60. }
  61. func TestNewListStream(t *testing.T) {
  62. ls := NewListStream(bytes.NewReader(unhex("0101010101")), 3)
  63. if k, size, err := ls.Kind(); k != List || size != 3 || err != nil {
  64. t.Errorf("Kind() returned (%v, %d, %v), expected (List, 3, nil)", k, size, err)
  65. }
  66. if size, err := ls.List(); size != 3 || err != nil {
  67. t.Errorf("List() returned (%d, %v), expected (3, nil)", size, err)
  68. }
  69. for i := 0; i < 3; i++ {
  70. if val, err := ls.Uint(); val != 1 || err != nil {
  71. t.Errorf("Uint() returned (%d, %v), expected (1, nil)", val, err)
  72. }
  73. }
  74. if err := ls.ListEnd(); err != nil {
  75. t.Errorf("ListEnd() returned %v, expected (3, nil)", err)
  76. }
  77. }
  78. func TestStreamErrors(t *testing.T) {
  79. withoutInputLimit := func(b []byte) *Stream {
  80. return NewStream(newPlainReader(b), 0)
  81. }
  82. withCustomInputLimit := func(limit uint64) func([]byte) *Stream {
  83. return func(b []byte) *Stream {
  84. return NewStream(bytes.NewReader(b), limit)
  85. }
  86. }
  87. type calls []string
  88. tests := []struct {
  89. string
  90. calls
  91. newStream func([]byte) *Stream // uses bytes.Reader if nil
  92. error error
  93. }{
  94. {"C0", calls{"Bytes"}, nil, ErrExpectedString},
  95. {"C0", calls{"Uint"}, nil, ErrExpectedString},
  96. {"89000000000000000001", calls{"Uint"}, nil, errUintOverflow},
  97. {"00", calls{"List"}, nil, ErrExpectedList},
  98. {"80", calls{"List"}, nil, ErrExpectedList},
  99. {"C0", calls{"List", "Uint"}, nil, EOL},
  100. {"C8C9010101010101010101", calls{"List", "Kind"}, nil, ErrElemTooLarge},
  101. {"C3C2010201", calls{"List", "List", "Uint", "Uint", "ListEnd", "Uint"}, nil, EOL},
  102. {"00", calls{"ListEnd"}, nil, errNotInList},
  103. {"C401020304", calls{"List", "Uint", "ListEnd"}, nil, errNotAtEOL},
  104. // Non-canonical integers (e.g. leading zero bytes).
  105. {"00", calls{"Uint"}, nil, ErrCanonInt},
  106. {"820002", calls{"Uint"}, nil, ErrCanonInt},
  107. {"8133", calls{"Uint"}, nil, ErrCanonSize},
  108. {"8156", calls{"Uint"}, nil, nil},
  109. // Size tags must use the smallest possible encoding.
  110. // Leading zero bytes in the size tag are also rejected.
  111. {"8100", calls{"Uint"}, nil, ErrCanonSize},
  112. {"8100", calls{"Bytes"}, nil, ErrCanonSize},
  113. {"B800", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
  114. {"B90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
  115. {"B90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
  116. {"BA0002FFFF", calls{"Bytes"}, withoutInputLimit, ErrCanonSize},
  117. {"F800", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
  118. {"F90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
  119. {"F90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize},
  120. {"FA0002FFFF", calls{"List"}, withoutInputLimit, ErrCanonSize},
  121. // Expected EOF
  122. {"", calls{"Kind"}, nil, io.EOF},
  123. {"", calls{"Uint"}, nil, io.EOF},
  124. {"", calls{"List"}, nil, io.EOF},
  125. {"8158", calls{"Uint", "Uint"}, nil, io.EOF},
  126. {"C0", calls{"List", "ListEnd", "List"}, nil, io.EOF},
  127. {"", calls{"List"}, withoutInputLimit, io.EOF},
  128. {"8158", calls{"Uint", "Uint"}, withoutInputLimit, io.EOF},
  129. {"C0", calls{"List", "ListEnd", "List"}, withoutInputLimit, io.EOF},
  130. // Input limit errors.
  131. {"81", calls{"Bytes"}, nil, ErrValueTooLarge},
  132. {"81", calls{"Uint"}, nil, ErrValueTooLarge},
  133. {"81", calls{"Raw"}, nil, ErrValueTooLarge},
  134. {"BFFFFFFFFFFFFFFFFFFF", calls{"Bytes"}, nil, ErrValueTooLarge},
  135. {"C801", calls{"List"}, nil, ErrValueTooLarge},
  136. // Test for list element size check overflow.
  137. {"CD04040404FFFFFFFFFFFFFFFFFF0303", calls{"List", "Uint", "Uint", "Uint", "Uint", "List"}, nil, ErrElemTooLarge},
  138. // Test for input limit overflow. Since we are counting the limit
  139. // down toward zero in Stream.remaining, reading too far can overflow
  140. // remaining to a large value, effectively disabling the limit.
  141. {"C40102030401", calls{"Raw", "Uint"}, withCustomInputLimit(5), io.EOF},
  142. {"C4010203048158", calls{"Raw", "Uint"}, withCustomInputLimit(6), ErrValueTooLarge},
  143. // Check that the same calls are fine without a limit.
  144. {"C40102030401", calls{"Raw", "Uint"}, withoutInputLimit, nil},
  145. {"C4010203048158", calls{"Raw", "Uint"}, withoutInputLimit, nil},
  146. // Unexpected EOF. This only happens when there is
  147. // no input limit, so the reader needs to be 'dumbed down'.
  148. {"81", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF},
  149. {"81", calls{"Uint"}, withoutInputLimit, io.ErrUnexpectedEOF},
  150. {"BFFFFFFFFFFFFFFF", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF},
  151. {"C801", calls{"List", "Uint", "Uint"}, withoutInputLimit, io.ErrUnexpectedEOF},
  152. // This test verifies that the input position is advanced
  153. // correctly when calling Bytes for empty strings. Kind can be called
  154. // any number of times in between and doesn't advance.
  155. {"C3808080", calls{
  156. "List", // enter the list
  157. "Bytes", // past first element
  158. "Kind", "Kind", "Kind", // this shouldn't advance
  159. "Bytes", // past second element
  160. "Kind", "Kind", // can't hurt to try
  161. "Bytes", // past final element
  162. "Bytes", // this one should fail
  163. }, nil, EOL},
  164. }
  165. testfor:
  166. for i, test := range tests {
  167. if test.newStream == nil {
  168. test.newStream = func(b []byte) *Stream { return NewStream(bytes.NewReader(b), 0) }
  169. }
  170. s := test.newStream(unhex(test.string))
  171. rs := reflect.ValueOf(s)
  172. for j, call := range test.calls {
  173. fval := rs.MethodByName(call)
  174. ret := fval.Call(nil)
  175. err := "<nil>"
  176. if lastret := ret[len(ret)-1].Interface(); lastret != nil {
  177. err = lastret.(error).Error()
  178. }
  179. if j == len(test.calls)-1 {
  180. want := "<nil>"
  181. if test.error != nil {
  182. want = test.error.Error()
  183. }
  184. if err != want {
  185. t.Log(test)
  186. t.Errorf("test %d: last call (%s) error mismatch\ngot: %s\nwant: %s",
  187. i, call, err, test.error)
  188. }
  189. } else if err != "<nil>" {
  190. t.Log(test)
  191. t.Errorf("test %d: call %d (%s) unexpected error: %q", i, j, call, err)
  192. continue testfor
  193. }
  194. }
  195. }
  196. }
  197. func TestStreamList(t *testing.T) {
  198. s := NewStream(bytes.NewReader(unhex("C80102030405060708")), 0)
  199. len, err := s.List()
  200. if err != nil {
  201. t.Fatalf("List error: %v", err)
  202. }
  203. if len != 8 {
  204. t.Fatalf("List returned invalid length, got %d, want 8", len)
  205. }
  206. for i := uint64(1); i <= 8; i++ {
  207. v, err := s.Uint()
  208. if err != nil {
  209. t.Fatalf("Uint error: %v", err)
  210. }
  211. if i != v {
  212. t.Errorf("Uint returned wrong value, got %d, want %d", v, i)
  213. }
  214. }
  215. if _, err := s.Uint(); err != EOL {
  216. t.Errorf("Uint error mismatch, got %v, want %v", err, EOL)
  217. }
  218. if err = s.ListEnd(); err != nil {
  219. t.Fatalf("ListEnd error: %v", err)
  220. }
  221. }
  222. func TestStreamRaw(t *testing.T) {
  223. s := NewStream(bytes.NewReader(unhex("C58401010101")), 0)
  224. s.List()
  225. want := unhex("8401010101")
  226. raw, err := s.Raw()
  227. if err != nil {
  228. t.Fatal(err)
  229. }
  230. if !bytes.Equal(want, raw) {
  231. t.Errorf("raw mismatch: got %x, want %x", raw, want)
  232. }
  233. }
  234. func TestDecodeErrors(t *testing.T) {
  235. r := bytes.NewReader(nil)
  236. if err := Decode(r, nil); err != errDecodeIntoNil {
  237. t.Errorf("Decode(r, nil) error mismatch, got %q, want %q", err, errDecodeIntoNil)
  238. }
  239. var nilptr *struct{}
  240. if err := Decode(r, nilptr); err != errDecodeIntoNil {
  241. t.Errorf("Decode(r, nilptr) error mismatch, got %q, want %q", err, errDecodeIntoNil)
  242. }
  243. if err := Decode(r, struct{}{}); err != errNoPointer {
  244. t.Errorf("Decode(r, struct{}{}) error mismatch, got %q, want %q", err, errNoPointer)
  245. }
  246. expectErr := "rlp: type chan bool is not RLP-serializable"
  247. if err := Decode(r, new(chan bool)); err == nil || err.Error() != expectErr {
  248. t.Errorf("Decode(r, new(chan bool)) error mismatch, got %q, want %q", err, expectErr)
  249. }
  250. if err := Decode(r, new(uint)); err != io.EOF {
  251. t.Errorf("Decode(r, new(int)) error mismatch, got %q, want %q", err, io.EOF)
  252. }
  253. }
  254. type decodeTest struct {
  255. input string
  256. ptr interface{}
  257. value interface{}
  258. error string
  259. }
  260. type simplestruct struct {
  261. A uint
  262. B string
  263. }
  264. type recstruct struct {
  265. I uint
  266. Child *recstruct `rlp:"nil"`
  267. }
  268. var (
  269. veryBigInt = big.NewInt(0).Add(
  270. big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16),
  271. big.NewInt(0xFFFF),
  272. )
  273. )
  274. var decodeTests = []decodeTest{
  275. // integers
  276. {input: "05", ptr: new(uint32), value: uint32(5)},
  277. {input: "80", ptr: new(uint32), value: uint32(0)},
  278. {input: "820505", ptr: new(uint32), value: uint32(0x0505)},
  279. {input: "83050505", ptr: new(uint32), value: uint32(0x050505)},
  280. {input: "8405050505", ptr: new(uint32), value: uint32(0x05050505)},
  281. {input: "850505050505", ptr: new(uint32), error: "rlp: input string too long for uint32"},
  282. {input: "C0", ptr: new(uint32), error: "rlp: expected input string or byte for uint32"},
  283. {input: "00", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"},
  284. {input: "8105", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"},
  285. {input: "820004", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"},
  286. {input: "B8020004", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"},
  287. // slices
  288. {input: "C0", ptr: new([]uint), value: []uint{}},
  289. {input: "C80102030405060708", ptr: new([]uint), value: []uint{1, 2, 3, 4, 5, 6, 7, 8}},
  290. {input: "F8020004", ptr: new([]uint), error: "rlp: non-canonical size information for []uint"},
  291. // arrays
  292. {input: "C50102030405", ptr: new([5]uint), value: [5]uint{1, 2, 3, 4, 5}},
  293. {input: "C0", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"},
  294. {input: "C102", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"},
  295. {input: "C6010203040506", ptr: new([5]uint), error: "rlp: input list has too many elements for [5]uint"},
  296. {input: "F8020004", ptr: new([5]uint), error: "rlp: non-canonical size information for [5]uint"},
  297. // zero sized arrays
  298. {input: "C0", ptr: new([0]uint), value: [0]uint{}},
  299. {input: "C101", ptr: new([0]uint), error: "rlp: input list has too many elements for [0]uint"},
  300. // byte slices
  301. {input: "01", ptr: new([]byte), value: []byte{1}},
  302. {input: "80", ptr: new([]byte), value: []byte{}},
  303. {input: "8D6162636465666768696A6B6C6D", ptr: new([]byte), value: []byte("abcdefghijklm")},
  304. {input: "C0", ptr: new([]byte), error: "rlp: expected input string or byte for []uint8"},
  305. {input: "8105", ptr: new([]byte), error: "rlp: non-canonical size information for []uint8"},
  306. // byte arrays
  307. {input: "02", ptr: new([1]byte), value: [1]byte{2}},
  308. {input: "850102030405", ptr: new([5]byte), value: [5]byte{1, 2, 3, 4, 5}},
  309. // byte array errors
  310. {input: "02", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"},
  311. {input: "80", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"},
  312. {input: "820000", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"},
  313. {input: "C0", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"},
  314. {input: "C3010203", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"},
  315. {input: "86010203040506", ptr: new([5]byte), error: "rlp: input string too long for [5]uint8"},
  316. {input: "8105", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"},
  317. // zero sized byte arrays
  318. {input: "80", ptr: new([0]byte), value: [0]byte{}},
  319. {input: "01", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"},
  320. {input: "8101", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"},
  321. // strings
  322. {input: "00", ptr: new(string), value: "\000"},
  323. {input: "8D6162636465666768696A6B6C6D", ptr: new(string), value: "abcdefghijklm"},
  324. {input: "C0", ptr: new(string), error: "rlp: expected input string or byte for string"},
  325. // big ints
  326. {input: "01", ptr: new(*big.Int), value: big.NewInt(1)},
  327. {input: "89FFFFFFFFFFFFFFFFFF", ptr: new(*big.Int), value: veryBigInt},
  328. {input: "10", ptr: new(big.Int), value: *big.NewInt(16)}, // non-pointer also works
  329. {input: "C0", ptr: new(*big.Int), error: "rlp: expected input string or byte for *big.Int"},
  330. {input: "820001", ptr: new(big.Int), error: "rlp: non-canonical integer (leading zero bytes) for *big.Int"},
  331. {input: "8105", ptr: new(big.Int), error: "rlp: non-canonical size information for *big.Int"},
  332. // structs
  333. {
  334. input: "C50583343434",
  335. ptr: new(simplestruct),
  336. value: simplestruct{5, "444"},
  337. },
  338. {
  339. input: "C601C402C203C0",
  340. ptr: new(recstruct),
  341. value: recstruct{1, &recstruct{2, &recstruct{3, nil}}},
  342. },
  343. // struct errors
  344. {
  345. input: "C0",
  346. ptr: new(simplestruct),
  347. error: "rlp: too few elements for rlp.simplestruct",
  348. },
  349. {
  350. input: "C105",
  351. ptr: new(simplestruct),
  352. error: "rlp: too few elements for rlp.simplestruct",
  353. },
  354. {
  355. input: "C7C50583343434C0",
  356. ptr: new([]*simplestruct),
  357. error: "rlp: too few elements for rlp.simplestruct, decoding into ([]*rlp.simplestruct)[1]",
  358. },
  359. {
  360. input: "83222222",
  361. ptr: new(simplestruct),
  362. error: "rlp: expected input list for rlp.simplestruct",
  363. },
  364. {
  365. input: "C3010101",
  366. ptr: new(simplestruct),
  367. error: "rlp: input list has too many elements for rlp.simplestruct",
  368. },
  369. {
  370. input: "C501C3C00000",
  371. ptr: new(recstruct),
  372. error: "rlp: expected input string or byte for uint, decoding into (rlp.recstruct).Child.I",
  373. },
  374. // pointers
  375. {input: "00", ptr: new(*[]byte), value: &[]byte{0}},
  376. {input: "80", ptr: new(*uint), value: uintp(0)},
  377. {input: "C0", ptr: new(*uint), error: "rlp: expected input string or byte for uint"},
  378. {input: "07", ptr: new(*uint), value: uintp(7)},
  379. {input: "8158", ptr: new(*uint), value: uintp(0x58)},
  380. {input: "C109", ptr: new(*[]uint), value: &[]uint{9}},
  381. {input: "C58403030303", ptr: new(*[][]byte), value: &[][]byte{{3, 3, 3, 3}}},
  382. // check that input position is advanced also for empty values.
  383. {input: "C3808005", ptr: new([]*uint), value: []*uint{uintp(0), uintp(0), uintp(5)}},
  384. // interface{}
  385. {input: "00", ptr: new(interface{}), value: []byte{0}},
  386. {input: "01", ptr: new(interface{}), value: []byte{1}},
  387. {input: "80", ptr: new(interface{}), value: []byte{}},
  388. {input: "850505050505", ptr: new(interface{}), value: []byte{5, 5, 5, 5, 5}},
  389. {input: "C0", ptr: new(interface{}), value: []interface{}{}},
  390. {input: "C50183040404", ptr: new(interface{}), value: []interface{}{[]byte{1}, []byte{4, 4, 4}}},
  391. {
  392. input: "C3010203",
  393. ptr: new([]io.Reader),
  394. error: "rlp: type io.Reader is not RLP-serializable",
  395. },
  396. // fuzzer crashes
  397. {
  398. input: "c330f9c030f93030ce3030303030303030bd303030303030",
  399. ptr: new(interface{}),
  400. error: "rlp: element is larger than containing list",
  401. },
  402. }
  403. func uintp(i uint) *uint { return &i }
  404. func runTests(t *testing.T, decode func([]byte, interface{}) error) {
  405. for i, test := range decodeTests {
  406. input, err := hex.DecodeString(test.input)
  407. if err != nil {
  408. t.Errorf("test %d: invalid hex input %q", i, test.input)
  409. continue
  410. }
  411. err = decode(input, test.ptr)
  412. if err != nil && test.error == "" {
  413. t.Errorf("test %d: unexpected Decode error: %v\ndecoding into %T\ninput %q",
  414. i, err, test.ptr, test.input)
  415. continue
  416. }
  417. if test.error != "" && fmt.Sprint(err) != test.error {
  418. t.Errorf("test %d: Decode error mismatch\ngot %v\nwant %v\ndecoding into %T\ninput %q",
  419. i, err, test.error, test.ptr, test.input)
  420. continue
  421. }
  422. deref := reflect.ValueOf(test.ptr).Elem().Interface()
  423. if err == nil && !reflect.DeepEqual(deref, test.value) {
  424. t.Errorf("test %d: value mismatch\ngot %#v\nwant %#v\ndecoding into %T\ninput %q",
  425. i, deref, test.value, test.ptr, test.input)
  426. }
  427. }
  428. }
  429. func TestDecodeWithByteReader(t *testing.T) {
  430. runTests(t, func(input []byte, into interface{}) error {
  431. return Decode(bytes.NewReader(input), into)
  432. })
  433. }
  434. // plainReader reads from a byte slice but does not
  435. // implement ReadByte. It is also not recognized by the
  436. // size validation. This is useful to test how the decoder
  437. // behaves on a non-buffered input stream.
  438. type plainReader []byte
  439. func newPlainReader(b []byte) io.Reader {
  440. return (*plainReader)(&b)
  441. }
  442. func (r *plainReader) Read(buf []byte) (n int, err error) {
  443. if len(*r) == 0 {
  444. return 0, io.EOF
  445. }
  446. n = copy(buf, *r)
  447. *r = (*r)[n:]
  448. return n, nil
  449. }
  450. func TestDecodeWithNonByteReader(t *testing.T) {
  451. runTests(t, func(input []byte, into interface{}) error {
  452. return Decode(newPlainReader(input), into)
  453. })
  454. }
  455. func TestDecodeStreamReset(t *testing.T) {
  456. s := NewStream(nil, 0)
  457. runTests(t, func(input []byte, into interface{}) error {
  458. s.Reset(bytes.NewReader(input), 0)
  459. return s.Decode(into)
  460. })
  461. }
  462. type testDecoder struct{ called bool }
  463. func (t *testDecoder) DecodeRLP(s *Stream) error {
  464. if _, err := s.Uint(); err != nil {
  465. return err
  466. }
  467. t.called = true
  468. return nil
  469. }
  470. func TestDecodeDecoder(t *testing.T) {
  471. var s struct {
  472. T1 testDecoder
  473. T2 *testDecoder
  474. T3 **testDecoder
  475. }
  476. if err := Decode(bytes.NewReader(unhex("C3010203")), &s); err != nil {
  477. t.Fatalf("Decode error: %v", err)
  478. }
  479. if !s.T1.called {
  480. t.Errorf("DecodeRLP was not called for (non-pointer) testDecoder")
  481. }
  482. if s.T2 == nil {
  483. t.Errorf("*testDecoder has not been allocated")
  484. } else if !s.T2.called {
  485. t.Errorf("DecodeRLP was not called for *testDecoder")
  486. }
  487. if s.T3 == nil || *s.T3 == nil {
  488. t.Errorf("**testDecoder has not been allocated")
  489. } else if !(*s.T3).called {
  490. t.Errorf("DecodeRLP was not called for **testDecoder")
  491. }
  492. }
  493. type byteDecoder byte
  494. func (bd *byteDecoder) DecodeRLP(s *Stream) error {
  495. _, err := s.Uint()
  496. *bd = 255
  497. return err
  498. }
  499. func (bd byteDecoder) called() bool {
  500. return bd == 255
  501. }
  502. // This test verifies that the byte slice/byte array logic
  503. // does not kick in for element types implementing Decoder.
  504. func TestDecoderInByteSlice(t *testing.T) {
  505. var slice []byteDecoder
  506. if err := Decode(bytes.NewReader(unhex("C101")), &slice); err != nil {
  507. t.Errorf("unexpected Decode error %v", err)
  508. } else if !slice[0].called() {
  509. t.Errorf("DecodeRLP not called for slice element")
  510. }
  511. var array [1]byteDecoder
  512. if err := Decode(bytes.NewReader(unhex("C101")), &array); err != nil {
  513. t.Errorf("unexpected Decode error %v", err)
  514. } else if !array[0].called() {
  515. t.Errorf("DecodeRLP not called for array element")
  516. }
  517. }
  518. func ExampleDecode() {
  519. input, _ := hex.DecodeString("C90A1486666F6F626172")
  520. type example struct {
  521. A, B uint
  522. private uint // private fields are ignored
  523. String string
  524. }
  525. var s example
  526. err := Decode(bytes.NewReader(input), &s)
  527. if err != nil {
  528. fmt.Printf("Error: %v\n", err)
  529. } else {
  530. fmt.Printf("Decoded value: %#v\n", s)
  531. }
  532. // Output:
  533. // Decoded value: rlp.example{A:0xa, B:0x14, private:0x0, String:"foobar"}
  534. }
  535. func ExampleDecode_structTagNil() {
  536. // In this example, we'll use the "nil" struct tag to change
  537. // how a pointer-typed field is decoded. The input contains an RLP
  538. // list of one element, an empty string.
  539. input := []byte{0xC1, 0x80}
  540. // This type uses the normal rules.
  541. // The empty input string is decoded as a pointer to an empty Go string.
  542. var normalRules struct {
  543. String *string
  544. }
  545. Decode(bytes.NewReader(input), &normalRules)
  546. fmt.Printf("normal: String = %q\n", *normalRules.String)
  547. // This type uses the struct tag.
  548. // The empty input string is decoded as a nil pointer.
  549. var withEmptyOK struct {
  550. String *string `rlp:"nil"`
  551. }
  552. Decode(bytes.NewReader(input), &withEmptyOK)
  553. fmt.Printf("with nil tag: String = %v\n", withEmptyOK.String)
  554. // Output:
  555. // normal: String = ""
  556. // with nil tag: String = <nil>
  557. }
  558. func ExampleStream() {
  559. input, _ := hex.DecodeString("C90A1486666F6F626172")
  560. s := NewStream(bytes.NewReader(input), 0)
  561. // Check what kind of value lies ahead
  562. kind, size, _ := s.Kind()
  563. fmt.Printf("Kind: %v size:%d\n", kind, size)
  564. // Enter the list
  565. if _, err := s.List(); err != nil {
  566. fmt.Printf("List error: %v\n", err)
  567. return
  568. }
  569. // Decode elements
  570. fmt.Println(s.Uint())
  571. fmt.Println(s.Uint())
  572. fmt.Println(s.Bytes())
  573. // Acknowledge end of list
  574. if err := s.ListEnd(); err != nil {
  575. fmt.Printf("ListEnd error: %v\n", err)
  576. }
  577. // Output:
  578. // Kind: List size:9
  579. // 10 <nil>
  580. // 20 <nil>
  581. // [102 111 111 98 97 114] <nil>
  582. }
  583. func BenchmarkDecode(b *testing.B) {
  584. enc := encodeTestSlice(90000)
  585. b.SetBytes(int64(len(enc)))
  586. b.ReportAllocs()
  587. b.ResetTimer()
  588. for i := 0; i < b.N; i++ {
  589. var s []uint
  590. r := bytes.NewReader(enc)
  591. if err := Decode(r, &s); err != nil {
  592. b.Fatalf("Decode error: %v", err)
  593. }
  594. }
  595. }
  596. func BenchmarkDecodeIntSliceReuse(b *testing.B) {
  597. enc := encodeTestSlice(100000)
  598. b.SetBytes(int64(len(enc)))
  599. b.ReportAllocs()
  600. b.ResetTimer()
  601. var s []uint
  602. for i := 0; i < b.N; i++ {
  603. r := bytes.NewReader(enc)
  604. if err := Decode(r, &s); err != nil {
  605. b.Fatalf("Decode error: %v", err)
  606. }
  607. }
  608. }
  609. func encodeTestSlice(n uint) []byte {
  610. s := make([]uint, n)
  611. for i := uint(0); i < n; i++ {
  612. s[i] = i
  613. }
  614. b, err := EncodeToBytes(s)
  615. if err != nil {
  616. panic(fmt.Sprintf("encode error: %v", err))
  617. }
  618. return b
  619. }
  620. func unhex(str string) []byte {
  621. b, err := hex.DecodeString(str)
  622. if err != nil {
  623. panic(fmt.Sprintf("invalid hex string: %q", str))
  624. }
  625. return b
  626. }