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