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