github.com/theQRL/go-zond@v0.2.1/core/rawdb/accessors_chain_test.go (about) 1 // Copyright 2018 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 rawdb 18 19 import ( 20 "bytes" 21 "encoding/hex" 22 "fmt" 23 "math/big" 24 "math/rand" 25 "os" 26 "reflect" 27 "testing" 28 29 "github.com/theQRL/go-zond/common" 30 "github.com/theQRL/go-zond/core/types" 31 "github.com/theQRL/go-zond/crypto/pqcrypto" 32 "github.com/theQRL/go-zond/params" 33 "github.com/theQRL/go-zond/rlp" 34 "golang.org/x/crypto/sha3" 35 ) 36 37 // Tests block header storage and retrieval operations. 38 func TestHeaderStorage(t *testing.T) { 39 db := NewMemoryDatabase() 40 41 // Create a test header to move around the database and make sure it's really new 42 header := &types.Header{ 43 Number: big.NewInt(42), 44 Extra: []byte("test header"), 45 BaseFee: common.Big0, 46 WithdrawalsHash: &types.EmptyWithdrawalsHash, 47 } 48 if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil { 49 t.Fatalf("Non existent header returned: %v", entry) 50 } 51 // Write and verify the header in the database 52 WriteHeader(db, header) 53 if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry == nil { 54 t.Fatalf("Stored header not found") 55 } else if entry.Hash() != header.Hash() { 56 t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, header) 57 } 58 if entry := ReadHeaderRLP(db, header.Hash(), header.Number.Uint64()); entry == nil { 59 t.Fatalf("Stored header RLP not found") 60 } else { 61 hasher := sha3.NewLegacyKeccak256() 62 hasher.Write(entry) 63 64 if hash := common.BytesToHash(hasher.Sum(nil)); hash != header.Hash() { 65 t.Fatalf("Retrieved RLP header mismatch: have %v, want %v", entry, header) 66 } 67 } 68 // Delete the header and verify the execution 69 DeleteHeader(db, header.Hash(), header.Number.Uint64()) 70 if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil { 71 t.Fatalf("Deleted header returned: %v", entry) 72 } 73 } 74 75 // Tests block body storage and retrieval operations. 76 func TestBodyStorage(t *testing.T) { 77 db := NewMemoryDatabase() 78 79 // Create a test body to move around the database and make sure it's really new 80 body := &types.Body{} 81 82 hasher := sha3.NewLegacyKeccak256() 83 rlp.Encode(hasher, body) 84 hash := common.BytesToHash(hasher.Sum(nil)) 85 86 if entry := ReadBody(db, hash, 0); entry != nil { 87 t.Fatalf("Non existent body returned: %v", entry) 88 } 89 // Write and verify the body in the database 90 WriteBody(db, hash, 0, body) 91 if entry := ReadBody(db, hash, 0); entry == nil { 92 t.Fatalf("Stored body not found") 93 } else if types.DeriveSha(types.Transactions(entry.Transactions), newTestHasher()) != types.DeriveSha(types.Transactions(body.Transactions), newTestHasher()) { 94 t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body) 95 } 96 if entry := ReadBodyRLP(db, hash, 0); entry == nil { 97 t.Fatalf("Stored body RLP not found") 98 } else { 99 hasher := sha3.NewLegacyKeccak256() 100 hasher.Write(entry) 101 102 if calc := common.BytesToHash(hasher.Sum(nil)); calc != hash { 103 t.Fatalf("Retrieved RLP body mismatch: have %v, want %v", entry, body) 104 } 105 } 106 // Delete the body and verify the execution 107 DeleteBody(db, hash, 0) 108 if entry := ReadBody(db, hash, 0); entry != nil { 109 t.Fatalf("Deleted body returned: %v", entry) 110 } 111 } 112 113 // Tests block storage and retrieval operations. 114 func TestBlockStorage(t *testing.T) { 115 db := NewMemoryDatabase() 116 117 // Create a test block to move around the database and make sure it's really new 118 block := types.NewBlockWithHeader(&types.Header{ 119 Extra: []byte("test block"), 120 TxHash: types.EmptyTxsHash, 121 ReceiptHash: types.EmptyReceiptsHash, 122 BaseFee: common.Big0, 123 WithdrawalsHash: &types.EmptyWithdrawalsHash, 124 }) 125 if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil { 126 t.Fatalf("Non existent block returned: %v", entry) 127 } 128 if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil { 129 t.Fatalf("Non existent header returned: %v", entry) 130 } 131 if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil { 132 t.Fatalf("Non existent body returned: %v", entry) 133 } 134 // Write and verify the block in the database 135 WriteBlock(db, block) 136 if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil { 137 t.Fatalf("Stored block not found") 138 } else if entry.Hash() != block.Hash() { 139 t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block) 140 } 141 if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry == nil { 142 t.Fatalf("Stored header not found") 143 } else if entry.Hash() != block.Header().Hash() { 144 t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, block.Header()) 145 } 146 if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry == nil { 147 t.Fatalf("Stored body not found") 148 } else if types.DeriveSha(types.Transactions(entry.Transactions), newTestHasher()) != types.DeriveSha(block.Transactions(), newTestHasher()) { 149 t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, block.Body()) 150 } 151 // Delete the block and verify the execution 152 DeleteBlock(db, block.Hash(), block.NumberU64()) 153 if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil { 154 t.Fatalf("Deleted block returned: %v", entry) 155 } 156 if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil { 157 t.Fatalf("Deleted header returned: %v", entry) 158 } 159 if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil { 160 t.Fatalf("Deleted body returned: %v", entry) 161 } 162 } 163 164 // Tests that partial block contents don't get reassembled into full blocks. 165 func TestPartialBlockStorage(t *testing.T) { 166 db := NewMemoryDatabase() 167 block := types.NewBlockWithHeader(&types.Header{ 168 Extra: []byte("test block"), 169 TxHash: types.EmptyTxsHash, 170 ReceiptHash: types.EmptyReceiptsHash, 171 BaseFee: common.Big0, 172 WithdrawalsHash: &types.EmptyWithdrawalsHash, 173 }) 174 // Store a header and check that it's not recognized as a block 175 WriteHeader(db, block.Header()) 176 if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil { 177 t.Fatalf("Non existent block returned: %v", entry) 178 } 179 DeleteHeader(db, block.Hash(), block.NumberU64()) 180 181 // Store a body and check that it's not recognized as a block 182 WriteBody(db, block.Hash(), block.NumberU64(), block.Body()) 183 if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil { 184 t.Fatalf("Non existent block returned: %v", entry) 185 } 186 DeleteBody(db, block.Hash(), block.NumberU64()) 187 188 // Store a header and a body separately and check reassembly 189 WriteHeader(db, block.Header()) 190 WriteBody(db, block.Hash(), block.NumberU64(), block.Body()) 191 192 if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil { 193 t.Fatalf("Stored block not found") 194 } else if entry.Hash() != block.Hash() { 195 t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block) 196 } 197 } 198 199 // Tests block storage and retrieval operations. 200 func TestBadBlockStorage(t *testing.T) { 201 db := NewMemoryDatabase() 202 203 // Create a test block to move around the database and make sure it's really new 204 block := types.NewBlockWithHeader(&types.Header{ 205 Number: big.NewInt(1), 206 Extra: []byte("bad block"), 207 TxHash: types.EmptyTxsHash, 208 ReceiptHash: types.EmptyReceiptsHash, 209 BaseFee: common.Big0, 210 WithdrawalsHash: &types.EmptyWithdrawalsHash, 211 }) 212 if entry := ReadBadBlock(db, block.Hash()); entry != nil { 213 t.Fatalf("Non existent block returned: %v", entry) 214 } 215 // Write and verify the block in the database 216 WriteBadBlock(db, block) 217 if entry := ReadBadBlock(db, block.Hash()); entry == nil { 218 t.Fatalf("Stored block not found") 219 } else if entry.Hash() != block.Hash() { 220 t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block) 221 } 222 // Write one more bad block 223 blockTwo := types.NewBlockWithHeader(&types.Header{ 224 Number: big.NewInt(2), 225 Extra: []byte("bad block two"), 226 TxHash: types.EmptyTxsHash, 227 ReceiptHash: types.EmptyReceiptsHash, 228 BaseFee: common.Big0, 229 WithdrawalsHash: &types.EmptyWithdrawalsHash, 230 }) 231 WriteBadBlock(db, blockTwo) 232 233 // Write the block one again, should be filtered out. 234 WriteBadBlock(db, block) 235 badBlocks := ReadAllBadBlocks(db) 236 if len(badBlocks) != 2 { 237 t.Fatalf("Failed to load all bad blocks") 238 } 239 240 // Write a bunch of bad blocks, all the blocks are should sorted 241 // in reverse order. The extra blocks should be truncated. 242 for _, n := range rand.Perm(100) { 243 block := types.NewBlockWithHeader(&types.Header{ 244 Number: big.NewInt(int64(n)), 245 Extra: []byte("bad block"), 246 TxHash: types.EmptyTxsHash, 247 ReceiptHash: types.EmptyReceiptsHash, 248 BaseFee: common.Big0, 249 WithdrawalsHash: &types.EmptyWithdrawalsHash, 250 }) 251 WriteBadBlock(db, block) 252 } 253 badBlocks = ReadAllBadBlocks(db) 254 if len(badBlocks) != badBlockToKeep { 255 t.Fatalf("The number of persised bad blocks in incorrect %d", len(badBlocks)) 256 } 257 for i := 0; i < len(badBlocks)-1; i++ { 258 if badBlocks[i].NumberU64() < badBlocks[i+1].NumberU64() { 259 t.Fatalf("The bad blocks are not sorted #[%d](%d) < #[%d](%d)", i, i+1, badBlocks[i].NumberU64(), badBlocks[i+1].NumberU64()) 260 } 261 } 262 263 // Delete all bad blocks 264 DeleteBadBlocks(db) 265 badBlocks = ReadAllBadBlocks(db) 266 if len(badBlocks) != 0 { 267 t.Fatalf("Failed to delete bad blocks") 268 } 269 } 270 271 // Tests that canonical numbers can be mapped to hashes and retrieved. 272 func TestCanonicalMappingStorage(t *testing.T) { 273 db := NewMemoryDatabase() 274 275 // Create a test canonical number and assigned hash to move around 276 hash, number := common.Hash{0: 0xff}, uint64(314) 277 if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) { 278 t.Fatalf("Non existent canonical mapping returned: %v", entry) 279 } 280 // Write and verify the TD in the database 281 WriteCanonicalHash(db, hash, number) 282 if entry := ReadCanonicalHash(db, number); entry == (common.Hash{}) { 283 t.Fatalf("Stored canonical mapping not found") 284 } else if entry != hash { 285 t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash) 286 } 287 // Delete the TD and verify the execution 288 DeleteCanonicalHash(db, number) 289 if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) { 290 t.Fatalf("Deleted canonical mapping returned: %v", entry) 291 } 292 } 293 294 // Tests that head headers and head blocks can be assigned, individually. 295 func TestHeadStorage(t *testing.T) { 296 db := NewMemoryDatabase() 297 298 blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")}) 299 blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")}) 300 blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")}) 301 302 // Check that no head entries are in a pristine database 303 if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) { 304 t.Fatalf("Non head header entry returned: %v", entry) 305 } 306 if entry := ReadHeadBlockHash(db); entry != (common.Hash{}) { 307 t.Fatalf("Non head block entry returned: %v", entry) 308 } 309 if entry := ReadHeadFastBlockHash(db); entry != (common.Hash{}) { 310 t.Fatalf("Non fast head block entry returned: %v", entry) 311 } 312 // Assign separate entries for the head header and block 313 WriteHeadHeaderHash(db, blockHead.Hash()) 314 WriteHeadBlockHash(db, blockFull.Hash()) 315 WriteHeadFastBlockHash(db, blockFast.Hash()) 316 317 // Check that both heads are present, and different (i.e. two heads maintained) 318 if entry := ReadHeadHeaderHash(db); entry != blockHead.Hash() { 319 t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash()) 320 } 321 if entry := ReadHeadBlockHash(db); entry != blockFull.Hash() { 322 t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash()) 323 } 324 if entry := ReadHeadFastBlockHash(db); entry != blockFast.Hash() { 325 t.Fatalf("Fast head block hash mismatch: have %v, want %v", entry, blockFast.Hash()) 326 } 327 } 328 329 // Tests that receipts associated with a single block can be stored and retrieved. 330 func TestBlockReceiptStorage(t *testing.T) { 331 db := NewMemoryDatabase() 332 333 // Create a live block since we need metadata to reconstruct the receipt 334 to1, _ := common.NewAddressFromString("Z0000000000000000000000000000000000000001") 335 tx1 := types.NewTx(&types.DynamicFeeTx{ 336 Nonce: 1, 337 To: &to1, 338 Value: big.NewInt(1), 339 Gas: 1, 340 GasFeeCap: big.NewInt(1), 341 Data: nil, 342 }) 343 to2, _ := common.NewAddressFromString("Z0000000000000000000000000000000000000002") 344 tx2 := types.NewTx(&types.DynamicFeeTx{ 345 Nonce: 2, 346 To: &to2, 347 Value: big.NewInt(2), 348 Gas: 2, 349 GasFeeCap: big.NewInt(2), 350 Data: nil, 351 }) 352 353 body := &types.Body{Transactions: types.Transactions{tx1, tx2}} 354 355 // Create the two receipts to manage afterwards 356 receipt1 := &types.Receipt{ 357 Type: 0x02, 358 Status: types.ReceiptStatusFailed, 359 CumulativeGasUsed: 1, 360 Logs: []*types.Log{ 361 {Address: common.BytesToAddress([]byte{0x11})}, 362 {Address: common.BytesToAddress([]byte{0x01, 0x11})}, 363 }, 364 TxHash: tx1.Hash(), 365 ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}), 366 GasUsed: 111111, 367 } 368 receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1}) 369 370 receipt2 := &types.Receipt{ 371 Type: 0x02, 372 PostState: common.Hash{2}.Bytes(), 373 CumulativeGasUsed: 2, 374 Logs: []*types.Log{ 375 {Address: common.BytesToAddress([]byte{0x22})}, 376 {Address: common.BytesToAddress([]byte{0x02, 0x22})}, 377 }, 378 TxHash: tx2.Hash(), 379 ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}), 380 GasUsed: 222222, 381 } 382 receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2}) 383 receipts := []*types.Receipt{receipt1, receipt2} 384 385 // Check that no receipt entries are in a pristine database 386 hash := common.BytesToHash([]byte{0x03, 0x14}) 387 if rs := ReadReceipts(db, hash, 0, 0, params.TestChainConfig); len(rs) != 0 { 388 t.Fatalf("non existent receipts returned: %v", rs) 389 } 390 // Insert the body that corresponds to the receipts 391 WriteBody(db, hash, 0, body) 392 393 // Insert the receipt slice into the database and check presence 394 WriteReceipts(db, hash, 0, receipts) 395 if rs := ReadReceipts(db, hash, 0, 0, params.TestChainConfig); len(rs) == 0 { 396 t.Fatalf("no receipts returned") 397 } else { 398 if err := checkReceiptsRLP(rs, receipts); err != nil { 399 t.Fatalf(err.Error()) 400 } 401 } 402 // Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed) 403 DeleteBody(db, hash, 0) 404 if rs := ReadReceipts(db, hash, 0, 0, params.TestChainConfig); rs != nil { 405 t.Fatalf("receipts returned when body was deleted: %v", rs) 406 } 407 // NOTE(rgeraldes24): this check does not work for typed transactions because 408 // we need the body to derive the receipts computed fields such as the type. 409 // we could call DeriveFields with the required info to do the checkReceiptsRLP 410 // Ensure that receipts without metadata can be returned without the block body too 411 // if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil { 412 // t.Fatalf(err.Error()) 413 // } 414 // Sanity check that body alone without the receipt is a full purge 415 WriteBody(db, hash, 0, body) 416 417 DeleteReceipts(db, hash, 0) 418 if rs := ReadReceipts(db, hash, 0, 0, params.TestChainConfig); len(rs) != 0 { 419 t.Fatalf("deleted receipts returned: %v", rs) 420 } 421 } 422 423 func checkReceiptsRLP(have, want types.Receipts) error { 424 if len(have) != len(want) { 425 return fmt.Errorf("receipts sizes mismatch: have %d, want %d", len(have), len(want)) 426 } 427 for i := 0; i < len(want); i++ { 428 rlpHave, err := rlp.EncodeToBytes(have[i]) 429 if err != nil { 430 return err 431 } 432 rlpWant, err := rlp.EncodeToBytes(want[i]) 433 if err != nil { 434 return err 435 } 436 if !bytes.Equal(rlpHave, rlpWant) { 437 return fmt.Errorf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant)) 438 } 439 } 440 return nil 441 } 442 443 func TestAncientStorage(t *testing.T) { 444 // Freezer style fast import the chain. 445 frdir := t.TempDir() 446 db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false) 447 if err != nil { 448 t.Fatalf("failed to create database with ancient backend") 449 } 450 defer db.Close() 451 452 // Create a test block 453 block := types.NewBlockWithHeader(&types.Header{ 454 Number: big.NewInt(0), 455 Extra: []byte("test block"), 456 TxHash: types.EmptyTxsHash, 457 ReceiptHash: types.EmptyReceiptsHash, 458 }) 459 // Ensure nothing non-existent will be read 460 hash, number := block.Hash(), block.NumberU64() 461 if blob := ReadHeaderRLP(db, hash, number); len(blob) > 0 { 462 t.Fatalf("non existent header returned") 463 } 464 if blob := ReadBodyRLP(db, hash, number); len(blob) > 0 { 465 t.Fatalf("non existent body returned") 466 } 467 if blob := ReadReceiptsRLP(db, hash, number); len(blob) > 0 { 468 t.Fatalf("non existent receipts returned") 469 } 470 471 // Write and verify the header in the database 472 WriteAncientBlocks(db, []*types.Block{block}, []types.Receipts{nil}) 473 474 if blob := ReadHeaderRLP(db, hash, number); len(blob) == 0 { 475 t.Fatalf("no header returned") 476 } 477 if blob := ReadBodyRLP(db, hash, number); len(blob) == 0 { 478 t.Fatalf("no body returned") 479 } 480 if blob := ReadReceiptsRLP(db, hash, number); len(blob) == 0 { 481 t.Fatalf("no receipts returned") 482 } 483 484 // Use a fake hash for data retrieval, nothing should be returned. 485 fakeHash := common.BytesToHash([]byte{0x01, 0x02, 0x03}) 486 if blob := ReadHeaderRLP(db, fakeHash, number); len(blob) != 0 { 487 t.Fatalf("invalid header returned") 488 } 489 if blob := ReadBodyRLP(db, fakeHash, number); len(blob) != 0 { 490 t.Fatalf("invalid body returned") 491 } 492 if blob := ReadReceiptsRLP(db, fakeHash, number); len(blob) != 0 { 493 t.Fatalf("invalid receipts returned") 494 } 495 } 496 497 func TestCanonicalHashIteration(t *testing.T) { 498 var cases = []struct { 499 from, to uint64 500 limit int 501 expect []uint64 502 }{ 503 {1, 8, 0, nil}, 504 {1, 8, 1, []uint64{1}}, 505 {1, 8, 10, []uint64{1, 2, 3, 4, 5, 6, 7}}, 506 {1, 9, 10, []uint64{1, 2, 3, 4, 5, 6, 7, 8}}, 507 {2, 9, 10, []uint64{2, 3, 4, 5, 6, 7, 8}}, 508 {9, 10, 10, nil}, 509 } 510 // Test empty db iteration 511 db := NewMemoryDatabase() 512 numbers, _ := ReadAllCanonicalHashes(db, 0, 10, 10) 513 if len(numbers) != 0 { 514 t.Fatalf("No entry should be returned to iterate an empty db") 515 } 516 // Fill database with testing data. 517 for i := uint64(1); i <= 8; i++ { 518 WriteCanonicalHash(db, common.Hash{}, i) 519 } 520 for i, c := range cases { 521 numbers, _ := ReadAllCanonicalHashes(db, c.from, c.to, c.limit) 522 if !reflect.DeepEqual(numbers, c.expect) { 523 t.Fatalf("Case %d failed, want %v, got %v", i, c.expect, numbers) 524 } 525 } 526 } 527 528 func TestHashesInRange(t *testing.T) { 529 mkHeader := func(number, seq int) *types.Header { 530 h := types.Header{ 531 Number: big.NewInt(int64(number)), 532 GasLimit: uint64(seq), 533 } 534 return &h 535 } 536 db := NewMemoryDatabase() 537 // For each number, write N versions of that particular number 538 total := 0 539 for i := 0; i < 15; i++ { 540 for ii := 0; ii < i; ii++ { 541 WriteHeader(db, mkHeader(i, ii)) 542 total++ 543 } 544 } 545 if have, want := len(ReadAllHashesInRange(db, 10, 10)), 10; have != want { 546 t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have) 547 } 548 if have, want := len(ReadAllHashesInRange(db, 10, 9)), 0; have != want { 549 t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have) 550 } 551 if have, want := len(ReadAllHashesInRange(db, 0, 100)), total; have != want { 552 t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have) 553 } 554 if have, want := len(ReadAllHashesInRange(db, 9, 10)), 9+10; have != want { 555 t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have) 556 } 557 if have, want := len(ReadAllHashes(db, 10)), 10; have != want { 558 t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have) 559 } 560 if have, want := len(ReadAllHashes(db, 16)), 0; have != want { 561 t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have) 562 } 563 if have, want := len(ReadAllHashes(db, 1)), 1; have != want { 564 t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have) 565 } 566 } 567 568 // This measures the write speed of the WriteAncientBlocks operation. 569 func BenchmarkWriteAncientBlocks(b *testing.B) { 570 // Open freezer database. 571 frdir := b.TempDir() 572 db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false) 573 if err != nil { 574 b.Fatalf("failed to create database with ancient backend") 575 } 576 defer db.Close() 577 578 // Create the data to insert. The blocks must have consecutive numbers, so we create 579 // all of them ahead of time. However, there is no need to create receipts 580 // individually for each block, just make one batch here and reuse it for all writes. 581 const batchSize = 128 582 const blockTxs = 20 583 allBlocks := makeTestBlocks(b.N, blockTxs) 584 batchReceipts := makeTestReceipts(batchSize, blockTxs) 585 b.ResetTimer() 586 587 // The benchmark loop writes batches of blocks, but note that the total block count is 588 // b.N. This means the resulting ns/op measurement is the time it takes to write a 589 // single block and its associated data. 590 var totalSize int64 591 for i := 0; i < b.N; i += batchSize { 592 length := batchSize 593 if i+batchSize > b.N { 594 length = b.N - i 595 } 596 597 blocks := allBlocks[i : i+length] 598 receipts := batchReceipts[:length] 599 writeSize, err := WriteAncientBlocks(db, blocks, receipts) 600 if err != nil { 601 b.Fatal(err) 602 } 603 totalSize += writeSize 604 } 605 606 // Enable MB/s reporting. 607 b.SetBytes(totalSize / int64(b.N)) 608 } 609 610 // makeTestBlocks creates fake blocks for the ancient write benchmark. 611 func makeTestBlocks(nblock int, txsPerBlock int) []*types.Block { 612 key, _ := pqcrypto.HexToDilithium("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 613 signer := types.LatestSignerForChainID(big.NewInt(8)) 614 615 // Create transactions. 616 txs := make([]*types.Transaction, txsPerBlock) 617 for i := 0; i < len(txs); i++ { 618 var err error 619 to := common.Address{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} 620 txs[i], err = types.SignNewTx(key, signer, &types.DynamicFeeTx{ 621 Nonce: 2, 622 GasFeeCap: big.NewInt(30000), 623 Gas: 0x45454545, 624 To: &to, 625 }) 626 if err != nil { 627 panic(err) 628 } 629 } 630 631 // Create the blocks. 632 blocks := make([]*types.Block, nblock) 633 for i := 0; i < nblock; i++ { 634 header := &types.Header{ 635 Number: big.NewInt(int64(i)), 636 Extra: []byte("test block"), 637 } 638 blocks[i] = types.NewBlockWithHeader(header).WithBody(types.Body{Transactions: txs}) 639 blocks[i].Hash() // pre-cache the block hash 640 } 641 return blocks 642 } 643 644 // makeTestReceipts creates fake receipts for the ancient write benchmark. 645 func makeTestReceipts(n int, nPerBlock int) []types.Receipts { 646 receipts := make([]*types.Receipt, nPerBlock) 647 for i := 0; i < len(receipts); i++ { 648 receipts[i] = &types.Receipt{ 649 Status: types.ReceiptStatusSuccessful, 650 CumulativeGasUsed: 0x888888888, 651 Logs: make([]*types.Log, 5), 652 } 653 } 654 allReceipts := make([]types.Receipts, n) 655 for i := 0; i < n; i++ { 656 allReceipts[i] = receipts 657 } 658 return allReceipts 659 } 660 661 type fullLogRLP struct { 662 Address common.Address 663 Topics []common.Hash 664 Data []byte 665 BlockNumber uint64 666 TxHash common.Hash 667 TxIndex uint 668 BlockHash common.Hash 669 Index uint 670 } 671 672 func newFullLogRLP(l *types.Log) *fullLogRLP { 673 return &fullLogRLP{ 674 Address: l.Address, 675 Topics: l.Topics, 676 Data: l.Data, 677 BlockNumber: l.BlockNumber, 678 TxHash: l.TxHash, 679 TxIndex: l.TxIndex, 680 BlockHash: l.BlockHash, 681 Index: l.Index, 682 } 683 } 684 685 // Tests that logs associated with a single block can be retrieved. 686 func TestReadLogs(t *testing.T) { 687 db := NewMemoryDatabase() 688 689 // Create a live block since we need metadata to reconstruct the receipt 690 to1, _ := common.NewAddressFromString("Z0000000000000000000000000000000000000001") 691 tx1 := types.NewTx(&types.DynamicFeeTx{ 692 Nonce: 1, 693 To: &to1, 694 Value: big.NewInt(1), 695 Gas: 1, 696 GasFeeCap: big.NewInt(1), 697 Data: nil, 698 }) 699 to2, _ := common.NewAddressFromString("Z0000000000000000000000000000000000000002") 700 tx2 := types.NewTx(&types.DynamicFeeTx{ 701 Nonce: 2, 702 To: &to2, 703 Value: big.NewInt(2), 704 Gas: 2, 705 GasFeeCap: big.NewInt(2), 706 Data: nil, 707 }) 708 709 body := &types.Body{Transactions: types.Transactions{tx1, tx2}} 710 711 // Create the two receipts to manage afterwards 712 receipt1 := &types.Receipt{ 713 Status: types.ReceiptStatusFailed, 714 CumulativeGasUsed: 1, 715 Logs: []*types.Log{ 716 {Address: common.BytesToAddress([]byte{0x11})}, 717 {Address: common.BytesToAddress([]byte{0x01, 0x11})}, 718 }, 719 TxHash: tx1.Hash(), 720 ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}), 721 GasUsed: 111111, 722 } 723 receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1}) 724 725 receipt2 := &types.Receipt{ 726 PostState: common.Hash{2}.Bytes(), 727 CumulativeGasUsed: 2, 728 Logs: []*types.Log{ 729 {Address: common.BytesToAddress([]byte{0x22})}, 730 {Address: common.BytesToAddress([]byte{0x02, 0x22})}, 731 }, 732 TxHash: tx2.Hash(), 733 ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}), 734 GasUsed: 222222, 735 } 736 receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2}) 737 receipts := []*types.Receipt{receipt1, receipt2} 738 739 hash := common.BytesToHash([]byte{0x03, 0x14}) 740 // Check that no receipt entries are in a pristine database 741 if rs := ReadReceipts(db, hash, 0, 0, params.TestChainConfig); len(rs) != 0 { 742 t.Fatalf("non existent receipts returned: %v", rs) 743 } 744 // Insert the body that corresponds to the receipts 745 WriteBody(db, hash, 0, body) 746 747 // Insert the receipt slice into the database and check presence 748 WriteReceipts(db, hash, 0, receipts) 749 750 logs := ReadLogs(db, hash, 0) 751 if len(logs) == 0 { 752 t.Fatalf("no logs returned") 753 } 754 if have, want := len(logs), 2; have != want { 755 t.Fatalf("unexpected number of logs returned, have %d want %d", have, want) 756 } 757 if have, want := len(logs[0]), 2; have != want { 758 t.Fatalf("unexpected number of logs[0] returned, have %d want %d", have, want) 759 } 760 if have, want := len(logs[1]), 2; have != want { 761 t.Fatalf("unexpected number of logs[1] returned, have %d want %d", have, want) 762 } 763 764 for i, pr := range receipts { 765 for j, pl := range pr.Logs { 766 rlpHave, err := rlp.EncodeToBytes(newFullLogRLP(logs[i][j])) 767 if err != nil { 768 t.Fatal(err) 769 } 770 rlpWant, err := rlp.EncodeToBytes(newFullLogRLP(pl)) 771 if err != nil { 772 t.Fatal(err) 773 } 774 if !bytes.Equal(rlpHave, rlpWant) { 775 t.Fatalf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant)) 776 } 777 } 778 } 779 } 780 781 func TestDeriveLogFields(t *testing.T) { 782 // Create a few transactions to have receipts for 783 to2, _ := common.NewAddressFromString("Z0000000000000000000000000000000000000002") 784 to3, _ := common.NewAddressFromString("Z0000000000000000000000000000000000000003") 785 txs := types.Transactions{ 786 types.NewTx(&types.DynamicFeeTx{ 787 Nonce: 1, 788 Value: big.NewInt(1), 789 Gas: 1, 790 GasFeeCap: big.NewInt(1), 791 }), 792 types.NewTx(&types.DynamicFeeTx{ 793 To: &to2, 794 Nonce: 2, 795 Value: big.NewInt(2), 796 Gas: 2, 797 GasFeeCap: big.NewInt(2), 798 }), 799 types.NewTx(&types.DynamicFeeTx{ 800 To: &to3, 801 Nonce: 3, 802 Value: big.NewInt(3), 803 Gas: 3, 804 GasFeeCap: big.NewInt(3), 805 }), 806 } 807 // Create the corresponding receipts 808 receipts := []*receiptLogs{ 809 { 810 Logs: []*types.Log{ 811 {Address: common.BytesToAddress([]byte{0x11})}, 812 {Address: common.BytesToAddress([]byte{0x01, 0x11})}, 813 }, 814 }, 815 { 816 Logs: []*types.Log{ 817 {Address: common.BytesToAddress([]byte{0x22})}, 818 {Address: common.BytesToAddress([]byte{0x02, 0x22})}, 819 }, 820 }, 821 { 822 Logs: []*types.Log{ 823 {Address: common.BytesToAddress([]byte{0x33})}, 824 {Address: common.BytesToAddress([]byte{0x03, 0x33})}, 825 }, 826 }, 827 } 828 829 // Derive log metadata fields 830 number := big.NewInt(1) 831 hash := common.BytesToHash([]byte{0x03, 0x14}) 832 if err := deriveLogFields(receipts, hash, number.Uint64(), txs); err != nil { 833 t.Fatal(err) 834 } 835 836 // Iterate over all the computed fields and check that they're correct 837 logIndex := uint(0) 838 for i := range receipts { 839 for j := range receipts[i].Logs { 840 if receipts[i].Logs[j].BlockNumber != number.Uint64() { 841 t.Errorf("receipts[%d].Logs[%d].BlockNumber = %d, want %d", i, j, receipts[i].Logs[j].BlockNumber, number.Uint64()) 842 } 843 if receipts[i].Logs[j].BlockHash != hash { 844 t.Errorf("receipts[%d].Logs[%d].BlockHash = %s, want %s", i, j, receipts[i].Logs[j].BlockHash.String(), hash.String()) 845 } 846 if receipts[i].Logs[j].TxHash != txs[i].Hash() { 847 t.Errorf("receipts[%d].Logs[%d].TxHash = %s, want %s", i, j, receipts[i].Logs[j].TxHash.String(), txs[i].Hash().String()) 848 } 849 if receipts[i].Logs[j].TxIndex != uint(i) { 850 t.Errorf("receipts[%d].Logs[%d].TransactionIndex = %d, want %d", i, j, receipts[i].Logs[j].TxIndex, i) 851 } 852 if receipts[i].Logs[j].Index != logIndex { 853 t.Errorf("receipts[%d].Logs[%d].Index = %d, want %d", i, j, receipts[i].Logs[j].Index, logIndex) 854 } 855 logIndex++ 856 } 857 } 858 } 859 860 func BenchmarkDecodeRLPLogs(b *testing.B) { 861 // Encoded receipts from block 0x14ee094309fbe8f70b65f45ebcc08fb33f126942d97464aad5eb91cfd1e2d269 862 buf, err := os.ReadFile("testdata/stored_receipts.bin") 863 if err != nil { 864 b.Fatal(err) 865 } 866 b.Run("ReceiptForStorage", func(b *testing.B) { 867 b.ReportAllocs() 868 var r []*types.ReceiptForStorage 869 for i := 0; i < b.N; i++ { 870 if err := rlp.DecodeBytes(buf, &r); err != nil { 871 b.Fatal(err) 872 } 873 } 874 }) 875 b.Run("rlpLogs", func(b *testing.B) { 876 b.ReportAllocs() 877 var r []*receiptLogs 878 for i := 0; i < b.N; i++ { 879 if err := rlp.DecodeBytes(buf, &r); err != nil { 880 b.Fatal(err) 881 } 882 } 883 }) 884 } 885 886 func TestHeadersRLPStorage(t *testing.T) { 887 // Have N headers in the freezer 888 frdir := t.TempDir() 889 890 db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false) 891 if err != nil { 892 t.Fatalf("failed to create database with ancient backend") 893 } 894 defer db.Close() 895 // Create blocks 896 var chain []*types.Block 897 var pHash common.Hash 898 for i := 0; i < 100; i++ { 899 block := types.NewBlockWithHeader(&types.Header{ 900 Number: big.NewInt(int64(i)), 901 Extra: []byte("test block"), 902 TxHash: types.EmptyTxsHash, 903 ReceiptHash: types.EmptyReceiptsHash, 904 ParentHash: pHash, 905 BaseFee: common.Big0, 906 WithdrawalsHash: &types.EmptyWithdrawalsHash, 907 }) 908 chain = append(chain, block) 909 pHash = block.Hash() 910 } 911 var receipts []types.Receipts = make([]types.Receipts, 100) 912 // Write first half to ancients 913 WriteAncientBlocks(db, chain[:50], receipts[:50]) 914 // Write second half to db 915 for i := 50; i < 100; i++ { 916 WriteCanonicalHash(db, chain[i].Hash(), chain[i].NumberU64()) 917 WriteBlock(db, chain[i]) 918 } 919 checkSequence := func(from, amount int) { 920 headersRlp := ReadHeaderRange(db, uint64(from), uint64(amount)) 921 if have, want := len(headersRlp), amount; have != want { 922 t.Fatalf("have %d headers, want %d", have, want) 923 } 924 for i, headerRlp := range headersRlp { 925 var header types.Header 926 if err := rlp.DecodeBytes(headerRlp, &header); err != nil { 927 t.Fatal(err) 928 } 929 if have, want := header.Number.Uint64(), uint64(from-i); have != want { 930 t.Fatalf("wrong number, have %d want %d", have, want) 931 } 932 } 933 } 934 checkSequence(99, 20) // Latest block and 19 parents 935 checkSequence(99, 50) // Latest block -> all db blocks 936 checkSequence(99, 51) // Latest block -> one from ancients 937 checkSequence(99, 52) // Latest blocks -> two from ancients 938 checkSequence(50, 2) // One from db, one from ancients 939 checkSequence(49, 1) // One from ancients 940 checkSequence(49, 50) // All ancient ones 941 checkSequence(99, 100) // All blocks 942 checkSequence(0, 1) // Only genesis 943 checkSequence(1, 1) // Only block 1 944 checkSequence(1, 2) // Genesis + block 1 945 }