github.com/yinchengtsinghua/golang-Eos-dpos-Ethereum@v0.0.0-20190121132951-92cc4225ed8e/rlp/decode_test.go (about) 1 2 //此源码被清华学神尹成大魔王专业翻译分析并修改 3 //尹成QQ77025077 4 //尹成微信18510341407 5 //尹成所在QQ群721929980 6 //尹成邮箱 yinc13@mails.tsinghua.edu.cn 7 //尹成毕业于清华大学,微软区块链领域全球最有价值专家 8 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 9 //版权所有2014 Go Ethereum作者 10 //此文件是Go以太坊库的一部分。 11 // 12 //Go-Ethereum库是免费软件:您可以重新分发它和/或修改 13 //根据GNU发布的较低通用公共许可证的条款 14 //自由软件基金会,或者许可证的第3版,或者 15 //(由您选择)任何更高版本。 16 // 17 //Go以太坊图书馆的发行目的是希望它会有用, 18 //但没有任何保证;甚至没有 19 //适销性或特定用途的适用性。见 20 //GNU较低的通用公共许可证,了解更多详细信息。 21 // 22 //你应该收到一份GNU较低级别的公共许可证副本 23 //以及Go以太坊图书馆。如果没有,请参见<http://www.gnu.org/licenses/>。 24 25 package rlp 26 27 import ( 28 "bytes" 29 "encoding/hex" 30 "errors" 31 "fmt" 32 "io" 33 "math/big" 34 "reflect" 35 "strings" 36 "testing" 37 ) 38 39 func TestStreamKind(t *testing.T) { 40 tests := []struct { 41 input string 42 wantKind Kind 43 wantLen uint64 44 }{ 45 {"00", Byte, 0}, 46 {"01", Byte, 0}, 47 {"7F", Byte, 0}, 48 {"80", String, 0}, 49 {"B7", String, 55}, 50 {"B90400", String, 1024}, 51 {"BFFFFFFFFFFFFFFFFF", String, ^uint64(0)}, 52 {"C0", List, 0}, 53 {"C8", List, 8}, 54 {"F7", List, 55}, 55 {"F90400", List, 1024}, 56 {"FFFFFFFFFFFFFFFFFF", List, ^uint64(0)}, 57 } 58 59 for i, test := range tests { 60 //使用普通读卡器抑制输入极限误差。 61 s := NewStream(newPlainReader(unhex(test.input)), 0) 62 kind, len, err := s.Kind() 63 if err != nil { 64 t.Errorf("test %d: Kind returned error: %v", i, err) 65 continue 66 } 67 if kind != test.wantKind { 68 t.Errorf("test %d: kind mismatch: got %d, want %d", i, kind, test.wantKind) 69 } 70 if len != test.wantLen { 71 t.Errorf("test %d: len mismatch: got %d, want %d", i, len, test.wantLen) 72 } 73 } 74 } 75 76 func TestNewListStream(t *testing.T) { 77 ls := NewListStream(bytes.NewReader(unhex("0101010101")), 3) 78 if k, size, err := ls.Kind(); k != List || size != 3 || err != nil { 79 t.Errorf("Kind() returned (%v, %d, %v), expected (List, 3, nil)", k, size, err) 80 } 81 if size, err := ls.List(); size != 3 || err != nil { 82 t.Errorf("List() returned (%d, %v), expected (3, nil)", size, err) 83 } 84 for i := 0; i < 3; i++ { 85 if val, err := ls.Uint(); val != 1 || err != nil { 86 t.Errorf("Uint() returned (%d, %v), expected (1, nil)", val, err) 87 } 88 } 89 if err := ls.ListEnd(); err != nil { 90 t.Errorf("ListEnd() returned %v, expected (3, nil)", err) 91 } 92 } 93 94 func TestStreamErrors(t *testing.T) { 95 withoutInputLimit := func(b []byte) *Stream { 96 return NewStream(newPlainReader(b), 0) 97 } 98 withCustomInputLimit := func(limit uint64) func([]byte) *Stream { 99 return func(b []byte) *Stream { 100 return NewStream(bytes.NewReader(b), limit) 101 } 102 } 103 104 type calls []string 105 tests := []struct { 106 string 107 calls 108 newStream func([]byte) *Stream //使用bytes.reader(如果为nil) 109 error error 110 }{ 111 {"C0", calls{"Bytes"}, nil, ErrExpectedString}, 112 {"C0", calls{"Uint"}, nil, ErrExpectedString}, 113 {"89000000000000000001", calls{"Uint"}, nil, errUintOverflow}, 114 {"00", calls{"List"}, nil, ErrExpectedList}, 115 {"80", calls{"List"}, nil, ErrExpectedList}, 116 {"C0", calls{"List", "Uint"}, nil, EOL}, 117 {"C8C9010101010101010101", calls{"List", "Kind"}, nil, ErrElemTooLarge}, 118 {"C3C2010201", calls{"List", "List", "Uint", "Uint", "ListEnd", "Uint"}, nil, EOL}, 119 {"00", calls{"ListEnd"}, nil, errNotInList}, 120 {"C401020304", calls{"List", "Uint", "ListEnd"}, nil, errNotAtEOL}, 121 122 //非规范整数(例如前导零字节)。 123 {"00", calls{"Uint"}, nil, ErrCanonInt}, 124 {"820002", calls{"Uint"}, nil, ErrCanonInt}, 125 {"8133", calls{"Uint"}, nil, ErrCanonSize}, 126 {"817F", calls{"Uint"}, nil, ErrCanonSize}, 127 {"8180", calls{"Uint"}, nil, nil}, 128 129 //无效布尔值 130 {"02", calls{"Bool"}, nil, errors.New("rlp: invalid boolean value: 2")}, 131 132 //大小标记必须使用尽可能小的编码。 133 //大小标记中的前导零字节也被拒绝。 134 {"8100", calls{"Uint"}, nil, ErrCanonSize}, 135 {"8100", calls{"Bytes"}, nil, ErrCanonSize}, 136 {"8101", calls{"Bytes"}, nil, ErrCanonSize}, 137 {"817F", calls{"Bytes"}, nil, ErrCanonSize}, 138 {"8180", calls{"Bytes"}, nil, nil}, 139 {"B800", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, 140 {"B90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, 141 {"B90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, 142 {"BA0002FFFF", calls{"Bytes"}, withoutInputLimit, ErrCanonSize}, 143 {"F800", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, 144 {"F90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, 145 {"F90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, 146 {"FA0002FFFF", calls{"List"}, withoutInputLimit, ErrCanonSize}, 147 148 //预期EOF 149 {"", calls{"Kind"}, nil, io.EOF}, 150 {"", calls{"Uint"}, nil, io.EOF}, 151 {"", calls{"List"}, nil, io.EOF}, 152 {"8180", calls{"Uint", "Uint"}, nil, io.EOF}, 153 {"C0", calls{"List", "ListEnd", "List"}, nil, io.EOF}, 154 155 {"", calls{"List"}, withoutInputLimit, io.EOF}, 156 {"8180", calls{"Uint", "Uint"}, withoutInputLimit, io.EOF}, 157 {"C0", calls{"List", "ListEnd", "List"}, withoutInputLimit, io.EOF}, 158 159 //输入限制错误。 160 {"81", calls{"Bytes"}, nil, ErrValueTooLarge}, 161 {"81", calls{"Uint"}, nil, ErrValueTooLarge}, 162 {"81", calls{"Raw"}, nil, ErrValueTooLarge}, 163 {"BFFFFFFFFFFFFFFFFFFF", calls{"Bytes"}, nil, ErrValueTooLarge}, 164 {"C801", calls{"List"}, nil, ErrValueTooLarge}, 165 166 //测试列表元素大小检查溢出。 167 {"CD04040404FFFFFFFFFFFFFFFFFF0303", calls{"List", "Uint", "Uint", "Uint", "Uint", "List"}, nil, ErrElemTooLarge}, 168 169 //输入极限溢出测试。因为我们在计算限额 170 //在stream.remaining中向下接近零,如果读数太远,则可能溢出 171 //保留为大值,有效禁用限制。 172 {"C40102030401", calls{"Raw", "Uint"}, withCustomInputLimit(5), io.EOF}, 173 {"C4010203048180", calls{"Raw", "Uint"}, withCustomInputLimit(6), ErrValueTooLarge}, 174 175 //检查相同的呼叫是否可以无限制地进行。 176 {"C40102030401", calls{"Raw", "Uint"}, withoutInputLimit, nil}, 177 {"C4010203048180", calls{"Raw", "Uint"}, withoutInputLimit, nil}, 178 179 //意外的EOF。只有当 180 //没有输入限制,所以读卡器需要“减速”。 181 {"81", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF}, 182 {"81", calls{"Uint"}, withoutInputLimit, io.ErrUnexpectedEOF}, 183 {"BFFFFFFFFFFFFFFF", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF}, 184 {"C801", calls{"List", "Uint", "Uint"}, withoutInputLimit, io.ErrUnexpectedEOF}, 185 186 //此测试验证输入位置是否提前。 187 //为空字符串调用字节时正确。可以称之为 188 //和之间的任何次数都不会提前。 189 {"C3808080", calls{ 190 "List", //进入列表 191 "Bytes", //超过第一个元素 192 193 "Kind", "Kind", "Kind", //这不应该提前 194 195 "Bytes", //过去的第二个元素 196 197 "Kind", "Kind", //尝试是不会受伤的 198 199 "Bytes", //过去的最后一个元素 200 "Bytes", //这个应该失败 201 }, nil, EOL}, 202 } 203 204 testfor: 205 for i, test := range tests { 206 if test.newStream == nil { 207 test.newStream = func(b []byte) *Stream { return NewStream(bytes.NewReader(b), 0) } 208 } 209 s := test.newStream(unhex(test.string)) 210 rs := reflect.ValueOf(s) 211 for j, call := range test.calls { 212 fval := rs.MethodByName(call) 213 ret := fval.Call(nil) 214 err := "<nil>" 215 if lastret := ret[len(ret)-1].Interface(); lastret != nil { 216 err = lastret.(error).Error() 217 } 218 if j == len(test.calls)-1 { 219 want := "<nil>" 220 if test.error != nil { 221 want = test.error.Error() 222 } 223 if err != want { 224 t.Log(test) 225 t.Errorf("test %d: last call (%s) error mismatch\ngot: %s\nwant: %s", 226 i, call, err, test.error) 227 } 228 } else if err != "<nil>" { 229 t.Log(test) 230 t.Errorf("test %d: call %d (%s) unexpected error: %q", i, j, call, err) 231 continue testfor 232 } 233 } 234 } 235 } 236 237 func TestStreamList(t *testing.T) { 238 s := NewStream(bytes.NewReader(unhex("C80102030405060708")), 0) 239 240 len, err := s.List() 241 if err != nil { 242 t.Fatalf("List error: %v", err) 243 } 244 if len != 8 { 245 t.Fatalf("List returned invalid length, got %d, want 8", len) 246 } 247 248 for i := uint64(1); i <= 8; i++ { 249 v, err := s.Uint() 250 if err != nil { 251 t.Fatalf("Uint error: %v", err) 252 } 253 if i != v { 254 t.Errorf("Uint returned wrong value, got %d, want %d", v, i) 255 } 256 } 257 258 if _, err := s.Uint(); err != EOL { 259 t.Errorf("Uint error mismatch, got %v, want %v", err, EOL) 260 } 261 if err = s.ListEnd(); err != nil { 262 t.Fatalf("ListEnd error: %v", err) 263 } 264 } 265 266 func TestStreamRaw(t *testing.T) { 267 tests := []struct { 268 input string 269 output string 270 }{ 271 { 272 "C58401010101", 273 "8401010101", 274 }, 275 { 276 "F842B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", 277 "B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", 278 }, 279 } 280 for i, tt := range tests { 281 s := NewStream(bytes.NewReader(unhex(tt.input)), 0) 282 s.List() 283 284 want := unhex(tt.output) 285 raw, err := s.Raw() 286 if err != nil { 287 t.Fatal(err) 288 } 289 if !bytes.Equal(want, raw) { 290 t.Errorf("test %d: raw mismatch: got %x, want %x", i, raw, want) 291 } 292 } 293 } 294 295 func TestDecodeErrors(t *testing.T) { 296 r := bytes.NewReader(nil) 297 298 if err := Decode(r, nil); err != errDecodeIntoNil { 299 t.Errorf("Decode(r, nil) error mismatch, got %q, want %q", err, errDecodeIntoNil) 300 } 301 302 var nilptr *struct{} 303 if err := Decode(r, nilptr); err != errDecodeIntoNil { 304 t.Errorf("Decode(r, nilptr) error mismatch, got %q, want %q", err, errDecodeIntoNil) 305 } 306 307 if err := Decode(r, struct{}{}); err != errNoPointer { 308 t.Errorf("Decode(r, struct{}{}) error mismatch, got %q, want %q", err, errNoPointer) 309 } 310 311 expectErr := "rlp: type chan bool is not RLP-serializable" 312 if err := Decode(r, new(chan bool)); err == nil || err.Error() != expectErr { 313 t.Errorf("Decode(r, new(chan bool)) error mismatch, got %q, want %q", err, expectErr) 314 } 315 316 if err := Decode(r, new(uint)); err != io.EOF { 317 t.Errorf("Decode(r, new(int)) error mismatch, got %q, want %q", err, io.EOF) 318 } 319 } 320 321 type decodeTest struct { 322 input string 323 ptr interface{} 324 value interface{} 325 error string 326 } 327 328 type simplestruct struct { 329 A uint 330 B string 331 } 332 333 type recstruct struct { 334 I uint 335 Child *recstruct `rlp:"nil"` 336 } 337 338 type invalidTail1 struct { 339 A uint `rlp:"tail"` 340 B string 341 } 342 343 type invalidTail2 struct { 344 A uint 345 B string `rlp:"tail"` 346 } 347 348 type tailRaw struct { 349 A uint 350 Tail []RawValue `rlp:"tail"` 351 } 352 353 type tailUint struct { 354 A uint 355 Tail []uint `rlp:"tail"` 356 } 357 358 var ( 359 veryBigInt = big.NewInt(0).Add( 360 big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16), 361 big.NewInt(0xFFFF), 362 ) 363 ) 364 365 type hasIgnoredField struct { 366 A uint 367 B uint `rlp:"-"` 368 C uint 369 } 370 371 var decodeTests = []decodeTest{ 372 //布尔运算 373 {input: "01", ptr: new(bool), value: true}, 374 {input: "80", ptr: new(bool), value: false}, 375 {input: "02", ptr: new(bool), error: "rlp: invalid boolean value: 2"}, 376 377 //整数 378 {input: "05", ptr: new(uint32), value: uint32(5)}, 379 {input: "80", ptr: new(uint32), value: uint32(0)}, 380 {input: "820505", ptr: new(uint32), value: uint32(0x0505)}, 381 {input: "83050505", ptr: new(uint32), value: uint32(0x050505)}, 382 {input: "8405050505", ptr: new(uint32), value: uint32(0x05050505)}, 383 {input: "850505050505", ptr: new(uint32), error: "rlp: input string too long for uint32"}, 384 {input: "C0", ptr: new(uint32), error: "rlp: expected input string or byte for uint32"}, 385 {input: "00", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"}, 386 {input: "8105", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"}, 387 {input: "820004", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"}, 388 {input: "B8020004", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"}, 389 390 //片 391 {input: "C0", ptr: new([]uint), value: []uint{}}, 392 {input: "C80102030405060708", ptr: new([]uint), value: []uint{1, 2, 3, 4, 5, 6, 7, 8}}, 393 {input: "F8020004", ptr: new([]uint), error: "rlp: non-canonical size information for []uint"}, 394 395 //数组 396 {input: "C50102030405", ptr: new([5]uint), value: [5]uint{1, 2, 3, 4, 5}}, 397 {input: "C0", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"}, 398 {input: "C102", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"}, 399 {input: "C6010203040506", ptr: new([5]uint), error: "rlp: input list has too many elements for [5]uint"}, 400 {input: "F8020004", ptr: new([5]uint), error: "rlp: non-canonical size information for [5]uint"}, 401 402 //零大小数组 403 {input: "C0", ptr: new([0]uint), value: [0]uint{}}, 404 {input: "C101", ptr: new([0]uint), error: "rlp: input list has too many elements for [0]uint"}, 405 406 //字节切片 407 {input: "01", ptr: new([]byte), value: []byte{1}}, 408 {input: "80", ptr: new([]byte), value: []byte{}}, 409 {input: "8D6162636465666768696A6B6C6D", ptr: new([]byte), value: []byte("abcdefghijklm")}, 410 {input: "C0", ptr: new([]byte), error: "rlp: expected input string or byte for []uint8"}, 411 {input: "8105", ptr: new([]byte), error: "rlp: non-canonical size information for []uint8"}, 412 413 //字节数组 414 {input: "02", ptr: new([1]byte), value: [1]byte{2}}, 415 {input: "8180", ptr: new([1]byte), value: [1]byte{128}}, 416 {input: "850102030405", ptr: new([5]byte), value: [5]byte{1, 2, 3, 4, 5}}, 417 418 //字节数组错误 419 {input: "02", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"}, 420 {input: "80", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"}, 421 {input: "820000", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"}, 422 {input: "C0", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"}, 423 {input: "C3010203", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"}, 424 {input: "86010203040506", ptr: new([5]byte), error: "rlp: input string too long for [5]uint8"}, 425 {input: "8105", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"}, 426 {input: "817F", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"}, 427 428 //零大小字节数组 429 {input: "80", ptr: new([0]byte), value: [0]byte{}}, 430 {input: "01", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"}, 431 {input: "8101", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"}, 432 433 //串 434 {input: "00", ptr: new(string), value: "\000"}, 435 {input: "8D6162636465666768696A6B6C6D", ptr: new(string), value: "abcdefghijklm"}, 436 {input: "C0", ptr: new(string), error: "rlp: expected input string or byte for string"}, 437 438 //大企业 439 {input: "01", ptr: new(*big.Int), value: big.NewInt(1)}, 440 {input: "89FFFFFFFFFFFFFFFFFF", ptr: new(*big.Int), value: veryBigInt}, 441 {input: "10", ptr: new(big.Int), value: *big.NewInt(16)}, //非指针也有效 442 {input: "C0", ptr: new(*big.Int), error: "rlp: expected input string or byte for *big.Int"}, 443 {input: "820001", ptr: new(big.Int), error: "rlp: non-canonical integer (leading zero bytes) for *big.Int"}, 444 {input: "8105", ptr: new(big.Int), error: "rlp: non-canonical size information for *big.Int"}, 445 446 //结构体 447 { 448 input: "C50583343434", 449 ptr: new(simplestruct), 450 value: simplestruct{5, "444"}, 451 }, 452 { 453 input: "C601C402C203C0", 454 ptr: new(recstruct), 455 value: recstruct{1, &recstruct{2, &recstruct{3, nil}}}, 456 }, 457 458 //结构错误 459 { 460 input: "C0", 461 ptr: new(simplestruct), 462 error: "rlp: too few elements for rlp.simplestruct", 463 }, 464 { 465 input: "C105", 466 ptr: new(simplestruct), 467 error: "rlp: too few elements for rlp.simplestruct", 468 }, 469 { 470 input: "C7C50583343434C0", 471 ptr: new([]*simplestruct), 472 error: "rlp: too few elements for rlp.simplestruct, decoding into ([]*rlp.simplestruct)[1]", 473 }, 474 { 475 input: "83222222", 476 ptr: new(simplestruct), 477 error: "rlp: expected input list for rlp.simplestruct", 478 }, 479 { 480 input: "C3010101", 481 ptr: new(simplestruct), 482 error: "rlp: input list has too many elements for rlp.simplestruct", 483 }, 484 { 485 input: "C501C3C00000", 486 ptr: new(recstruct), 487 error: "rlp: expected input string or byte for uint, decoding into (rlp.recstruct).Child.I", 488 }, 489 { 490 input: "C0", 491 ptr: new(invalidTail1), 492 error: "rlp: invalid struct tag \"tail\" for rlp.invalidTail1.A (must be on last field)", 493 }, 494 { 495 input: "C0", 496 ptr: new(invalidTail2), 497 error: "rlp: invalid struct tag \"tail\" for rlp.invalidTail2.B (field type is not slice)", 498 }, 499 { 500 input: "C50102C20102", 501 ptr: new(tailUint), 502 error: "rlp: expected input string or byte for uint, decoding into (rlp.tailUint).Tail[1]", 503 }, 504 505 //结构标记“tail” 506 { 507 input: "C3010203", 508 ptr: new(tailRaw), 509 value: tailRaw{A: 1, Tail: []RawValue{unhex("02"), unhex("03")}}, 510 }, 511 { 512 input: "C20102", 513 ptr: new(tailRaw), 514 value: tailRaw{A: 1, Tail: []RawValue{unhex("02")}}, 515 }, 516 { 517 input: "C101", 518 ptr: new(tailRaw), 519 value: tailRaw{A: 1, Tail: []RawValue{}}, 520 }, 521 522 //“标签”结构 523 { 524 input: "C20102", 525 ptr: new(hasIgnoredField), 526 value: hasIgnoredField{A: 1, C: 2}, 527 }, 528 529 //RAW值 530 {input: "01", ptr: new(RawValue), value: RawValue(unhex("01"))}, 531 {input: "82FFFF", ptr: new(RawValue), value: RawValue(unhex("82FFFF"))}, 532 {input: "C20102", ptr: new([]RawValue), value: []RawValue{unhex("01"), unhex("02")}}, 533 534 //指针 535 {input: "00", ptr: new(*[]byte), value: &[]byte{0}}, 536 {input: "80", ptr: new(*uint), value: uintp(0)}, 537 {input: "C0", ptr: new(*uint), error: "rlp: expected input string or byte for uint"}, 538 {input: "07", ptr: new(*uint), value: uintp(7)}, 539 {input: "817F", ptr: new(*uint), error: "rlp: non-canonical size information for uint"}, 540 {input: "8180", ptr: new(*uint), value: uintp(0x80)}, 541 {input: "C109", ptr: new(*[]uint), value: &[]uint{9}}, 542 {input: "C58403030303", ptr: new(*[][]byte), value: &[][]byte{{3, 3, 3, 3}}}, 543 544 //检查输入位置是否也为空值。 545 {input: "C3808005", ptr: new([]*uint), value: []*uint{uintp(0), uintp(0), uintp(5)}}, 546 547 //接口{} 548 {input: "00", ptr: new(interface{}), value: []byte{0}}, 549 {input: "01", ptr: new(interface{}), value: []byte{1}}, 550 {input: "80", ptr: new(interface{}), value: []byte{}}, 551 {input: "850505050505", ptr: new(interface{}), value: []byte{5, 5, 5, 5, 5}}, 552 {input: "C0", ptr: new(interface{}), value: []interface{}{}}, 553 {input: "C50183040404", ptr: new(interface{}), value: []interface{}{[]byte{1}, []byte{4, 4, 4}}}, 554 { 555 input: "C3010203", 556 ptr: new([]io.Reader), 557 error: "rlp: type io.Reader is not RLP-serializable", 558 }, 559 560 //模糊崩溃 561 { 562 input: "c330f9c030f93030ce3030303030303030bd303030303030", 563 ptr: new(interface{}), 564 error: "rlp: element is larger than containing list", 565 }, 566 } 567 568 func uintp(i uint) *uint { return &i } 569 570 func runTests(t *testing.T, decode func([]byte, interface{}) error) { 571 for i, test := range decodeTests { 572 input, err := hex.DecodeString(test.input) 573 if err != nil { 574 t.Errorf("test %d: invalid hex input %q", i, test.input) 575 continue 576 } 577 err = decode(input, test.ptr) 578 if err != nil && test.error == "" { 579 t.Errorf("test %d: unexpected Decode error: %v\ndecoding into %T\ninput %q", 580 i, err, test.ptr, test.input) 581 continue 582 } 583 if test.error != "" && fmt.Sprint(err) != test.error { 584 t.Errorf("test %d: Decode error mismatch\ngot %v\nwant %v\ndecoding into %T\ninput %q", 585 i, err, test.error, test.ptr, test.input) 586 continue 587 } 588 deref := reflect.ValueOf(test.ptr).Elem().Interface() 589 if err == nil && !reflect.DeepEqual(deref, test.value) { 590 t.Errorf("test %d: value mismatch\ngot %#v\nwant %#v\ndecoding into %T\ninput %q", 591 i, deref, test.value, test.ptr, test.input) 592 } 593 } 594 } 595 596 func TestDecodeWithByteReader(t *testing.T) { 597 runTests(t, func(input []byte, into interface{}) error { 598 return Decode(bytes.NewReader(input), into) 599 }) 600 } 601 602 //PlainReader从字节片读取,但不读取 603 //实现readbyte。它也不被 604 //尺寸验证。这对于测试解码器 605 //在非缓冲输入流上运行。 606 type plainReader []byte 607 608 func newPlainReader(b []byte) io.Reader { 609 return (*plainReader)(&b) 610 } 611 612 func (r *plainReader) Read(buf []byte) (n int, err error) { 613 if len(*r) == 0 { 614 return 0, io.EOF 615 } 616 n = copy(buf, *r) 617 *r = (*r)[n:] 618 return n, nil 619 } 620 621 func TestDecodeWithNonByteReader(t *testing.T) { 622 runTests(t, func(input []byte, into interface{}) error { 623 return Decode(newPlainReader(input), into) 624 }) 625 } 626 627 func TestDecodeStreamReset(t *testing.T) { 628 s := NewStream(nil, 0) 629 runTests(t, func(input []byte, into interface{}) error { 630 s.Reset(bytes.NewReader(input), 0) 631 return s.Decode(into) 632 }) 633 } 634 635 type testDecoder struct{ called bool } 636 637 func (t *testDecoder) DecodeRLP(s *Stream) error { 638 if _, err := s.Uint(); err != nil { 639 return err 640 } 641 t.called = true 642 return nil 643 } 644 645 func TestDecodeDecoder(t *testing.T) { 646 var s struct { 647 T1 testDecoder 648 T2 *testDecoder 649 T3 **testDecoder 650 } 651 if err := Decode(bytes.NewReader(unhex("C3010203")), &s); err != nil { 652 t.Fatalf("Decode error: %v", err) 653 } 654 655 if !s.T1.called { 656 t.Errorf("DecodeRLP was not called for (non-pointer) testDecoder") 657 } 658 659 if s.T2 == nil { 660 t.Errorf("*testDecoder has not been allocated") 661 } else if !s.T2.called { 662 t.Errorf("DecodeRLP was not called for *testDecoder") 663 } 664 665 if s.T3 == nil || *s.T3 == nil { 666 t.Errorf("**testDecoder has not been allocated") 667 } else if !(*s.T3).called { 668 t.Errorf("DecodeRLP was not called for **testDecoder") 669 } 670 } 671 672 type byteDecoder byte 673 674 func (bd *byteDecoder) DecodeRLP(s *Stream) error { 675 _, err := s.Uint() 676 *bd = 255 677 return err 678 } 679 680 func (bd byteDecoder) called() bool { 681 return bd == 255 682 } 683 684 //此测试验证字节片/字节数组逻辑 685 //不适用于实现解码器的元素类型。 686 func TestDecoderInByteSlice(t *testing.T) { 687 var slice []byteDecoder 688 if err := Decode(bytes.NewReader(unhex("C101")), &slice); err != nil { 689 t.Errorf("unexpected Decode error %v", err) 690 } else if !slice[0].called() { 691 t.Errorf("DecodeRLP not called for slice element") 692 } 693 694 var array [1]byteDecoder 695 if err := Decode(bytes.NewReader(unhex("C101")), &array); err != nil { 696 t.Errorf("unexpected Decode error %v", err) 697 } else if !array[0].called() { 698 t.Errorf("DecodeRLP not called for array element") 699 } 700 } 701 702 func ExampleDecode() { 703 input, _ := hex.DecodeString("C90A1486666F6F626172") 704 705 type example struct { 706 A, B uint 707 private uint //忽略私有字段 708 String string 709 } 710 711 var s example 712 err := Decode(bytes.NewReader(input), &s) 713 if err != nil { 714 fmt.Printf("Error: %v\n", err) 715 } else { 716 fmt.Printf("Decoded value: %#v\n", s) 717 } 718 //输出: 719 //解码值:rlp。示例a:0xa,b:0x14,private:0x0,string:“foobar” 720 } 721 722 func ExampleDecode_structTagNil() { 723 //在本例中,我们将使用“nil”结构标记来更改 724 //如何解码指针类型字段。输入包含一个RLP 725 //一个元素的列表,空字符串。 726 input := []byte{0xC1, 0x80} 727 728 //此类型使用常规规则。 729 //空输入字符串被解码为指向空go字符串的指针。 730 var normalRules struct { 731 String *string 732 } 733 Decode(bytes.NewReader(input), &normalRules) 734 fmt.Printf("normal: String = %q\n", *normalRules.String) 735 736 //此类型使用struct标记。 737 //空输入字符串被解码为零指针。 738 var withEmptyOK struct { 739 String *string `rlp:"nil"` 740 } 741 Decode(bytes.NewReader(input), &withEmptyOK) 742 fmt.Printf("with nil tag: String = %v\n", withEmptyOK.String) 743 744 //输出: 745 //正常:字符串=“” 746 //带nil标记:string=<nil> 747 } 748 749 func ExampleStream() { 750 input, _ := hex.DecodeString("C90A1486666F6F626172") 751 s := NewStream(bytes.NewReader(input), 0) 752 753 //检查前面有什么价值 754 kind, size, _ := s.Kind() 755 fmt.Printf("Kind: %v size:%d\n", kind, size) 756 757 //进入列表 758 if _, err := s.List(); err != nil { 759 fmt.Printf("List error: %v\n", err) 760 return 761 } 762 763 //解码元件 764 fmt.Println(s.Uint()) 765 fmt.Println(s.Uint()) 766 fmt.Println(s.Bytes()) 767 768 //确认列表结尾 769 if err := s.ListEnd(); err != nil { 770 fmt.Printf("ListEnd error: %v\n", err) 771 } 772 //输出: 773 //种类:列表大小:9 774 //10 <NIL > 775 //20 <NIL > 776 //[102 111 111 98 97 114]<nil> 777 } 778 779 func BenchmarkDecode(b *testing.B) { 780 enc := encodeTestSlice(90000) 781 b.SetBytes(int64(len(enc))) 782 b.ReportAllocs() 783 b.ResetTimer() 784 785 for i := 0; i < b.N; i++ { 786 var s []uint 787 r := bytes.NewReader(enc) 788 if err := Decode(r, &s); err != nil { 789 b.Fatalf("Decode error: %v", err) 790 } 791 } 792 } 793 794 func BenchmarkDecodeIntSliceReuse(b *testing.B) { 795 enc := encodeTestSlice(100000) 796 b.SetBytes(int64(len(enc))) 797 b.ReportAllocs() 798 b.ResetTimer() 799 800 var s []uint 801 for i := 0; i < b.N; i++ { 802 r := bytes.NewReader(enc) 803 if err := Decode(r, &s); err != nil { 804 b.Fatalf("Decode error: %v", err) 805 } 806 } 807 } 808 809 func encodeTestSlice(n uint) []byte { 810 s := make([]uint, n) 811 for i := uint(0); i < n; i++ { 812 s[i] = i 813 } 814 b, err := EncodeToBytes(s) 815 if err != nil { 816 panic(fmt.Sprintf("encode error: %v", err)) 817 } 818 return b 819 } 820 821 func unhex(str string) []byte { 822 b, err := hex.DecodeString(strings.Replace(str, " ", "", -1)) 823 if err != nil { 824 panic(fmt.Sprintf("invalid hex string: %q", str)) 825 } 826 return b 827 }