decode_test.go 15 KB

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