github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/core/rawdb/accessors_chain.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/binary" 22 "errors" 23 "fmt" 24 "math/big" 25 "slices" 26 27 "github.com/ethereum/go-ethereum/common" 28 "github.com/ethereum/go-ethereum/consensus/misc/eip4844" 29 "github.com/ethereum/go-ethereum/core/types" 30 "github.com/ethereum/go-ethereum/crypto" 31 "github.com/ethereum/go-ethereum/ethdb" 32 "github.com/ethereum/go-ethereum/log" 33 "github.com/ethereum/go-ethereum/params" 34 "github.com/ethereum/go-ethereum/rlp" 35 ) 36 37 // ReadCanonicalHash retrieves the hash assigned to a canonical block number. 38 func ReadCanonicalHash(db ethdb.Reader, number uint64) common.Hash { 39 var data []byte 40 db.ReadAncients(func(reader ethdb.AncientReaderOp) error { 41 data, _ = reader.Ancient(ChainFreezerHashTable, number) 42 if len(data) == 0 { 43 // Get it by hash from leveldb 44 data, _ = db.Get(headerHashKey(number)) 45 } 46 return nil 47 }) 48 return common.BytesToHash(data) 49 } 50 51 // WriteCanonicalHash stores the hash assigned to a canonical block number. 52 func WriteCanonicalHash(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 53 if err := db.Put(headerHashKey(number), hash.Bytes()); err != nil { 54 log.Crit("Failed to store number to hash mapping", "err", err) 55 } 56 } 57 58 // DeleteCanonicalHash removes the number to hash canonical mapping. 59 func DeleteCanonicalHash(db ethdb.KeyValueWriter, number uint64) { 60 if err := db.Delete(headerHashKey(number)); err != nil { 61 log.Crit("Failed to delete number to hash mapping", "err", err) 62 } 63 } 64 65 // ReadAllHashes retrieves all the hashes assigned to blocks at a certain heights, 66 // both canonical and reorged forks included. 67 func ReadAllHashes(db ethdb.Iteratee, number uint64) []common.Hash { 68 prefix := headerKeyPrefix(number) 69 70 hashes := make([]common.Hash, 0, 1) 71 it := db.NewIterator(prefix, nil) 72 defer it.Release() 73 74 for it.Next() { 75 if key := it.Key(); len(key) == len(prefix)+32 { 76 hashes = append(hashes, common.BytesToHash(key[len(key)-32:])) 77 } 78 } 79 return hashes 80 } 81 82 type NumberHash struct { 83 Number uint64 84 Hash common.Hash 85 } 86 87 // ReadAllHashesInRange retrieves all the hashes assigned to blocks at certain 88 // heights, both canonical and reorged forks included. 89 // This method considers both limits to be _inclusive_. 90 func ReadAllHashesInRange(db ethdb.Iteratee, first, last uint64) []*NumberHash { 91 var ( 92 start = encodeBlockNumber(first) 93 keyLength = len(headerPrefix) + 8 + 32 94 hashes = make([]*NumberHash, 0, 1+last-first) 95 it = db.NewIterator(headerPrefix, start) 96 ) 97 defer it.Release() 98 for it.Next() { 99 key := it.Key() 100 if len(key) != keyLength { 101 continue 102 } 103 num := binary.BigEndian.Uint64(key[len(headerPrefix) : len(headerPrefix)+8]) 104 if num > last { 105 break 106 } 107 hash := common.BytesToHash(key[len(key)-32:]) 108 hashes = append(hashes, &NumberHash{num, hash}) 109 } 110 return hashes 111 } 112 113 // ReadAllCanonicalHashes retrieves all canonical number and hash mappings at the 114 // certain chain range. If the accumulated entries reaches the given threshold, 115 // abort the iteration and return the semi-finish result. 116 func ReadAllCanonicalHashes(db ethdb.Iteratee, from uint64, to uint64, limit int) ([]uint64, []common.Hash) { 117 // Short circuit if the limit is 0. 118 if limit == 0 { 119 return nil, nil 120 } 121 var ( 122 numbers []uint64 123 hashes []common.Hash 124 ) 125 // Construct the key prefix of start point. 126 start, end := headerHashKey(from), headerHashKey(to) 127 it := db.NewIterator(nil, start) 128 defer it.Release() 129 130 for it.Next() { 131 if bytes.Compare(it.Key(), end) >= 0 { 132 break 133 } 134 if key := it.Key(); len(key) == len(headerPrefix)+8+1 && bytes.Equal(key[len(key)-1:], headerHashSuffix) { 135 numbers = append(numbers, binary.BigEndian.Uint64(key[len(headerPrefix):len(headerPrefix)+8])) 136 hashes = append(hashes, common.BytesToHash(it.Value())) 137 // If the accumulated entries reaches the limit threshold, return. 138 if len(numbers) >= limit { 139 break 140 } 141 } 142 } 143 return numbers, hashes 144 } 145 146 // ReadHeaderNumber returns the header number assigned to a hash. 147 func ReadHeaderNumber(db ethdb.KeyValueReader, hash common.Hash) *uint64 { 148 data, _ := db.Get(headerNumberKey(hash)) 149 if len(data) != 8 { 150 return nil 151 } 152 number := binary.BigEndian.Uint64(data) 153 return &number 154 } 155 156 // WriteHeaderNumber stores the hash->number mapping. 157 func WriteHeaderNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 158 key := headerNumberKey(hash) 159 enc := encodeBlockNumber(number) 160 if err := db.Put(key, enc); err != nil { 161 log.Crit("Failed to store hash to number mapping", "err", err) 162 } 163 } 164 165 // DeleteHeaderNumber removes hash->number mapping. 166 func DeleteHeaderNumber(db ethdb.KeyValueWriter, hash common.Hash) { 167 if err := db.Delete(headerNumberKey(hash)); err != nil { 168 log.Crit("Failed to delete hash to number mapping", "err", err) 169 } 170 } 171 172 // ReadHeadHeaderHash retrieves the hash of the current canonical head header. 173 func ReadHeadHeaderHash(db ethdb.KeyValueReader) common.Hash { 174 data, _ := db.Get(headHeaderKey) 175 if len(data) == 0 { 176 return common.Hash{} 177 } 178 return common.BytesToHash(data) 179 } 180 181 // WriteHeadHeaderHash stores the hash of the current canonical head header. 182 func WriteHeadHeaderHash(db ethdb.KeyValueWriter, hash common.Hash) { 183 if err := db.Put(headHeaderKey, hash.Bytes()); err != nil { 184 log.Crit("Failed to store last header's hash", "err", err) 185 } 186 } 187 188 // ReadHeadBlockHash retrieves the hash of the current canonical head block. 189 func ReadHeadBlockHash(db ethdb.KeyValueReader) common.Hash { 190 data, _ := db.Get(headBlockKey) 191 if len(data) == 0 { 192 return common.Hash{} 193 } 194 return common.BytesToHash(data) 195 } 196 197 // WriteHeadBlockHash stores the head block's hash. 198 func WriteHeadBlockHash(db ethdb.KeyValueWriter, hash common.Hash) { 199 if err := db.Put(headBlockKey, hash.Bytes()); err != nil { 200 log.Crit("Failed to store last block's hash", "err", err) 201 } 202 } 203 204 // ReadHeadFastBlockHash retrieves the hash of the current fast-sync head block. 205 func ReadHeadFastBlockHash(db ethdb.KeyValueReader) common.Hash { 206 data, _ := db.Get(headFastBlockKey) 207 if len(data) == 0 { 208 return common.Hash{} 209 } 210 return common.BytesToHash(data) 211 } 212 213 // WriteHeadFastBlockHash stores the hash of the current fast-sync head block. 214 func WriteHeadFastBlockHash(db ethdb.KeyValueWriter, hash common.Hash) { 215 if err := db.Put(headFastBlockKey, hash.Bytes()); err != nil { 216 log.Crit("Failed to store last fast block's hash", "err", err) 217 } 218 } 219 220 // ReadFinalizedBlockHash retrieves the hash of the finalized block. 221 func ReadFinalizedBlockHash(db ethdb.KeyValueReader) common.Hash { 222 data, _ := db.Get(headFinalizedBlockKey) 223 if len(data) == 0 { 224 return common.Hash{} 225 } 226 return common.BytesToHash(data) 227 } 228 229 // WriteFinalizedBlockHash stores the hash of the finalized block. 230 func WriteFinalizedBlockHash(db ethdb.KeyValueWriter, hash common.Hash) { 231 if err := db.Put(headFinalizedBlockKey, hash.Bytes()); err != nil { 232 log.Crit("Failed to store last finalized block's hash", "err", err) 233 } 234 } 235 236 // ReadLastPivotNumber retrieves the number of the last pivot block. If the node 237 // full synced, the last pivot will always be nil. 238 func ReadLastPivotNumber(db ethdb.KeyValueReader) *uint64 { 239 data, _ := db.Get(lastPivotKey) 240 if len(data) == 0 { 241 return nil 242 } 243 var pivot uint64 244 if err := rlp.DecodeBytes(data, &pivot); err != nil { 245 log.Error("Invalid pivot block number in database", "err", err) 246 return nil 247 } 248 return &pivot 249 } 250 251 // WriteLastPivotNumber stores the number of the last pivot block. 252 func WriteLastPivotNumber(db ethdb.KeyValueWriter, pivot uint64) { 253 enc, err := rlp.EncodeToBytes(pivot) 254 if err != nil { 255 log.Crit("Failed to encode pivot block number", "err", err) 256 } 257 if err := db.Put(lastPivotKey, enc); err != nil { 258 log.Crit("Failed to store pivot block number", "err", err) 259 } 260 } 261 262 // ReadTxIndexTail retrieves the number of oldest indexed block 263 // whose transaction indices has been indexed. 264 func ReadTxIndexTail(db ethdb.KeyValueReader) *uint64 { 265 data, _ := db.Get(txIndexTailKey) 266 if len(data) != 8 { 267 return nil 268 } 269 number := binary.BigEndian.Uint64(data) 270 return &number 271 } 272 273 // WriteTxIndexTail stores the number of oldest indexed block 274 // into database. 275 func WriteTxIndexTail(db ethdb.KeyValueWriter, number uint64) { 276 if err := db.Put(txIndexTailKey, encodeBlockNumber(number)); err != nil { 277 log.Crit("Failed to store the transaction index tail", "err", err) 278 } 279 } 280 281 // ReadHeaderRange returns the rlp-encoded headers, starting at 'number', and going 282 // backwards towards genesis. This method assumes that the caller already has 283 // placed a cap on count, to prevent DoS issues. 284 // Since this method operates in head-towards-genesis mode, it will return an empty 285 // slice in case the head ('number') is missing. Hence, the caller must ensure that 286 // the head ('number') argument is actually an existing header. 287 // 288 // N.B: Since the input is a number, as opposed to a hash, it's implicit that 289 // this method only operates on canon headers. 290 func ReadHeaderRange(db ethdb.Reader, number uint64, count uint64) []rlp.RawValue { 291 var rlpHeaders []rlp.RawValue 292 if count == 0 { 293 return rlpHeaders 294 } 295 i := number 296 if count-1 > number { 297 // It's ok to request block 0, 1 item 298 count = number + 1 299 } 300 limit, _ := db.Ancients() 301 // First read live blocks 302 if i >= limit { 303 // If we need to read live blocks, we need to figure out the hash first 304 hash := ReadCanonicalHash(db, number) 305 for ; i >= limit && count > 0; i-- { 306 if data, _ := db.Get(headerKey(i, hash)); len(data) > 0 { 307 rlpHeaders = append(rlpHeaders, data) 308 // Get the parent hash for next query 309 hash = types.HeaderParentHashFromRLP(data) 310 } else { 311 break // Maybe got moved to ancients 312 } 313 count-- 314 } 315 } 316 if count == 0 { 317 return rlpHeaders 318 } 319 // read remaining from ancients, cap at 2M 320 data, err := db.AncientRange(ChainFreezerHeaderTable, i+1-count, count, 2*1024*1024) 321 if err != nil { 322 log.Error("Failed to read headers from freezer", "err", err) 323 return rlpHeaders 324 } 325 if uint64(len(data)) != count { 326 log.Warn("Incomplete read of headers from freezer", "wanted", count, "read", len(data)) 327 return rlpHeaders 328 } 329 // The data is on the order [h, h+1, .., n] -- reordering needed 330 for i := range data { 331 rlpHeaders = append(rlpHeaders, data[len(data)-1-i]) 332 } 333 return rlpHeaders 334 } 335 336 // ReadHeaderRLP retrieves a block header in its raw RLP database encoding. 337 func ReadHeaderRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue { 338 var data []byte 339 db.ReadAncients(func(reader ethdb.AncientReaderOp) error { 340 // First try to look up the data in ancient database. Extra hash 341 // comparison is necessary since ancient database only maintains 342 // the canonical data. 343 data, _ = reader.Ancient(ChainFreezerHeaderTable, number) 344 if len(data) > 0 && crypto.Keccak256Hash(data) == hash { 345 return nil 346 } 347 // If not, try reading from leveldb 348 data, _ = db.Get(headerKey(number, hash)) 349 return nil 350 }) 351 return data 352 } 353 354 // HasHeader verifies the existence of a block header corresponding to the hash. 355 func HasHeader(db ethdb.Reader, hash common.Hash, number uint64) bool { 356 if isCanon(db, number, hash) { 357 return true 358 } 359 if has, err := db.Has(headerKey(number, hash)); !has || err != nil { 360 return false 361 } 362 return true 363 } 364 365 // ReadHeader retrieves the block header corresponding to the hash. 366 func ReadHeader(db ethdb.Reader, hash common.Hash, number uint64) *types.Header { 367 data := ReadHeaderRLP(db, hash, number) 368 if len(data) == 0 { 369 return nil 370 } 371 header := new(types.Header) 372 if err := rlp.DecodeBytes(data, header); err != nil { 373 log.Error("Invalid block header RLP", "hash", hash, "err", err) 374 return nil 375 } 376 return header 377 } 378 379 // WriteHeader stores a block header into the database and also stores the hash- 380 // to-number mapping. 381 func WriteHeader(db ethdb.KeyValueWriter, header *types.Header) { 382 var ( 383 hash = header.Hash() 384 number = header.Number.Uint64() 385 ) 386 // Write the hash -> number mapping 387 WriteHeaderNumber(db, hash, number) 388 389 // Write the encoded header 390 data, err := rlp.EncodeToBytes(header) 391 if err != nil { 392 log.Crit("Failed to RLP encode header", "err", err) 393 } 394 key := headerKey(number, hash) 395 if err := db.Put(key, data); err != nil { 396 log.Crit("Failed to store header", "err", err) 397 } 398 } 399 400 // DeleteHeader removes all block header data associated with a hash. 401 func DeleteHeader(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 402 deleteHeaderWithoutNumber(db, hash, number) 403 if err := db.Delete(headerNumberKey(hash)); err != nil { 404 log.Crit("Failed to delete hash to number mapping", "err", err) 405 } 406 } 407 408 // deleteHeaderWithoutNumber removes only the block header but does not remove 409 // the hash to number mapping. 410 func deleteHeaderWithoutNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 411 if err := db.Delete(headerKey(number, hash)); err != nil { 412 log.Crit("Failed to delete header", "err", err) 413 } 414 } 415 416 // isCanon is an internal utility method, to check whether the given number/hash 417 // is part of the ancient (canon) set. 418 func isCanon(reader ethdb.AncientReaderOp, number uint64, hash common.Hash) bool { 419 h, err := reader.Ancient(ChainFreezerHashTable, number) 420 if err != nil { 421 return false 422 } 423 return bytes.Equal(h, hash[:]) 424 } 425 426 // ReadBodyRLP retrieves the block body (transactions and uncles) in RLP encoding. 427 func ReadBodyRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue { 428 // First try to look up the data in ancient database. Extra hash 429 // comparison is necessary since ancient database only maintains 430 // the canonical data. 431 var data []byte 432 db.ReadAncients(func(reader ethdb.AncientReaderOp) error { 433 // Check if the data is in ancients 434 if isCanon(reader, number, hash) { 435 data, _ = reader.Ancient(ChainFreezerBodiesTable, number) 436 return nil 437 } 438 // If not, try reading from leveldb 439 data, _ = db.Get(blockBodyKey(number, hash)) 440 return nil 441 }) 442 return data 443 } 444 445 // ReadCanonicalBodyRLP retrieves the block body (transactions and uncles) for the canonical 446 // block at number, in RLP encoding. 447 func ReadCanonicalBodyRLP(db ethdb.Reader, number uint64) rlp.RawValue { 448 var data []byte 449 db.ReadAncients(func(reader ethdb.AncientReaderOp) error { 450 data, _ = reader.Ancient(ChainFreezerBodiesTable, number) 451 if len(data) > 0 { 452 return nil 453 } 454 // Block is not in ancients, read from leveldb by hash and number. 455 // Note: ReadCanonicalHash cannot be used here because it also 456 // calls ReadAncients internally. 457 hash, _ := db.Get(headerHashKey(number)) 458 data, _ = db.Get(blockBodyKey(number, common.BytesToHash(hash))) 459 return nil 460 }) 461 return data 462 } 463 464 // WriteBodyRLP stores an RLP encoded block body into the database. 465 func WriteBodyRLP(db ethdb.KeyValueWriter, hash common.Hash, number uint64, rlp rlp.RawValue) { 466 if err := db.Put(blockBodyKey(number, hash), rlp); err != nil { 467 log.Crit("Failed to store block body", "err", err) 468 } 469 } 470 471 // HasBody verifies the existence of a block body corresponding to the hash. 472 func HasBody(db ethdb.Reader, hash common.Hash, number uint64) bool { 473 if isCanon(db, number, hash) { 474 return true 475 } 476 if has, err := db.Has(blockBodyKey(number, hash)); !has || err != nil { 477 return false 478 } 479 return true 480 } 481 482 // ReadBody retrieves the block body corresponding to the hash. 483 func ReadBody(db ethdb.Reader, hash common.Hash, number uint64) *types.Body { 484 data := ReadBodyRLP(db, hash, number) 485 if len(data) == 0 { 486 return nil 487 } 488 body := new(types.Body) 489 if err := rlp.DecodeBytes(data, body); err != nil { 490 log.Error("Invalid block body RLP", "hash", hash, "err", err) 491 return nil 492 } 493 return body 494 } 495 496 // WriteBody stores a block body into the database. 497 func WriteBody(db ethdb.KeyValueWriter, hash common.Hash, number uint64, body *types.Body) { 498 data, err := rlp.EncodeToBytes(body) 499 if err != nil { 500 log.Crit("Failed to RLP encode body", "err", err) 501 } 502 WriteBodyRLP(db, hash, number, data) 503 } 504 505 // DeleteBody removes all block body data associated with a hash. 506 func DeleteBody(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 507 if err := db.Delete(blockBodyKey(number, hash)); err != nil { 508 log.Crit("Failed to delete block body", "err", err) 509 } 510 } 511 512 // ReadTdRLP retrieves a block's total difficulty corresponding to the hash in RLP encoding. 513 func ReadTdRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue { 514 var data []byte 515 db.ReadAncients(func(reader ethdb.AncientReaderOp) error { 516 // Check if the data is in ancients 517 if isCanon(reader, number, hash) { 518 data, _ = reader.Ancient(ChainFreezerDifficultyTable, number) 519 return nil 520 } 521 // If not, try reading from leveldb 522 data, _ = db.Get(headerTDKey(number, hash)) 523 return nil 524 }) 525 return data 526 } 527 528 // ReadTd retrieves a block's total difficulty corresponding to the hash. 529 func ReadTd(db ethdb.Reader, hash common.Hash, number uint64) *big.Int { 530 data := ReadTdRLP(db, hash, number) 531 if len(data) == 0 { 532 return nil 533 } 534 td := new(big.Int) 535 if err := rlp.DecodeBytes(data, td); err != nil { 536 log.Error("Invalid block total difficulty RLP", "hash", hash, "err", err) 537 return nil 538 } 539 return td 540 } 541 542 // WriteTd stores the total difficulty of a block into the database. 543 func WriteTd(db ethdb.KeyValueWriter, hash common.Hash, number uint64, td *big.Int) { 544 data, err := rlp.EncodeToBytes(td) 545 if err != nil { 546 log.Crit("Failed to RLP encode block total difficulty", "err", err) 547 } 548 if err := db.Put(headerTDKey(number, hash), data); err != nil { 549 log.Crit("Failed to store block total difficulty", "err", err) 550 } 551 } 552 553 // DeleteTd removes all block total difficulty data associated with a hash. 554 func DeleteTd(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 555 if err := db.Delete(headerTDKey(number, hash)); err != nil { 556 log.Crit("Failed to delete block total difficulty", "err", err) 557 } 558 } 559 560 // HasReceipts verifies the existence of all the transaction receipts belonging 561 // to a block. 562 func HasReceipts(db ethdb.Reader, hash common.Hash, number uint64) bool { 563 if isCanon(db, number, hash) { 564 return true 565 } 566 if has, err := db.Has(blockReceiptsKey(number, hash)); !has || err != nil { 567 return false 568 } 569 return true 570 } 571 572 // ReadReceiptsRLP retrieves all the transaction receipts belonging to a block in RLP encoding. 573 func ReadReceiptsRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue { 574 var data []byte 575 db.ReadAncients(func(reader ethdb.AncientReaderOp) error { 576 // Check if the data is in ancients 577 if isCanon(reader, number, hash) { 578 data, _ = reader.Ancient(ChainFreezerReceiptTable, number) 579 return nil 580 } 581 // If not, try reading from leveldb 582 data, _ = db.Get(blockReceiptsKey(number, hash)) 583 return nil 584 }) 585 return data 586 } 587 588 // ReadRawReceipts retrieves all the transaction receipts belonging to a block. 589 // The receipt metadata fields are not guaranteed to be populated, so they 590 // should not be used. Use ReadReceipts instead if the metadata is needed. 591 func ReadRawReceipts(db ethdb.Reader, hash common.Hash, number uint64) types.Receipts { 592 // Retrieve the flattened receipt slice 593 data := ReadReceiptsRLP(db, hash, number) 594 if len(data) == 0 { 595 return nil 596 } 597 // Convert the receipts from their storage form to their internal representation 598 storageReceipts := []*types.ReceiptForStorage{} 599 if err := rlp.DecodeBytes(data, &storageReceipts); err != nil { 600 log.Error("Invalid receipt array RLP", "hash", hash, "err", err) 601 return nil 602 } 603 receipts := make(types.Receipts, len(storageReceipts)) 604 for i, storageReceipt := range storageReceipts { 605 receipts[i] = (*types.Receipt)(storageReceipt) 606 } 607 return receipts 608 } 609 610 // ReadReceipts retrieves all the transaction receipts belonging to a block, including 611 // its corresponding metadata fields. If it is unable to populate these metadata 612 // fields then nil is returned. 613 // 614 // The current implementation populates these metadata fields by reading the receipts' 615 // corresponding block body, so if the block body is not found it will return nil even 616 // if the receipt itself is stored. 617 func ReadReceipts(db ethdb.Reader, hash common.Hash, number uint64, time uint64, config *params.ChainConfig) types.Receipts { 618 // We're deriving many fields from the block body, retrieve beside the receipt 619 receipts := ReadRawReceipts(db, hash, number) 620 if receipts == nil { 621 return nil 622 } 623 body := ReadBody(db, hash, number) 624 if body == nil { 625 log.Error("Missing body but have receipt", "hash", hash, "number", number) 626 return nil 627 } 628 header := ReadHeader(db, hash, number) 629 630 var baseFee *big.Int 631 if header == nil { 632 baseFee = big.NewInt(0) 633 } else { 634 baseFee = header.BaseFee 635 } 636 // Compute effective blob gas price. 637 var blobGasPrice *big.Int 638 if header != nil && header.ExcessBlobGas != nil { 639 blobGasPrice = eip4844.CalcBlobFee(*header.ExcessBlobGas) 640 } 641 if err := receipts.DeriveFields(config, hash, number, time, baseFee, blobGasPrice, body.Transactions); err != nil { 642 log.Error("Failed to derive block receipts fields", "hash", hash, "number", number, "err", err) 643 return nil 644 } 645 return receipts 646 } 647 648 // WriteReceipts stores all the transaction receipts belonging to a block. 649 func WriteReceipts(db ethdb.KeyValueWriter, hash common.Hash, number uint64, receipts types.Receipts) { 650 // Convert the receipts into their storage form and serialize them 651 storageReceipts := make([]*types.ReceiptForStorage, len(receipts)) 652 for i, receipt := range receipts { 653 storageReceipts[i] = (*types.ReceiptForStorage)(receipt) 654 } 655 bytes, err := rlp.EncodeToBytes(storageReceipts) 656 if err != nil { 657 log.Crit("Failed to encode block receipts", "err", err) 658 } 659 // Store the flattened receipt slice 660 if err := db.Put(blockReceiptsKey(number, hash), bytes); err != nil { 661 log.Crit("Failed to store block receipts", "err", err) 662 } 663 } 664 665 // DeleteReceipts removes all receipt data associated with a block hash. 666 func DeleteReceipts(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 667 if err := db.Delete(blockReceiptsKey(number, hash)); err != nil { 668 log.Crit("Failed to delete block receipts", "err", err) 669 } 670 } 671 672 // storedReceiptRLP is the storage encoding of a receipt. 673 // Re-definition in core/types/receipt.go. 674 // TODO: Re-use the existing definition. 675 type storedReceiptRLP struct { 676 PostStateOrStatus []byte 677 CumulativeGasUsed uint64 678 Logs []*types.Log 679 } 680 681 // ReceiptLogs is a barebone version of ReceiptForStorage which only keeps 682 // the list of logs. When decoding a stored receipt into this object we 683 // avoid creating the bloom filter. 684 type receiptLogs struct { 685 Logs []*types.Log 686 } 687 688 // DecodeRLP implements rlp.Decoder. 689 func (r *receiptLogs) DecodeRLP(s *rlp.Stream) error { 690 var stored storedReceiptRLP 691 if err := s.Decode(&stored); err != nil { 692 return err 693 } 694 r.Logs = stored.Logs 695 return nil 696 } 697 698 // deriveLogFields fills the logs in receiptLogs with information such as block number, txhash, etc. 699 func deriveLogFields(receipts []*receiptLogs, hash common.Hash, number uint64, txs types.Transactions) error { 700 logIndex := uint(0) 701 if len(txs) != len(receipts) { 702 return errors.New("transaction and receipt count mismatch") 703 } 704 for i := 0; i < len(receipts); i++ { 705 txHash := txs[i].Hash() 706 // The derived log fields can simply be set from the block and transaction 707 for j := 0; j < len(receipts[i].Logs); j++ { 708 receipts[i].Logs[j].BlockNumber = number 709 receipts[i].Logs[j].BlockHash = hash 710 receipts[i].Logs[j].TxHash = txHash 711 receipts[i].Logs[j].TxIndex = uint(i) 712 receipts[i].Logs[j].Index = logIndex 713 logIndex++ 714 } 715 } 716 return nil 717 } 718 719 // ReadLogs retrieves the logs for all transactions in a block. In case 720 // receipts is not found, a nil is returned. 721 // Note: ReadLogs does not derive unstored log fields. 722 func ReadLogs(db ethdb.Reader, hash common.Hash, number uint64) [][]*types.Log { 723 // Retrieve the flattened receipt slice 724 data := ReadReceiptsRLP(db, hash, number) 725 if len(data) == 0 { 726 return nil 727 } 728 receipts := []*receiptLogs{} 729 if err := rlp.DecodeBytes(data, &receipts); err != nil { 730 log.Error("Invalid receipt array RLP", "hash", hash, "err", err) 731 return nil 732 } 733 734 logs := make([][]*types.Log, len(receipts)) 735 for i, receipt := range receipts { 736 logs[i] = receipt.Logs 737 } 738 return logs 739 } 740 741 // ReadBlock retrieves an entire block corresponding to the hash, assembling it 742 // back from the stored header and body. If either the header or body could not 743 // be retrieved nil is returned. 744 // 745 // Note, due to concurrent download of header and block body the header and thus 746 // canonical hash can be stored in the database but the body data not (yet). 747 func ReadBlock(db ethdb.Reader, hash common.Hash, number uint64) *types.Block { 748 header := ReadHeader(db, hash, number) 749 if header == nil { 750 return nil 751 } 752 body := ReadBody(db, hash, number) 753 if body == nil { 754 return nil 755 } 756 return types.NewBlockWithHeader(header).WithBody(*body) 757 } 758 759 // WriteBlock serializes a block into the database, header and body separately. 760 func WriteBlock(db ethdb.KeyValueWriter, block *types.Block) { 761 WriteBody(db, block.Hash(), block.NumberU64(), block.Body()) 762 WriteHeader(db, block.Header()) 763 } 764 765 // WriteAncientBlocks writes entire block data into ancient store and returns the total written size. 766 func WriteAncientBlocks(db ethdb.AncientWriter, blocks []*types.Block, receipts []types.Receipts, td *big.Int) (int64, error) { 767 var ( 768 tdSum = new(big.Int).Set(td) 769 stReceipts []*types.ReceiptForStorage 770 ) 771 return db.ModifyAncients(func(op ethdb.AncientWriteOp) error { 772 for i, block := range blocks { 773 // Convert receipts to storage format and sum up total difficulty. 774 stReceipts = stReceipts[:0] 775 for _, receipt := range receipts[i] { 776 stReceipts = append(stReceipts, (*types.ReceiptForStorage)(receipt)) 777 } 778 header := block.Header() 779 if i > 0 { 780 tdSum.Add(tdSum, header.Difficulty) 781 } 782 if err := writeAncientBlock(op, block, header, stReceipts, tdSum); err != nil { 783 return err 784 } 785 } 786 return nil 787 }) 788 } 789 790 func writeAncientBlock(op ethdb.AncientWriteOp, block *types.Block, header *types.Header, receipts []*types.ReceiptForStorage, td *big.Int) error { 791 num := block.NumberU64() 792 if err := op.AppendRaw(ChainFreezerHashTable, num, block.Hash().Bytes()); err != nil { 793 return fmt.Errorf("can't add block %d hash: %v", num, err) 794 } 795 if err := op.Append(ChainFreezerHeaderTable, num, header); err != nil { 796 return fmt.Errorf("can't append block header %d: %v", num, err) 797 } 798 if err := op.Append(ChainFreezerBodiesTable, num, block.Body()); err != nil { 799 return fmt.Errorf("can't append block body %d: %v", num, err) 800 } 801 if err := op.Append(ChainFreezerReceiptTable, num, receipts); err != nil { 802 return fmt.Errorf("can't append block %d receipts: %v", num, err) 803 } 804 if err := op.Append(ChainFreezerDifficultyTable, num, td); err != nil { 805 return fmt.Errorf("can't append block %d total difficulty: %v", num, err) 806 } 807 return nil 808 } 809 810 // DeleteBlock removes all block data associated with a hash. 811 func DeleteBlock(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 812 DeleteReceipts(db, hash, number) 813 DeleteHeader(db, hash, number) 814 DeleteBody(db, hash, number) 815 DeleteTd(db, hash, number) 816 } 817 818 // DeleteBlockWithoutNumber removes all block data associated with a hash, except 819 // the hash to number mapping. 820 func DeleteBlockWithoutNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 821 DeleteReceipts(db, hash, number) 822 deleteHeaderWithoutNumber(db, hash, number) 823 DeleteBody(db, hash, number) 824 DeleteTd(db, hash, number) 825 } 826 827 const badBlockToKeep = 10 828 829 type badBlock struct { 830 Header *types.Header 831 Body *types.Body 832 } 833 834 // ReadBadBlock retrieves the bad block with the corresponding block hash. 835 func ReadBadBlock(db ethdb.Reader, hash common.Hash) *types.Block { 836 blob, err := db.Get(badBlockKey) 837 if err != nil { 838 return nil 839 } 840 var badBlocks []*badBlock 841 if err := rlp.DecodeBytes(blob, &badBlocks); err != nil { 842 return nil 843 } 844 for _, bad := range badBlocks { 845 if bad.Header.Hash() == hash { 846 block := types.NewBlockWithHeader(bad.Header) 847 if bad.Body != nil { 848 block = block.WithBody(*bad.Body) 849 } 850 return block 851 } 852 } 853 return nil 854 } 855 856 // ReadAllBadBlocks retrieves all the bad blocks in the database. 857 // All returned blocks are sorted in reverse order by number. 858 func ReadAllBadBlocks(db ethdb.Reader) []*types.Block { 859 blob, err := db.Get(badBlockKey) 860 if err != nil { 861 return nil 862 } 863 var badBlocks []*badBlock 864 if err := rlp.DecodeBytes(blob, &badBlocks); err != nil { 865 return nil 866 } 867 var blocks []*types.Block 868 for _, bad := range badBlocks { 869 block := types.NewBlockWithHeader(bad.Header) 870 if bad.Body != nil { 871 block = block.WithBody(*bad.Body) 872 } 873 blocks = append(blocks, block) 874 } 875 return blocks 876 } 877 878 // WriteBadBlock serializes the bad block into the database. If the cumulated 879 // bad blocks exceeds the limitation, the oldest will be dropped. 880 func WriteBadBlock(db ethdb.KeyValueStore, block *types.Block) { 881 blob, err := db.Get(badBlockKey) 882 if err != nil { 883 log.Warn("Failed to load old bad blocks", "error", err) 884 } 885 var badBlocks []*badBlock 886 if len(blob) > 0 { 887 if err := rlp.DecodeBytes(blob, &badBlocks); err != nil { 888 log.Crit("Failed to decode old bad blocks", "error", err) 889 } 890 } 891 for _, b := range badBlocks { 892 if b.Header.Number.Uint64() == block.NumberU64() && b.Header.Hash() == block.Hash() { 893 log.Info("Skip duplicated bad block", "number", block.NumberU64(), "hash", block.Hash()) 894 return 895 } 896 } 897 badBlocks = append(badBlocks, &badBlock{ 898 Header: block.Header(), 899 Body: block.Body(), 900 }) 901 slices.SortFunc(badBlocks, func(a, b *badBlock) int { 902 // Note: sorting in descending number order. 903 return -a.Header.Number.Cmp(b.Header.Number) 904 }) 905 if len(badBlocks) > badBlockToKeep { 906 badBlocks = badBlocks[:badBlockToKeep] 907 } 908 data, err := rlp.EncodeToBytes(badBlocks) 909 if err != nil { 910 log.Crit("Failed to encode bad blocks", "err", err) 911 } 912 if err := db.Put(badBlockKey, data); err != nil { 913 log.Crit("Failed to write bad blocks", "err", err) 914 } 915 } 916 917 // DeleteBadBlocks deletes all the bad blocks from the database 918 func DeleteBadBlocks(db ethdb.KeyValueWriter) { 919 if err := db.Delete(badBlockKey); err != nil { 920 log.Crit("Failed to delete bad blocks", "err", err) 921 } 922 } 923 924 // FindCommonAncestor returns the last common ancestor of two block headers 925 func FindCommonAncestor(db ethdb.Reader, a, b *types.Header) *types.Header { 926 for bn := b.Number.Uint64(); a.Number.Uint64() > bn; { 927 a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1) 928 if a == nil { 929 return nil 930 } 931 } 932 for an := a.Number.Uint64(); an < b.Number.Uint64(); { 933 b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1) 934 if b == nil { 935 return nil 936 } 937 } 938 for a.Hash() != b.Hash() { 939 a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1) 940 if a == nil { 941 return nil 942 } 943 b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1) 944 if b == nil { 945 return nil 946 } 947 } 948 return a 949 } 950 951 // ReadHeadHeader returns the current canonical head header. 952 func ReadHeadHeader(db ethdb.Reader) *types.Header { 953 headHeaderHash := ReadHeadHeaderHash(db) 954 if headHeaderHash == (common.Hash{}) { 955 return nil 956 } 957 headHeaderNumber := ReadHeaderNumber(db, headHeaderHash) 958 if headHeaderNumber == nil { 959 return nil 960 } 961 return ReadHeader(db, headHeaderHash, *headHeaderNumber) 962 } 963 964 // ReadHeadBlock returns the current canonical head block. 965 func ReadHeadBlock(db ethdb.Reader) *types.Block { 966 headBlockHash := ReadHeadBlockHash(db) 967 if headBlockHash == (common.Hash{}) { 968 return nil 969 } 970 headBlockNumber := ReadHeaderNumber(db, headBlockHash) 971 if headBlockNumber == nil { 972 return nil 973 } 974 return ReadBlock(db, headBlockHash, *headBlockNumber) 975 }