github.com/klaytn/klaytn@v1.10.2/rlp/decode_test.go (about) 1 // Modifications Copyright 2022 The klaytn Authors 2 // Copyright 2014 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-ethereum library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 // This file is derived from rlp/decode_test.go(2022/05/19) 19 // Modified and improved for the klaytn development. 20 21 package rlp 22 23 import ( 24 "bytes" 25 "encoding/hex" 26 "errors" 27 "fmt" 28 "io" 29 "math/big" 30 "reflect" 31 "strings" 32 "testing" 33 34 "github.com/klaytn/klaytn/common/math" 35 ) 36 37 func TestStreamKind(t *testing.T) { 38 tests := []struct { 39 input string 40 wantKind Kind 41 wantLen uint64 42 }{ 43 {"00", Byte, 0}, 44 {"01", Byte, 0}, 45 {"7F", Byte, 0}, 46 {"80", String, 0}, 47 {"B7", String, 55}, 48 {"B90400", String, 1024}, 49 {"BFFFFFFFFFFFFFFFFF", String, ^uint64(0)}, 50 {"C0", List, 0}, 51 {"C8", List, 8}, 52 {"F7", List, 55}, 53 {"F90400", List, 1024}, 54 {"FFFFFFFFFFFFFFFFFF", List, ^uint64(0)}, 55 } 56 57 for i, test := range tests { 58 // using plainReader to inhibit input limit errors. 59 s := NewStream(newPlainReader(unhex(test.input)), 0) 60 kind, len, err := s.Kind() 61 if err != nil { 62 t.Errorf("test %d: Kind returned error: %v", i, err) 63 continue 64 } 65 if kind != test.wantKind { 66 t.Errorf("test %d: kind mismatch: got %d, want %d", i, kind, test.wantKind) 67 } 68 if len != test.wantLen { 69 t.Errorf("test %d: len mismatch: got %d, want %d", i, len, test.wantLen) 70 } 71 } 72 } 73 74 func TestNewListStream(t *testing.T) { 75 ls := NewListStream(bytes.NewReader(unhex("0101010101")), 3) 76 if k, size, err := ls.Kind(); k != List || size != 3 || err != nil { 77 t.Errorf("Kind() returned (%v, %d, %v), expected (List, 3, nil)", k, size, err) 78 } 79 if size, err := ls.List(); size != 3 || err != nil { 80 t.Errorf("List() returned (%d, %v), expected (3, nil)", size, err) 81 } 82 for i := 0; i < 3; i++ { 83 if val, err := ls.Uint(); val != 1 || err != nil { 84 t.Errorf("Uint() returned (%d, %v), expected (1, nil)", val, err) 85 } 86 } 87 if err := ls.ListEnd(); err != nil { 88 t.Errorf("ListEnd() returned %v, expected (3, nil)", err) 89 } 90 } 91 92 func TestStreamErrors(t *testing.T) { 93 withoutInputLimit := func(b []byte) *Stream { 94 return NewStream(newPlainReader(b), 0) 95 } 96 withCustomInputLimit := func(limit uint64) func([]byte) *Stream { 97 return func(b []byte) *Stream { 98 return NewStream(bytes.NewReader(b), limit) 99 } 100 } 101 102 type calls []string 103 tests := []struct { 104 string 105 calls 106 newStream func([]byte) *Stream // uses bytes.Reader if nil 107 error error 108 }{ 109 {"C0", calls{"Bytes"}, nil, ErrExpectedString}, 110 {"C0", calls{"Uint"}, nil, ErrExpectedString}, 111 {"89000000000000000001", calls{"Uint"}, nil, errUintOverflow}, 112 {"00", calls{"List"}, nil, ErrExpectedList}, 113 {"80", calls{"List"}, nil, ErrExpectedList}, 114 {"C0", calls{"List", "Uint"}, nil, EOL}, 115 {"C8C9010101010101010101", calls{"List", "Kind"}, nil, ErrElemTooLarge}, 116 {"C3C2010201", calls{"List", "List", "Uint", "Uint", "ListEnd", "Uint"}, nil, EOL}, 117 {"00", calls{"ListEnd"}, nil, errNotInList}, 118 {"C401020304", calls{"List", "Uint", "ListEnd"}, nil, errNotAtEOL}, 119 120 // Non-canonical integers (e.g. leading zero bytes). 121 {"00", calls{"Uint"}, nil, ErrCanonInt}, 122 {"820002", calls{"Uint"}, nil, ErrCanonInt}, 123 {"8133", calls{"Uint"}, nil, ErrCanonSize}, 124 {"817F", calls{"Uint"}, nil, ErrCanonSize}, 125 {"8180", calls{"Uint"}, nil, nil}, 126 127 // Non-valid boolean 128 {"02", calls{"Bool"}, nil, errors.New("rlp: invalid boolean value: 2")}, 129 130 // Size tags must use the smallest possible encoding. 131 // Leading zero bytes in the size tag are also rejected. 132 {"8100", calls{"Uint"}, nil, ErrCanonSize}, 133 {"8100", calls{"Bytes"}, nil, ErrCanonSize}, 134 {"8101", calls{"Bytes"}, nil, ErrCanonSize}, 135 {"817F", calls{"Bytes"}, nil, ErrCanonSize}, 136 {"8180", calls{"Bytes"}, nil, nil}, 137 {"B800", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, 138 {"B90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, 139 {"B90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, 140 {"BA0002FFFF", calls{"Bytes"}, withoutInputLimit, ErrCanonSize}, 141 {"F800", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, 142 {"F90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, 143 {"F90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, 144 {"FA0002FFFF", calls{"List"}, withoutInputLimit, ErrCanonSize}, 145 146 // Expected EOF 147 {"", calls{"Kind"}, nil, io.EOF}, 148 {"", calls{"Uint"}, nil, io.EOF}, 149 {"", calls{"List"}, nil, io.EOF}, 150 {"8180", calls{"Uint", "Uint"}, nil, io.EOF}, 151 {"C0", calls{"List", "ListEnd", "List"}, nil, io.EOF}, 152 153 {"", calls{"List"}, withoutInputLimit, io.EOF}, 154 {"8180", calls{"Uint", "Uint"}, withoutInputLimit, io.EOF}, 155 {"C0", calls{"List", "ListEnd", "List"}, withoutInputLimit, io.EOF}, 156 157 // Input limit errors. 158 {"81", calls{"Bytes"}, nil, ErrValueTooLarge}, 159 {"81", calls{"Uint"}, nil, ErrValueTooLarge}, 160 {"81", calls{"Raw"}, nil, ErrValueTooLarge}, 161 {"BFFFFFFFFFFFFFFFFFFF", calls{"Bytes"}, nil, ErrValueTooLarge}, 162 {"C801", calls{"List"}, nil, ErrValueTooLarge}, 163 164 // Test for list element size check overflow. 165 {"CD04040404FFFFFFFFFFFFFFFFFF0303", calls{"List", "Uint", "Uint", "Uint", "Uint", "List"}, nil, ErrElemTooLarge}, 166 167 // Test for input limit overflow. Since we are counting the limit 168 // down toward zero in Stream.remaining, reading too far can overflow 169 // remaining to a large value, effectively disabling the limit. 170 {"C40102030401", calls{"Raw", "Uint"}, withCustomInputLimit(5), io.EOF}, 171 {"C4010203048180", calls{"Raw", "Uint"}, withCustomInputLimit(6), ErrValueTooLarge}, 172 173 // Check that the same calls are fine without a limit. 174 {"C40102030401", calls{"Raw", "Uint"}, withoutInputLimit, nil}, 175 {"C4010203048180", calls{"Raw", "Uint"}, withoutInputLimit, nil}, 176 177 // Unexpected EOF. This only happens when there is 178 // no input limit, so the reader needs to be 'dumbed down'. 179 {"81", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF}, 180 {"81", calls{"Uint"}, withoutInputLimit, io.ErrUnexpectedEOF}, 181 {"BFFFFFFFFFFFFFFF", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF}, 182 {"C801", calls{"List", "Uint", "Uint"}, withoutInputLimit, io.ErrUnexpectedEOF}, 183 184 // This test verifies that the input position is advanced 185 // correctly when calling Bytes for empty strings. Kind can be called 186 // any number of times in between and doesn't advance. 187 {"C3808080", calls{ 188 "List", // enter the list 189 "Bytes", // past first element 190 191 "Kind", "Kind", "Kind", // this shouldn't advance 192 193 "Bytes", // past second element 194 195 "Kind", "Kind", // can't hurt to try 196 197 "Bytes", // past final element 198 "Bytes", // this one should fail 199 }, nil, EOL}, 200 } 201 202 testfor: 203 for i, test := range tests { 204 if test.newStream == nil { 205 test.newStream = func(b []byte) *Stream { return NewStream(bytes.NewReader(b), 0) } 206 } 207 s := test.newStream(unhex(test.string)) 208 rs := reflect.ValueOf(s) 209 for j, call := range test.calls { 210 fval := rs.MethodByName(call) 211 ret := fval.Call(nil) 212 err := "<nil>" 213 if lastret := ret[len(ret)-1].Interface(); lastret != nil { 214 err = lastret.(error).Error() 215 } 216 if j == len(test.calls)-1 { 217 want := "<nil>" 218 if test.error != nil { 219 want = test.error.Error() 220 } 221 if err != want { 222 t.Log(test) 223 t.Errorf("test %d: last call (%s) error mismatch\ngot: %s\nwant: %s", 224 i, call, err, test.error) 225 } 226 } else if err != "<nil>" { 227 t.Log(test) 228 t.Errorf("test %d: call %d (%s) unexpected error: %q", i, j, call, err) 229 continue testfor 230 } 231 } 232 } 233 } 234 235 func TestStreamList(t *testing.T) { 236 s := NewStream(bytes.NewReader(unhex("C80102030405060708")), 0) 237 238 len, err := s.List() 239 if err != nil { 240 t.Fatalf("List error: %v", err) 241 } 242 if len != 8 { 243 t.Fatalf("List returned invalid length, got %d, want 8", len) 244 } 245 246 for i := uint64(1); i <= 8; i++ { 247 v, err := s.Uint() 248 if err != nil { 249 t.Fatalf("Uint error: %v", err) 250 } 251 if i != v { 252 t.Errorf("Uint returned wrong value, got %d, want %d", v, i) 253 } 254 } 255 256 if _, err := s.Uint(); err != EOL { 257 t.Errorf("Uint error mismatch, got %v, want %v", err, EOL) 258 } 259 if err = s.ListEnd(); err != nil { 260 t.Fatalf("ListEnd error: %v", err) 261 } 262 } 263 264 func TestStreamRaw(t *testing.T) { 265 tests := []struct { 266 input string 267 output string 268 }{ 269 { 270 "C58401010101", 271 "8401010101", 272 }, 273 { 274 "F842B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", 275 "B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", 276 }, 277 } 278 for i, tt := range tests { 279 s := NewStream(bytes.NewReader(unhex(tt.input)), 0) 280 s.List() 281 282 want := unhex(tt.output) 283 raw, err := s.Raw() 284 if err != nil { 285 t.Fatal(err) 286 } 287 if !bytes.Equal(want, raw) { 288 t.Errorf("test %d: raw mismatch: got %x, want %x", i, raw, want) 289 } 290 } 291 } 292 293 func TestStreamReadBytes(t *testing.T) { 294 tests := []struct { 295 input string 296 size int 297 err string 298 }{ 299 // kind List 300 {input: "C0", size: 1, err: "rlp: expected String or Byte"}, 301 // kind Byte 302 {input: "04", size: 0, err: "input value has wrong size 1, want 0"}, 303 {input: "04", size: 1}, 304 {input: "04", size: 2, err: "input value has wrong size 1, want 2"}, 305 // kind String 306 {input: "820102", size: 0, err: "input value has wrong size 2, want 0"}, 307 {input: "820102", size: 1, err: "input value has wrong size 2, want 1"}, 308 {input: "820102", size: 2}, 309 {input: "820102", size: 3, err: "input value has wrong size 2, want 3"}, 310 } 311 312 for _, test := range tests { 313 test := test 314 name := fmt.Sprintf("input_%s/size_%d", test.input, test.size) 315 t.Run(name, func(t *testing.T) { 316 s := NewStream(bytes.NewReader(unhex(test.input)), 0) 317 b := make([]byte, test.size) 318 err := s.ReadBytes(b) 319 if test.err == "" { 320 if err != nil { 321 t.Errorf("unexpected error %q", err) 322 } 323 } else { 324 if err == nil { 325 t.Errorf("expected error, got nil") 326 } else if err.Error() != test.err { 327 t.Errorf("wrong error %q", err) 328 } 329 } 330 }) 331 } 332 } 333 334 func TestDecodeErrors(t *testing.T) { 335 r := bytes.NewReader(nil) 336 337 if err := Decode(r, nil); err != errDecodeIntoNil { 338 t.Errorf("Decode(r, nil) error mismatch, got %q, want %q", err, errDecodeIntoNil) 339 } 340 341 var nilptr *struct{} 342 if err := Decode(r, nilptr); err != errDecodeIntoNil { 343 t.Errorf("Decode(r, nilptr) error mismatch, got %q, want %q", err, errDecodeIntoNil) 344 } 345 346 if err := Decode(r, struct{}{}); err != errNoPointer { 347 t.Errorf("Decode(r, struct{}{}) error mismatch, got %q, want %q", err, errNoPointer) 348 } 349 350 expectErr := "rlp: type chan bool is not RLP-serializable" 351 if err := Decode(r, new(chan bool)); err == nil || err.Error() != expectErr { 352 t.Errorf("Decode(r, new(chan bool)) error mismatch, got %q, want %q", err, expectErr) 353 } 354 355 if err := Decode(r, new(uint)); err != io.EOF { 356 t.Errorf("Decode(r, new(int)) error mismatch, got %q, want %q", err, io.EOF) 357 } 358 } 359 360 type decodeTest struct { 361 input string 362 ptr interface{} 363 value interface{} 364 error string 365 } 366 367 type simplestruct struct { 368 A uint 369 B string 370 } 371 372 type recstruct struct { 373 I uint 374 Child *recstruct `rlp:"nil"` 375 } 376 377 type bigIntStruct struct { 378 I *big.Int 379 B string 380 } 381 382 type invalidNilTag struct { 383 X []byte `rlp:"nil"` 384 } 385 386 type invalidTail1 struct { 387 A uint `rlp:"tail"` 388 B string 389 } 390 391 type invalidTail2 struct { 392 A uint 393 B string `rlp:"tail"` 394 } 395 396 type tailRaw struct { 397 A uint 398 Tail []RawValue `rlp:"tail"` 399 } 400 401 type tailUint struct { 402 A uint 403 Tail []uint `rlp:"tail"` 404 } 405 406 type tailPrivateFields struct { 407 A uint 408 Tail []uint `rlp:"tail"` 409 x, y bool //lint:ignore U1000 unused fields required for testing purposes. 410 } 411 412 type nilListUint struct { 413 X *uint `rlp:"nilList"` 414 } 415 416 type nilStringSlice struct { 417 X *[]uint `rlp:"nilString"` 418 } 419 420 type intField struct { 421 X int 422 } 423 424 type optionalFields struct { 425 A uint 426 B uint `rlp:"optional"` 427 C uint `rlp:"optional"` 428 } 429 430 type optionalAndTailField struct { 431 A uint 432 B uint `rlp:"optional"` 433 Tail []uint `rlp:"tail"` 434 } 435 436 type optionalBigIntField struct { 437 A uint 438 B *big.Int `rlp:"optional"` 439 } 440 441 type optionalPtrField struct { 442 A uint 443 B *[3]byte `rlp:"optional"` 444 } 445 446 type optionalPtrFieldNil struct { 447 A uint 448 B *[3]byte `rlp:"optional,nil"` 449 } 450 451 type ignoredField struct { 452 A uint 453 B uint `rlp:"-"` 454 C uint 455 } 456 457 var ( 458 veryBigInt = new(big.Int).Add( 459 big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16), 460 big.NewInt(0xFFFF), 461 ) 462 veryVeryBigInt = new(big.Int).Exp(veryBigInt, big.NewInt(8), nil) 463 ) 464 465 var decodeTests = []decodeTest{ 466 // booleans 467 {input: "01", ptr: new(bool), value: true}, 468 {input: "80", ptr: new(bool), value: false}, 469 {input: "02", ptr: new(bool), error: "rlp: invalid boolean value: 2"}, 470 471 // integers 472 {input: "05", ptr: new(uint32), value: uint32(5)}, 473 {input: "80", ptr: new(uint32), value: uint32(0)}, 474 {input: "820505", ptr: new(uint32), value: uint32(0x0505)}, 475 {input: "83050505", ptr: new(uint32), value: uint32(0x050505)}, 476 {input: "8405050505", ptr: new(uint32), value: uint32(0x05050505)}, 477 {input: "850505050505", ptr: new(uint32), error: "rlp: input string too long for uint32"}, 478 {input: "C0", ptr: new(uint32), error: "rlp: expected input string or byte for uint32"}, 479 {input: "00", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"}, 480 {input: "8105", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"}, 481 {input: "820004", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"}, 482 {input: "B8020004", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"}, 483 484 // slices 485 {input: "C0", ptr: new([]uint), value: []uint{}}, 486 {input: "C80102030405060708", ptr: new([]uint), value: []uint{1, 2, 3, 4, 5, 6, 7, 8}}, 487 {input: "F8020004", ptr: new([]uint), error: "rlp: non-canonical size information for []uint"}, 488 489 // arrays 490 {input: "C50102030405", ptr: new([5]uint), value: [5]uint{1, 2, 3, 4, 5}}, 491 {input: "C0", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"}, 492 {input: "C102", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"}, 493 {input: "C6010203040506", ptr: new([5]uint), error: "rlp: input list has too many elements for [5]uint"}, 494 {input: "F8020004", ptr: new([5]uint), error: "rlp: non-canonical size information for [5]uint"}, 495 496 // zero sized arrays 497 {input: "C0", ptr: new([0]uint), value: [0]uint{}}, 498 {input: "C101", ptr: new([0]uint), error: "rlp: input list has too many elements for [0]uint"}, 499 500 // byte slices 501 {input: "01", ptr: new([]byte), value: []byte{1}}, 502 {input: "80", ptr: new([]byte), value: []byte{}}, 503 {input: "8D6162636465666768696A6B6C6D", ptr: new([]byte), value: []byte("abcdefghijklm")}, 504 {input: "C0", ptr: new([]byte), error: "rlp: expected input string or byte for []uint8"}, 505 {input: "8105", ptr: new([]byte), error: "rlp: non-canonical size information for []uint8"}, 506 507 // byte arrays 508 {input: "02", ptr: new([1]byte), value: [1]byte{2}}, 509 {input: "8180", ptr: new([1]byte), value: [1]byte{128}}, 510 {input: "850102030405", ptr: new([5]byte), value: [5]byte{1, 2, 3, 4, 5}}, 511 512 // byte array errors 513 {input: "02", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"}, 514 {input: "80", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"}, 515 {input: "820000", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"}, 516 {input: "C0", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"}, 517 {input: "C3010203", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"}, 518 {input: "86010203040506", ptr: new([5]byte), error: "rlp: input string too long for [5]uint8"}, 519 {input: "8105", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"}, 520 {input: "817F", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"}, 521 522 // zero sized byte arrays 523 {input: "80", ptr: new([0]byte), value: [0]byte{}}, 524 {input: "01", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"}, 525 {input: "8101", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"}, 526 527 // strings 528 {input: "00", ptr: new(string), value: "\000"}, 529 {input: "8D6162636465666768696A6B6C6D", ptr: new(string), value: "abcdefghijklm"}, 530 {input: "C0", ptr: new(string), error: "rlp: expected input string or byte for string"}, 531 532 // big ints 533 {input: "80", ptr: new(*big.Int), value: big.NewInt(0)}, 534 {input: "01", ptr: new(*big.Int), value: big.NewInt(1)}, 535 {input: "89FFFFFFFFFFFFFFFFFF", ptr: new(*big.Int), value: veryBigInt}, 536 {input: "B848FFFFFFFFFFFFFFFFF800000000000000001BFFFFFFFFFFFFFFFFC8000000000000000045FFFFFFFFFFFFFFFFC800000000000000001BFFFFFFFFFFFFFFFFF8000000000000000001", ptr: new(*big.Int), value: veryVeryBigInt}, 537 {input: "10", ptr: new(big.Int), value: *big.NewInt(16)}, // non-pointer also works 538 {input: "C0", ptr: new(*big.Int), error: "rlp: expected input string or byte for *big.Int"}, 539 {input: "00", ptr: new(*big.Int), error: "rlp: non-canonical integer (leading zero bytes) for *big.Int"}, 540 {input: "820001", ptr: new(*big.Int), error: "rlp: non-canonical integer (leading zero bytes) for *big.Int"}, 541 {input: "8105", ptr: new(*big.Int), error: "rlp: non-canonical size information for *big.Int"}, 542 543 // structs 544 { 545 input: "C50583343434", 546 ptr: new(simplestruct), 547 value: simplestruct{5, "444"}, 548 }, 549 { 550 input: "C601C402C203C0", 551 ptr: new(recstruct), 552 value: recstruct{1, &recstruct{2, &recstruct{3, nil}}}, 553 }, 554 { 555 // This checks that empty big.Int works correctly in struct context. It's easy to 556 // miss the update of s.kind for this case, so it needs its own test. 557 input: "C58083343434", 558 ptr: new(bigIntStruct), 559 value: bigIntStruct{new(big.Int), "444"}, 560 }, 561 562 // struct errors 563 { 564 input: "C0", 565 ptr: new(simplestruct), 566 error: "rlp: too few elements for rlp.simplestruct", 567 }, 568 { 569 input: "C105", 570 ptr: new(simplestruct), 571 error: "rlp: too few elements for rlp.simplestruct", 572 }, 573 { 574 input: "C7C50583343434C0", 575 ptr: new([]*simplestruct), 576 error: "rlp: too few elements for rlp.simplestruct, decoding into ([]*rlp.simplestruct)[1]", 577 }, 578 { 579 input: "83222222", 580 ptr: new(simplestruct), 581 error: "rlp: expected input list for rlp.simplestruct", 582 }, 583 { 584 input: "C3010101", 585 ptr: new(simplestruct), 586 error: "rlp: input list has too many elements for rlp.simplestruct", 587 }, 588 { 589 input: "C501C3C00000", 590 ptr: new(recstruct), 591 error: "rlp: expected input string or byte for uint, decoding into (rlp.recstruct).Child.I", 592 }, 593 { 594 input: "C103", 595 ptr: new(intField), 596 error: "rlp: type int is not RLP-serializable (struct field rlp.intField.X)", 597 }, 598 { 599 input: "C50102C20102", 600 ptr: new(tailUint), 601 error: "rlp: expected input string or byte for uint, decoding into (rlp.tailUint).Tail[1]", 602 }, 603 { 604 input: "C0", 605 ptr: new(invalidNilTag), 606 error: `rlp: invalid struct tag "nil" for rlp.invalidNilTag.X (field is not a pointer)`, 607 }, 608 609 // struct tag "tail" 610 { 611 input: "C3010203", 612 ptr: new(tailRaw), 613 value: tailRaw{A: 1, Tail: []RawValue{unhex("02"), unhex("03")}}, 614 }, 615 { 616 input: "C20102", 617 ptr: new(tailRaw), 618 value: tailRaw{A: 1, Tail: []RawValue{unhex("02")}}, 619 }, 620 { 621 input: "C101", 622 ptr: new(tailRaw), 623 value: tailRaw{A: 1, Tail: []RawValue{}}, 624 }, 625 { 626 input: "C3010203", 627 ptr: new(tailPrivateFields), 628 value: tailPrivateFields{A: 1, Tail: []uint{2, 3}}, 629 }, 630 { 631 input: "C0", 632 ptr: new(invalidTail1), 633 error: `rlp: invalid struct tag "tail" for rlp.invalidTail1.A (must be on last field)`, 634 }, 635 { 636 input: "C0", 637 ptr: new(invalidTail2), 638 error: `rlp: invalid struct tag "tail" for rlp.invalidTail2.B (field type is not slice)`, 639 }, 640 641 // struct tag "-" 642 { 643 input: "C20102", 644 ptr: new(ignoredField), 645 value: ignoredField{A: 1, C: 2}, 646 }, 647 648 // struct tag "nilList" 649 { 650 input: "C180", 651 ptr: new(nilListUint), 652 error: "rlp: wrong kind of empty value (got String, want List) for *uint, decoding into (rlp.nilListUint).X", 653 }, 654 { 655 input: "C1C0", 656 ptr: new(nilListUint), 657 value: nilListUint{}, 658 }, 659 { 660 input: "C103", 661 ptr: new(nilListUint), 662 value: func() interface{} { 663 v := uint(3) 664 return nilListUint{X: &v} 665 }(), 666 }, 667 668 // struct tag "nilString" 669 { 670 input: "C1C0", 671 ptr: new(nilStringSlice), 672 error: "rlp: wrong kind of empty value (got List, want String) for *[]uint, decoding into (rlp.nilStringSlice).X", 673 }, 674 { 675 input: "C180", 676 ptr: new(nilStringSlice), 677 value: nilStringSlice{}, 678 }, 679 { 680 input: "C2C103", 681 ptr: new(nilStringSlice), 682 value: nilStringSlice{X: &[]uint{3}}, 683 }, 684 685 // struct tag "optional" 686 { 687 input: "C101", 688 ptr: new(optionalFields), 689 value: optionalFields{1, 0, 0}, 690 }, 691 { 692 input: "C20102", 693 ptr: new(optionalFields), 694 value: optionalFields{1, 2, 0}, 695 }, 696 { 697 input: "C3010203", 698 ptr: new(optionalFields), 699 value: optionalFields{1, 2, 3}, 700 }, 701 { 702 input: "C401020304", 703 ptr: new(optionalFields), 704 error: "rlp: input list has too many elements for rlp.optionalFields", 705 }, 706 { 707 input: "C101", 708 ptr: new(optionalAndTailField), 709 value: optionalAndTailField{A: 1}, 710 }, 711 { 712 input: "C20102", 713 ptr: new(optionalAndTailField), 714 value: optionalAndTailField{A: 1, B: 2, Tail: []uint{}}, 715 }, 716 { 717 input: "C401020304", 718 ptr: new(optionalAndTailField), 719 value: optionalAndTailField{A: 1, B: 2, Tail: []uint{3, 4}}, 720 }, 721 { 722 input: "C101", 723 ptr: new(optionalBigIntField), 724 value: optionalBigIntField{A: 1, B: nil}, 725 }, 726 { 727 input: "C20102", 728 ptr: new(optionalBigIntField), 729 value: optionalBigIntField{A: 1, B: big.NewInt(2)}, 730 }, 731 { 732 input: "C101", 733 ptr: new(optionalPtrField), 734 value: optionalPtrField{A: 1}, 735 }, 736 { 737 input: "C20180", // not accepted because "optional" doesn't enable "nil" 738 ptr: new(optionalPtrField), 739 error: "rlp: input string too short for [3]uint8, decoding into (rlp.optionalPtrField).B", 740 }, 741 { 742 input: "C20102", 743 ptr: new(optionalPtrField), 744 error: "rlp: input string too short for [3]uint8, decoding into (rlp.optionalPtrField).B", 745 }, 746 { 747 input: "C50183010203", 748 ptr: new(optionalPtrField), 749 value: optionalPtrField{A: 1, B: &[3]byte{1, 2, 3}}, 750 }, 751 { 752 input: "C101", 753 ptr: new(optionalPtrFieldNil), 754 value: optionalPtrFieldNil{A: 1}, 755 }, 756 { 757 input: "C20180", // accepted because "nil" tag allows empty input 758 ptr: new(optionalPtrFieldNil), 759 value: optionalPtrFieldNil{A: 1}, 760 }, 761 { 762 input: "C20102", 763 ptr: new(optionalPtrFieldNil), 764 error: "rlp: input string too short for [3]uint8, decoding into (rlp.optionalPtrFieldNil).B", 765 }, 766 767 // struct tag "optional" field clearing 768 { 769 input: "C101", 770 ptr: &optionalFields{A: 9, B: 8, C: 7}, 771 value: optionalFields{A: 1, B: 0, C: 0}, 772 }, 773 { 774 input: "C20102", 775 ptr: &optionalFields{A: 9, B: 8, C: 7}, 776 value: optionalFields{A: 1, B: 2, C: 0}, 777 }, 778 { 779 input: "C20102", 780 ptr: &optionalAndTailField{A: 9, B: 8, Tail: []uint{7, 6, 5}}, 781 value: optionalAndTailField{A: 1, B: 2, Tail: []uint{}}, 782 }, 783 { 784 input: "C101", 785 ptr: &optionalPtrField{A: 9, B: &[3]byte{8, 7, 6}}, 786 value: optionalPtrField{A: 1}, 787 }, 788 789 // RawValue 790 {input: "01", ptr: new(RawValue), value: RawValue(unhex("01"))}, 791 {input: "82FFFF", ptr: new(RawValue), value: RawValue(unhex("82FFFF"))}, 792 {input: "C20102", ptr: new([]RawValue), value: []RawValue{unhex("01"), unhex("02")}}, 793 794 // pointers 795 {input: "00", ptr: new(*[]byte), value: &[]byte{0}}, 796 {input: "80", ptr: new(*uint), value: uintp(0)}, 797 {input: "C0", ptr: new(*uint), error: "rlp: expected input string or byte for uint"}, 798 {input: "07", ptr: new(*uint), value: uintp(7)}, 799 {input: "817F", ptr: new(*uint), error: "rlp: non-canonical size information for uint"}, 800 {input: "8180", ptr: new(*uint), value: uintp(0x80)}, 801 {input: "C109", ptr: new(*[]uint), value: &[]uint{9}}, 802 {input: "C58403030303", ptr: new(*[][]byte), value: &[][]byte{{3, 3, 3, 3}}}, 803 804 // check that input position is advanced also for empty values. 805 {input: "C3808005", ptr: new([]*uint), value: []*uint{uintp(0), uintp(0), uintp(5)}}, 806 807 // interface{} 808 {input: "00", ptr: new(interface{}), value: []byte{0}}, 809 {input: "01", ptr: new(interface{}), value: []byte{1}}, 810 {input: "80", ptr: new(interface{}), value: []byte{}}, 811 {input: "850505050505", ptr: new(interface{}), value: []byte{5, 5, 5, 5, 5}}, 812 {input: "C0", ptr: new(interface{}), value: []interface{}{}}, 813 {input: "C50183040404", ptr: new(interface{}), value: []interface{}{[]byte{1}, []byte{4, 4, 4}}}, 814 { 815 input: "C3010203", 816 ptr: new([]io.Reader), 817 error: "rlp: type io.Reader is not RLP-serializable", 818 }, 819 820 // fuzzer crashes 821 { 822 input: "c330f9c030f93030ce3030303030303030bd303030303030", 823 ptr: new(interface{}), 824 error: "rlp: element is larger than containing list", 825 }, 826 } 827 828 func uintp(i uint) *uint { return &i } 829 830 func runTests(t *testing.T, decode func([]byte, interface{}) error) { 831 for i, test := range decodeTests { 832 input, err := hex.DecodeString(test.input) 833 if err != nil { 834 t.Errorf("test %d: invalid hex input %q", i, test.input) 835 continue 836 } 837 err = decode(input, test.ptr) 838 if err != nil && test.error == "" { 839 t.Errorf("test %d: unexpected Decode error: %v\ndecoding into %T\ninput %q", 840 i, err, test.ptr, test.input) 841 continue 842 } 843 if test.error != "" && fmt.Sprint(err) != test.error { 844 t.Errorf("test %d: Decode error mismatch\ngot %v\nwant %v\ndecoding into %T\ninput %q", 845 i, err, test.error, test.ptr, test.input) 846 continue 847 } 848 deref := reflect.ValueOf(test.ptr).Elem().Interface() 849 if err == nil && !reflect.DeepEqual(deref, test.value) { 850 t.Errorf("test %d: value mismatch\ngot %#v\nwant %#v\ndecoding into %T\ninput %q", 851 i, deref, test.value, test.ptr, test.input) 852 } 853 } 854 } 855 856 func TestDecodeWithByteReader(t *testing.T) { 857 runTests(t, func(input []byte, into interface{}) error { 858 return Decode(bytes.NewReader(input), into) 859 }) 860 } 861 862 func testDecodeWithEncReader(t *testing.T, n int) { 863 s := strings.Repeat("0", n) 864 _, r, _ := EncodeToReader(s) 865 var decoded string 866 err := Decode(r, &decoded) 867 if err != nil { 868 t.Errorf("Unexpected decode error with n=%v: %v", n, err) 869 } 870 if decoded != s { 871 t.Errorf("Decode mismatch with n=%v", n) 872 } 873 } 874 875 // This is a regression test checking that decoding from encReader 876 // works for RLP values of size 8192 bytes or more. 877 func TestDecodeWithEncReader(t *testing.T) { 878 testDecodeWithEncReader(t, 8188) // length with header is 8191 879 testDecodeWithEncReader(t, 8189) // length with header is 8192 880 } 881 882 // plainReader reads from a byte slice but does not 883 // implement ReadByte. It is also not recognized by the 884 // size validation. This is useful to test how the decoder 885 // behaves on a non-buffered input stream. 886 type plainReader []byte 887 888 func newPlainReader(b []byte) io.Reader { 889 return (*plainReader)(&b) 890 } 891 892 func (r *plainReader) Read(buf []byte) (n int, err error) { 893 if len(*r) == 0 { 894 return 0, io.EOF 895 } 896 n = copy(buf, *r) 897 *r = (*r)[n:] 898 return n, nil 899 } 900 901 func TestDecodeWithNonByteReader(t *testing.T) { 902 runTests(t, func(input []byte, into interface{}) error { 903 return Decode(newPlainReader(input), into) 904 }) 905 } 906 907 func TestDecodeStreamReset(t *testing.T) { 908 s := NewStream(nil, 0) 909 runTests(t, func(input []byte, into interface{}) error { 910 s.Reset(bytes.NewReader(input), 0) 911 return s.Decode(into) 912 }) 913 } 914 915 type testDecoder struct{ called bool } 916 917 func (t *testDecoder) DecodeRLP(s *Stream) error { 918 if _, err := s.Uint(); err != nil { 919 return err 920 } 921 t.called = true 922 return nil 923 } 924 925 func TestDecodeDecoder(t *testing.T) { 926 var s struct { 927 T1 testDecoder 928 T2 *testDecoder 929 T3 **testDecoder 930 } 931 if err := Decode(bytes.NewReader(unhex("C3010203")), &s); err != nil { 932 t.Fatalf("Decode error: %v", err) 933 } 934 935 if !s.T1.called { 936 t.Errorf("DecodeRLP was not called for (non-pointer) testDecoder") 937 } 938 939 if s.T2 == nil { 940 t.Errorf("*testDecoder has not been allocated") 941 } else if !s.T2.called { 942 t.Errorf("DecodeRLP was not called for *testDecoder") 943 } 944 945 if s.T3 == nil || *s.T3 == nil { 946 t.Errorf("**testDecoder has not been allocated") 947 } else if !(*s.T3).called { 948 t.Errorf("DecodeRLP was not called for **testDecoder") 949 } 950 } 951 952 func TestDecodeDecoderNilPointer(t *testing.T) { 953 var s struct { 954 T1 *testDecoder `rlp:"nil"` 955 T2 *testDecoder 956 } 957 if err := Decode(bytes.NewReader(unhex("C2C002")), &s); err != nil { 958 t.Fatalf("Decode error: %v", err) 959 } 960 if s.T1 != nil { 961 t.Errorf("decoder T1 allocated for empty input (called: %v)", s.T1.called) 962 } 963 if s.T2 == nil || !s.T2.called { 964 t.Errorf("decoder T2 not allocated/called") 965 } 966 } 967 968 type byteDecoder byte 969 970 func (bd *byteDecoder) DecodeRLP(s *Stream) error { 971 _, err := s.Uint() 972 *bd = 255 973 return err 974 } 975 976 func (bd byteDecoder) called() bool { 977 return bd == 255 978 } 979 980 // This test verifies that the byte slice/byte array logic 981 // does not kick in for element types implementing Decoder. 982 func TestDecoderInByteSlice(t *testing.T) { 983 var slice []byteDecoder 984 if err := Decode(bytes.NewReader(unhex("C101")), &slice); err != nil { 985 t.Errorf("unexpected Decode error %v", err) 986 } else if !slice[0].called() { 987 t.Errorf("DecodeRLP not called for slice element") 988 } 989 990 var array [1]byteDecoder 991 if err := Decode(bytes.NewReader(unhex("C101")), &array); err != nil { 992 t.Errorf("unexpected Decode error %v", err) 993 } else if !array[0].called() { 994 t.Errorf("DecodeRLP not called for array element") 995 } 996 } 997 998 type unencodableDecoder func() 999 1000 func (f *unencodableDecoder) DecodeRLP(s *Stream) error { 1001 if _, err := s.List(); err != nil { 1002 return err 1003 } 1004 if err := s.ListEnd(); err != nil { 1005 return err 1006 } 1007 *f = func() {} 1008 return nil 1009 } 1010 1011 func TestDecoderFunc(t *testing.T) { 1012 var x func() 1013 if err := DecodeBytes([]byte{0xC0}, (*unencodableDecoder)(&x)); err != nil { 1014 t.Fatal(err) 1015 } 1016 x() 1017 } 1018 1019 // This tests the validity checks for fields with struct tag "optional". 1020 func TestInvalidOptionalField(t *testing.T) { 1021 type ( 1022 invalid1 struct { 1023 A uint `rlp:"optional"` 1024 B uint 1025 } 1026 invalid2 struct { 1027 T []uint `rlp:"tail,optional"` 1028 } 1029 invalid3 struct { 1030 T []uint `rlp:"optional,tail"` 1031 } 1032 ) 1033 1034 tests := []struct { 1035 v interface{} 1036 err string 1037 }{ 1038 {v: new(invalid1), err: `rlp: invalid struct tag "" for rlp.invalid1.B (must be optional because preceding field "A" is optional)`}, 1039 {v: new(invalid2), err: `rlp: invalid struct tag "optional" for rlp.invalid2.T (also has "tail" tag)`}, 1040 {v: new(invalid3), err: `rlp: invalid struct tag "tail" for rlp.invalid3.T (also has "optional" tag)`}, 1041 } 1042 for _, test := range tests { 1043 err := DecodeBytes(unhex("C20102"), test.v) 1044 if err == nil { 1045 t.Errorf("no error for %T", test.v) 1046 } else if err.Error() != test.err { 1047 t.Errorf("wrong error for %T: %v", test.v, err.Error()) 1048 } 1049 } 1050 } 1051 1052 func ExampleDecode() { 1053 input, _ := hex.DecodeString("C90A1486666F6F626172") 1054 1055 type example struct { 1056 A, B uint 1057 String string 1058 } 1059 1060 var s example 1061 err := Decode(bytes.NewReader(input), &s) 1062 if err != nil { 1063 fmt.Printf("Error: %v\n", err) 1064 } else { 1065 fmt.Printf("Decoded value: %#v\n", s) 1066 } 1067 // Output: 1068 // Decoded value: rlp.example{A:0xa, B:0x14, String:"foobar"} 1069 } 1070 1071 func ExampleDecode_structTagNil() { 1072 // In this example, we'll use the "nil" struct tag to change 1073 // how a pointer-typed field is decoded. The input contains an RLP 1074 // list of one element, an empty string. 1075 input := []byte{0xC1, 0x80} 1076 1077 // This type uses the normal rules. 1078 // The empty input string is decoded as a pointer to an empty Go string. 1079 var normalRules struct { 1080 String *string 1081 } 1082 Decode(bytes.NewReader(input), &normalRules) 1083 fmt.Printf("normal: String = %q\n", *normalRules.String) 1084 1085 // This type uses the struct tag. 1086 // The empty input string is decoded as a nil pointer. 1087 var withEmptyOK struct { 1088 String *string `rlp:"nil"` 1089 } 1090 Decode(bytes.NewReader(input), &withEmptyOK) 1091 fmt.Printf("with nil tag: String = %v\n", withEmptyOK.String) 1092 1093 // Output: 1094 // normal: String = "" 1095 // with nil tag: String = <nil> 1096 } 1097 1098 func ExampleStream() { 1099 input, _ := hex.DecodeString("C90A1486666F6F626172") 1100 s := NewStream(bytes.NewReader(input), 0) 1101 1102 // Check what kind of value lies ahead 1103 kind, size, _ := s.Kind() 1104 fmt.Printf("Kind: %v size:%d\n", kind, size) 1105 1106 // Enter the list 1107 if _, err := s.List(); err != nil { 1108 fmt.Printf("List error: %v\n", err) 1109 return 1110 } 1111 1112 // Decode elements 1113 fmt.Println(s.Uint()) 1114 fmt.Println(s.Uint()) 1115 fmt.Println(s.Bytes()) 1116 1117 // Acknowledge end of list 1118 if err := s.ListEnd(); err != nil { 1119 fmt.Printf("ListEnd error: %v\n", err) 1120 } 1121 // Output: 1122 // Kind: List size:9 1123 // 10 <nil> 1124 // 20 <nil> 1125 // [102 111 111 98 97 114] <nil> 1126 } 1127 1128 func BenchmarkDecodeUints(b *testing.B) { 1129 enc := encodeTestSlice(90000) 1130 b.SetBytes(int64(len(enc))) 1131 b.ReportAllocs() 1132 b.ResetTimer() 1133 1134 for i := 0; i < b.N; i++ { 1135 var s []uint 1136 r := bytes.NewReader(enc) 1137 if err := Decode(r, &s); err != nil { 1138 b.Fatalf("Decode error: %v", err) 1139 } 1140 } 1141 } 1142 1143 func BenchmarkDecodeUintsReused(b *testing.B) { 1144 enc := encodeTestSlice(100000) 1145 b.SetBytes(int64(len(enc))) 1146 b.ReportAllocs() 1147 b.ResetTimer() 1148 1149 var s []uint 1150 for i := 0; i < b.N; i++ { 1151 r := bytes.NewReader(enc) 1152 if err := Decode(r, &s); err != nil { 1153 b.Fatalf("Decode error: %v", err) 1154 } 1155 } 1156 } 1157 1158 func BenchmarkDecodeByteArrayStruct(b *testing.B) { 1159 enc, err := EncodeToBytes(&byteArrayStruct{}) 1160 if err != nil { 1161 b.Fatal(err) 1162 } 1163 b.SetBytes(int64(len(enc))) 1164 b.ReportAllocs() 1165 b.ResetTimer() 1166 1167 var out byteArrayStruct 1168 for i := 0; i < b.N; i++ { 1169 if err := DecodeBytes(enc, &out); err != nil { 1170 b.Fatal(err) 1171 } 1172 } 1173 } 1174 1175 func BenchmarkDecodeBigInts(b *testing.B) { 1176 ints := make([]*big.Int, 200) 1177 for i := range ints { 1178 ints[i] = math.BigPow(2, int64(i)) 1179 } 1180 enc, err := EncodeToBytes(ints) 1181 if err != nil { 1182 b.Fatal(err) 1183 } 1184 b.SetBytes(int64(len(enc))) 1185 b.ReportAllocs() 1186 b.ResetTimer() 1187 1188 var out []*big.Int 1189 for i := 0; i < b.N; i++ { 1190 if err := DecodeBytes(enc, &out); err != nil { 1191 b.Fatal(err) 1192 } 1193 } 1194 } 1195 1196 func encodeTestSlice(n uint) []byte { 1197 s := make([]uint, n) 1198 for i := uint(0); i < n; i++ { 1199 s[i] = i 1200 } 1201 b, err := EncodeToBytes(s) 1202 if err != nil { 1203 panic(fmt.Sprintf("encode error: %v", err)) 1204 } 1205 return b 1206 } 1207 1208 func unhex(str string) []byte { 1209 b, err := hex.DecodeString(strings.Replace(str, " ", "", -1)) 1210 if err != nil { 1211 panic(fmt.Sprintf("invalid hex string: %q", str)) 1212 } 1213 return b 1214 }