decode_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. package rlp
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "fmt"
  6. "io"
  7. "math/big"
  8. "reflect"
  9. "testing"
  10. )
  11. func TestStreamKind(t *testing.T) {
  12. tests := []struct {
  13. input string
  14. wantKind Kind
  15. wantLen uint64
  16. }{
  17. {"00", Byte, 0},
  18. {"01", Byte, 0},
  19. {"7F", Byte, 0},
  20. {"80", String, 0},
  21. {"B7", String, 55},
  22. {"B800", String, 0},
  23. {"B90400", String, 1024},
  24. {"BA000400", String, 1024},
  25. {"BB00000400", String, 1024},
  26. {"BFFFFFFFFFFFFFFFFF", String, ^uint64(0)},
  27. {"C0", List, 0},
  28. {"C8", List, 8},
  29. {"F7", List, 55},
  30. {"F800", List, 0},
  31. {"F804", List, 4},
  32. {"F90400", List, 1024},
  33. {"FFFFFFFFFFFFFFFFFF", List, ^uint64(0)},
  34. }
  35. for i, test := range tests {
  36. s := NewStream(bytes.NewReader(unhex(test.input)))
  37. kind, len, err := s.Kind()
  38. if err != nil {
  39. t.Errorf("test %d: Type returned error: %v", i, err)
  40. continue
  41. }
  42. if kind != test.wantKind {
  43. t.Errorf("test %d: kind mismatch: got %d, want %d", i, kind, test.wantKind)
  44. }
  45. if len != test.wantLen {
  46. t.Errorf("test %d: len mismatch: got %d, want %d", i, len, test.wantLen)
  47. }
  48. }
  49. }
  50. func TestNewListStream(t *testing.T) {
  51. ls := NewListStream(bytes.NewReader(unhex("0101010101")), 3)
  52. if k, size, err := ls.Kind(); k != List || size != 3 || err != nil {
  53. t.Errorf("Kind() returned (%v, %d, %v), expected (List, 3, nil)", k, size, err)
  54. }
  55. if size, err := ls.List(); size != 3 || err != nil {
  56. t.Errorf("List() returned (%d, %v), expected (3, nil)", size, err)
  57. }
  58. for i := 0; i < 3; i++ {
  59. if val, err := ls.Uint(); val != 1 || err != nil {
  60. t.Errorf("Uint() returned (%d, %v), expected (1, nil)", val, err)
  61. }
  62. }
  63. if err := ls.ListEnd(); err != nil {
  64. t.Errorf("ListEnd() returned %v, expected (3, nil)", err)
  65. }
  66. }
  67. func TestStreamErrors(t *testing.T) {
  68. type calls []string
  69. tests := []struct {
  70. string
  71. calls
  72. error
  73. }{
  74. {"", calls{"Kind"}, io.EOF},
  75. {"", calls{"List"}, io.EOF},
  76. {"", calls{"Uint"}, io.EOF},
  77. {"C0", calls{"Bytes"}, ErrExpectedString},
  78. {"C0", calls{"Uint"}, ErrExpectedString},
  79. {"81", calls{"Bytes"}, io.ErrUnexpectedEOF},
  80. {"81", calls{"Uint"}, io.ErrUnexpectedEOF},
  81. {"BFFFFFFFFFFFFFFF", calls{"Bytes"}, io.ErrUnexpectedEOF},
  82. {"89000000000000000001", calls{"Uint"}, errUintOverflow},
  83. {"00", calls{"List"}, ErrExpectedList},
  84. {"80", calls{"List"}, ErrExpectedList},
  85. {"C0", calls{"List", "Uint"}, EOL},
  86. {"C801", calls{"List", "Uint", "Uint"}, io.ErrUnexpectedEOF},
  87. {"C8C9", calls{"List", "Kind"}, ErrElemTooLarge},
  88. {"C3C2010201", calls{"List", "List", "Uint", "Uint", "ListEnd", "Uint"}, EOL},
  89. {"00", calls{"ListEnd"}, errNotInList},
  90. {"C40102", calls{"List", "Uint", "ListEnd"}, errNotAtEOL},
  91. }
  92. testfor:
  93. for i, test := range tests {
  94. s := NewStream(bytes.NewReader(unhex(test.string)))
  95. rs := reflect.ValueOf(s)
  96. for j, call := range test.calls {
  97. fval := rs.MethodByName(call)
  98. ret := fval.Call(nil)
  99. err := "<nil>"
  100. if lastret := ret[len(ret)-1].Interface(); lastret != nil {
  101. err = lastret.(error).Error()
  102. }
  103. if j == len(test.calls)-1 {
  104. if err != test.error.Error() {
  105. t.Errorf("test %d: last call (%s) error mismatch\ngot: %s\nwant: %v",
  106. i, call, err, test.error)
  107. }
  108. } else if err != "<nil>" {
  109. t.Errorf("test %d: call %d (%s) unexpected error: %q", i, j, call, err)
  110. continue testfor
  111. }
  112. }
  113. }
  114. }
  115. func TestStreamList(t *testing.T) {
  116. s := NewStream(bytes.NewReader(unhex("C80102030405060708")))
  117. len, err := s.List()
  118. if err != nil {
  119. t.Fatalf("List error: %v", err)
  120. }
  121. if len != 8 {
  122. t.Fatalf("List returned invalid length, got %d, want 8", len)
  123. }
  124. for i := uint64(1); i <= 8; i++ {
  125. v, err := s.Uint()
  126. if err != nil {
  127. t.Fatalf("Uint error: %v", err)
  128. }
  129. if i != v {
  130. t.Errorf("Uint returned wrong value, got %d, want %d", v, i)
  131. }
  132. }
  133. if _, err := s.Uint(); err != EOL {
  134. t.Errorf("Uint error mismatch, got %v, want %v", err, EOL)
  135. }
  136. if err = s.ListEnd(); err != nil {
  137. t.Fatalf("ListEnd error: %v", err)
  138. }
  139. }
  140. func TestDecodeErrors(t *testing.T) {
  141. r := bytes.NewReader(nil)
  142. if err := Decode(r, nil); err != errDecodeIntoNil {
  143. t.Errorf("Decode(r, nil) error mismatch, got %q, want %q", err, errDecodeIntoNil)
  144. }
  145. var nilptr *struct{}
  146. if err := Decode(r, nilptr); err != errDecodeIntoNil {
  147. t.Errorf("Decode(r, nilptr) error mismatch, got %q, want %q", err, errDecodeIntoNil)
  148. }
  149. if err := Decode(r, struct{}{}); err != errNoPointer {
  150. t.Errorf("Decode(r, struct{}{}) error mismatch, got %q, want %q", err, errNoPointer)
  151. }
  152. expectErr := "rlp: type chan bool is not RLP-serializable"
  153. if err := Decode(r, new(chan bool)); err == nil || err.Error() != expectErr {
  154. t.Errorf("Decode(r, new(chan bool)) error mismatch, got %q, want %q", err, expectErr)
  155. }
  156. if err := Decode(r, new(uint)); err != io.EOF {
  157. t.Errorf("Decode(r, new(int)) error mismatch, got %q, want %q", err, io.EOF)
  158. }
  159. }
  160. type decodeTest struct {
  161. input string
  162. ptr interface{}
  163. value interface{}
  164. error string
  165. }
  166. type simplestruct struct {
  167. A uint
  168. B string
  169. }
  170. type recstruct struct {
  171. I uint
  172. Child *recstruct
  173. }
  174. var (
  175. veryBigInt = big.NewInt(0).Add(
  176. big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16),
  177. big.NewInt(0xFFFF),
  178. )
  179. )
  180. var (
  181. sharedByteArray [5]byte
  182. sharedPtr = new(*uint)
  183. )
  184. var decodeTests = []decodeTest{
  185. // integers
  186. {input: "05", ptr: new(uint32), value: uint32(5)},
  187. {input: "80", ptr: new(uint32), value: uint32(0)},
  188. {input: "8105", ptr: new(uint32), value: uint32(5)},
  189. {input: "820505", ptr: new(uint32), value: uint32(0x0505)},
  190. {input: "83050505", ptr: new(uint32), value: uint32(0x050505)},
  191. {input: "8405050505", ptr: new(uint32), value: uint32(0x05050505)},
  192. {input: "850505050505", ptr: new(uint32), error: "rlp: input string too long for uint32"},
  193. {input: "C0", ptr: new(uint32), error: "rlp: expected input string or byte for uint32"},
  194. // slices
  195. {input: "C0", ptr: new([]uint), value: []uint{}},
  196. {input: "C80102030405060708", ptr: new([]uint), value: []uint{1, 2, 3, 4, 5, 6, 7, 8}},
  197. // arrays
  198. {input: "C0", ptr: new([5]uint), value: [5]uint{}},
  199. {input: "C50102030405", ptr: new([5]uint), value: [5]uint{1, 2, 3, 4, 5}},
  200. {input: "C6010203040506", ptr: new([5]uint), error: "rlp: input list has too many elements for [5]uint"},
  201. // byte slices
  202. {input: "01", ptr: new([]byte), value: []byte{1}},
  203. {input: "80", ptr: new([]byte), value: []byte{}},
  204. {input: "8D6162636465666768696A6B6C6D", ptr: new([]byte), value: []byte("abcdefghijklm")},
  205. {input: "C0", ptr: new([]byte), value: []byte{}},
  206. {input: "C3010203", ptr: new([]byte), value: []byte{1, 2, 3}},
  207. {
  208. input: "C3820102",
  209. ptr: new([]byte),
  210. error: "rlp: input string too long for uint8, decoding into ([]uint8)[0]",
  211. },
  212. // byte arrays
  213. {input: "01", ptr: new([5]byte), value: [5]byte{1}},
  214. {input: "80", ptr: new([5]byte), value: [5]byte{}},
  215. {input: "850102030405", ptr: new([5]byte), value: [5]byte{1, 2, 3, 4, 5}},
  216. {input: "C0", ptr: new([5]byte), value: [5]byte{}},
  217. {input: "C3010203", ptr: new([5]byte), value: [5]byte{1, 2, 3, 0, 0}},
  218. {
  219. input: "C3820102",
  220. ptr: new([5]byte),
  221. error: "rlp: input string too long for uint8, decoding into ([5]uint8)[0]",
  222. },
  223. {
  224. input: "86010203040506",
  225. ptr: new([5]byte),
  226. error: "rlp: input string too long for [5]uint8",
  227. },
  228. {
  229. input: "850101",
  230. ptr: new([5]byte),
  231. error: io.ErrUnexpectedEOF.Error(),
  232. },
  233. // byte array reuse (should be zeroed)
  234. {input: "850102030405", ptr: &sharedByteArray, value: [5]byte{1, 2, 3, 4, 5}},
  235. {input: "8101", ptr: &sharedByteArray, value: [5]byte{1}}, // kind: String
  236. {input: "850102030405", ptr: &sharedByteArray, value: [5]byte{1, 2, 3, 4, 5}},
  237. {input: "01", ptr: &sharedByteArray, value: [5]byte{1}}, // kind: Byte
  238. {input: "C3010203", ptr: &sharedByteArray, value: [5]byte{1, 2, 3, 0, 0}},
  239. {input: "C101", ptr: &sharedByteArray, value: [5]byte{1}}, // kind: List
  240. // zero sized byte arrays
  241. {input: "80", ptr: new([0]byte), value: [0]byte{}},
  242. {input: "C0", ptr: new([0]byte), value: [0]byte{}},
  243. {input: "01", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"},
  244. {input: "8101", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"},
  245. // strings
  246. {input: "00", ptr: new(string), value: "\000"},
  247. {input: "8D6162636465666768696A6B6C6D", ptr: new(string), value: "abcdefghijklm"},
  248. {input: "C0", ptr: new(string), error: "rlp: expected input string or byte for string"},
  249. // big ints
  250. {input: "01", ptr: new(*big.Int), value: big.NewInt(1)},
  251. {input: "89FFFFFFFFFFFFFFFFFF", ptr: new(*big.Int), value: veryBigInt},
  252. {input: "10", ptr: new(big.Int), value: *big.NewInt(16)}, // non-pointer also works
  253. {input: "C0", ptr: new(*big.Int), error: "rlp: expected input string or byte for *big.Int"},
  254. // structs
  255. {input: "C0", ptr: new(simplestruct), value: simplestruct{0, ""}},
  256. {input: "C105", ptr: new(simplestruct), value: simplestruct{5, ""}},
  257. {input: "C50583343434", ptr: new(simplestruct), value: simplestruct{5, "444"}},
  258. {
  259. input: "C501C302C103",
  260. ptr: new(recstruct),
  261. value: recstruct{1, &recstruct{2, &recstruct{3, nil}}},
  262. },
  263. {
  264. input: "C3010101",
  265. ptr: new(simplestruct),
  266. error: "rlp: input list has too many elements for rlp.simplestruct",
  267. },
  268. {
  269. input: "C501C3C00000",
  270. ptr: new(recstruct),
  271. error: "rlp: expected input string or byte for uint, decoding into (rlp.recstruct).Child.I",
  272. },
  273. // pointers
  274. {input: "00", ptr: new(*uint), value: (*uint)(nil)},
  275. {input: "80", ptr: new(*uint), value: (*uint)(nil)},
  276. {input: "C0", ptr: new(*uint), value: (*uint)(nil)},
  277. {input: "07", ptr: new(*uint), value: uintp(7)},
  278. {input: "8108", ptr: new(*uint), value: uintp(8)},
  279. {input: "C109", ptr: new(*[]uint), value: &[]uint{9}},
  280. {input: "C58403030303", ptr: new(*[][]byte), value: &[][]byte{{3, 3, 3, 3}}},
  281. // pointer should be reset to nil
  282. {input: "05", ptr: sharedPtr, value: uintp(5)},
  283. {input: "80", ptr: sharedPtr, value: (*uint)(nil)},
  284. // interface{}
  285. {input: "00", ptr: new(interface{}), value: []byte{0}},
  286. {input: "01", ptr: new(interface{}), value: []byte{1}},
  287. {input: "80", ptr: new(interface{}), value: []byte{}},
  288. {input: "850505050505", ptr: new(interface{}), value: []byte{5, 5, 5, 5, 5}},
  289. {input: "C0", ptr: new(interface{}), value: []interface{}{}},
  290. {input: "C50183040404", ptr: new(interface{}), value: []interface{}{[]byte{1}, []byte{4, 4, 4}}},
  291. }
  292. func uintp(i uint) *uint { return &i }
  293. func runTests(t *testing.T, decode func([]byte, interface{}) error) {
  294. for i, test := range decodeTests {
  295. input, err := hex.DecodeString(test.input)
  296. if err != nil {
  297. t.Errorf("test %d: invalid hex input %q", i, test.input)
  298. continue
  299. }
  300. err = decode(input, test.ptr)
  301. if err != nil && test.error == "" {
  302. t.Errorf("test %d: unexpected Decode error: %v\ndecoding into %T\ninput %q",
  303. i, err, test.ptr, test.input)
  304. continue
  305. }
  306. if test.error != "" && fmt.Sprint(err) != test.error {
  307. t.Errorf("test %d: Decode error mismatch\ngot %v\nwant %v\ndecoding into %T\ninput %q",
  308. i, err, test.error, test.ptr, test.input)
  309. continue
  310. }
  311. deref := reflect.ValueOf(test.ptr).Elem().Interface()
  312. if err == nil && !reflect.DeepEqual(deref, test.value) {
  313. t.Errorf("test %d: value mismatch\ngot %#v\nwant %#v\ndecoding into %T\ninput %q",
  314. i, deref, test.value, test.ptr, test.input)
  315. }
  316. }
  317. }
  318. func TestDecodeWithByteReader(t *testing.T) {
  319. runTests(t, func(input []byte, into interface{}) error {
  320. return Decode(bytes.NewReader(input), into)
  321. })
  322. }
  323. // dumbReader reads from a byte slice but does not
  324. // implement ReadByte.
  325. type dumbReader []byte
  326. func (r *dumbReader) Read(buf []byte) (n int, err error) {
  327. if len(*r) == 0 {
  328. return 0, io.EOF
  329. }
  330. n = copy(buf, *r)
  331. *r = (*r)[n:]
  332. return n, nil
  333. }
  334. func TestDecodeWithNonByteReader(t *testing.T) {
  335. runTests(t, func(input []byte, into interface{}) error {
  336. r := dumbReader(input)
  337. return Decode(&r, into)
  338. })
  339. }
  340. func TestDecodeStreamReset(t *testing.T) {
  341. s := NewStream(nil)
  342. runTests(t, func(input []byte, into interface{}) error {
  343. s.Reset(bytes.NewReader(input))
  344. return s.Decode(into)
  345. })
  346. }
  347. type testDecoder struct{ called bool }
  348. func (t *testDecoder) DecodeRLP(s *Stream) error {
  349. if _, err := s.Uint(); err != nil {
  350. return err
  351. }
  352. t.called = true
  353. return nil
  354. }
  355. func TestDecodeDecoder(t *testing.T) {
  356. var s struct {
  357. T1 testDecoder
  358. T2 *testDecoder
  359. T3 **testDecoder
  360. }
  361. if err := Decode(bytes.NewReader(unhex("C3010203")), &s); err != nil {
  362. t.Fatalf("Decode error: %v", err)
  363. }
  364. if !s.T1.called {
  365. t.Errorf("DecodeRLP was not called for (non-pointer) testDecoder")
  366. }
  367. if s.T2 == nil {
  368. t.Errorf("*testDecoder has not been allocated")
  369. } else if !s.T2.called {
  370. t.Errorf("DecodeRLP was not called for *testDecoder")
  371. }
  372. if s.T3 == nil || *s.T3 == nil {
  373. t.Errorf("**testDecoder has not been allocated")
  374. } else if !(*s.T3).called {
  375. t.Errorf("DecodeRLP was not called for **testDecoder")
  376. }
  377. }
  378. type byteDecoder byte
  379. func (bd *byteDecoder) DecodeRLP(s *Stream) error {
  380. _, err := s.Uint()
  381. *bd = 255
  382. return err
  383. }
  384. func (bd byteDecoder) called() bool {
  385. return bd == 255
  386. }
  387. // This test verifies that the byte slice/byte array logic
  388. // does not kick in for element types implementing Decoder.
  389. func TestDecoderInByteSlice(t *testing.T) {
  390. var slice []byteDecoder
  391. if err := Decode(bytes.NewReader(unhex("C101")), &slice); err != nil {
  392. t.Errorf("unexpected Decode error %v", err)
  393. } else if !slice[0].called() {
  394. t.Errorf("DecodeRLP not called for slice element")
  395. }
  396. var array [1]byteDecoder
  397. if err := Decode(bytes.NewReader(unhex("C101")), &array); err != nil {
  398. t.Errorf("unexpected Decode error %v", err)
  399. } else if !array[0].called() {
  400. t.Errorf("DecodeRLP not called for array element")
  401. }
  402. }
  403. func ExampleDecode() {
  404. input, _ := hex.DecodeString("C90A1486666F6F626172")
  405. type example struct {
  406. A, B uint
  407. private uint // private fields are ignored
  408. String string
  409. }
  410. var s example
  411. err := Decode(bytes.NewReader(input), &s)
  412. if err != nil {
  413. fmt.Printf("Error: %v\n", err)
  414. } else {
  415. fmt.Printf("Decoded value: %#v\n", s)
  416. }
  417. // Output:
  418. // Decoded value: rlp.example{A:0xa, B:0x14, private:0x0, String:"foobar"}
  419. }
  420. func ExampleStream() {
  421. input, _ := hex.DecodeString("C90A1486666F6F626172")
  422. s := NewStream(bytes.NewReader(input))
  423. // Check what kind of value lies ahead
  424. kind, size, _ := s.Kind()
  425. fmt.Printf("Kind: %v size:%d\n", kind, size)
  426. // Enter the list
  427. if _, err := s.List(); err != nil {
  428. fmt.Printf("List error: %v\n", err)
  429. return
  430. }
  431. // Decode elements
  432. fmt.Println(s.Uint())
  433. fmt.Println(s.Uint())
  434. fmt.Println(s.Bytes())
  435. // Acknowledge end of list
  436. if err := s.ListEnd(); err != nil {
  437. fmt.Printf("ListEnd error: %v\n", err)
  438. }
  439. // Output:
  440. // Kind: List size:9
  441. // 10 <nil>
  442. // 20 <nil>
  443. // [102 111 111 98 97 114] <nil>
  444. }
  445. func BenchmarkDecode(b *testing.B) {
  446. enc := encodeTestSlice(90000)
  447. b.SetBytes(int64(len(enc)))
  448. b.ReportAllocs()
  449. b.ResetTimer()
  450. for i := 0; i < b.N; i++ {
  451. var s []uint
  452. r := bytes.NewReader(enc)
  453. if err := Decode(r, &s); err != nil {
  454. b.Fatalf("Decode error: %v", err)
  455. }
  456. }
  457. }
  458. func BenchmarkDecodeIntSliceReuse(b *testing.B) {
  459. enc := encodeTestSlice(100000)
  460. b.SetBytes(int64(len(enc)))
  461. b.ReportAllocs()
  462. b.ResetTimer()
  463. var s []uint
  464. for i := 0; i < b.N; i++ {
  465. r := bytes.NewReader(enc)
  466. if err := Decode(r, &s); err != nil {
  467. b.Fatalf("Decode error: %v", err)
  468. }
  469. }
  470. }
  471. func encodeTestSlice(n uint) []byte {
  472. s := make([]uint, n)
  473. for i := uint(0); i < n; i++ {
  474. s[i] = i
  475. }
  476. b, err := EncodeToBytes(s)
  477. if err != nil {
  478. panic(fmt.Sprintf("encode error: %v", err))
  479. }
  480. return b
  481. }
  482. func unhex(str string) []byte {
  483. b, err := hex.DecodeString(str)
  484. if err != nil {
  485. panic(fmt.Sprintf("invalid hex string: %q", str))
  486. }
  487. return b
  488. }