github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/core/rawdb/accessors_chain.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 package rawdb 19 20 import ( 21 "bytes" 22 "encoding/binary" 23 "math/big" 24 25 "github.com/AigarNetwork/aigar/common" 26 "github.com/AigarNetwork/aigar/core/types" 27 "github.com/AigarNetwork/aigar/ethdb" 28 "github.com/AigarNetwork/aigar/log" 29 "github.com/AigarNetwork/aigar/params" 30 "github.com/AigarNetwork/aigar/rlp" 31 ) 32 33 // ReadCanonicalHash retrieves the hash assigned to a canonical block number. 34 func ReadCanonicalHash(db ethdb.Reader, number uint64) common.Hash { 35 data, _ := db.Ancient(freezerHashTable, number) 36 if len(data) == 0 { 37 data, _ = db.Get(headerHashKey(number)) 38 // In the background freezer is moving data from leveldb to flatten files. 39 // So during the first check for ancient db, the data is not yet in there, 40 // but when we reach into leveldb, the data was already moved. That would 41 // result in a not found error. 42 if len(data) == 0 { 43 data, _ = db.Ancient(freezerHashTable, number) 44 } 45 } 46 if len(data) == 0 { 47 return common.Hash{} 48 } 49 return common.BytesToHash(data) 50 } 51 52 // WriteCanonicalHash stores the hash assigned to a canonical block number. 53 func WriteCanonicalHash(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 54 if err := db.Put(headerHashKey(number), hash.Bytes()); err != nil { 55 log.Crit("Failed to store number to hash mapping", "err", err) 56 } 57 } 58 59 // DeleteCanonicalHash removes the number to hash canonical mapping. 60 func DeleteCanonicalHash(db ethdb.KeyValueWriter, number uint64) { 61 if err := db.Delete(headerHashKey(number)); err != nil { 62 log.Crit("Failed to delete number to hash mapping", "err", err) 63 } 64 } 65 66 // ReadAllHashes retrieves all the hashes assigned to blocks at a certain heights, 67 // both canonical and reorged forks included. 68 func ReadAllHashes(db ethdb.Iteratee, number uint64) []common.Hash { 69 prefix := headerKeyPrefix(number) 70 71 hashes := make([]common.Hash, 0, 1) 72 it := db.NewIteratorWithPrefix(prefix) 73 defer it.Release() 74 75 for it.Next() { 76 if key := it.Key(); len(key) == len(prefix)+32 { 77 hashes = append(hashes, common.BytesToHash(key[len(key)-32:])) 78 } 79 } 80 return hashes 81 } 82 83 // ReadHeaderNumber returns the header number assigned to a hash. 84 func ReadHeaderNumber(db ethdb.KeyValueReader, hash common.Hash) *uint64 { 85 data, _ := db.Get(headerNumberKey(hash)) 86 if len(data) != 8 { 87 return nil 88 } 89 number := binary.BigEndian.Uint64(data) 90 return &number 91 } 92 93 // WriteHeaderNumber stores the hash->number mapping. 94 func WriteHeaderNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 95 key := headerNumberKey(hash) 96 enc := encodeBlockNumber(number) 97 if err := db.Put(key, enc); err != nil { 98 log.Crit("Failed to store hash to number mapping", "err", err) 99 } 100 } 101 102 // DeleteHeaderNumber removes hash->number mapping. 103 func DeleteHeaderNumber(db ethdb.KeyValueWriter, hash common.Hash) { 104 if err := db.Delete(headerNumberKey(hash)); err != nil { 105 log.Crit("Failed to delete hash to number mapping", "err", err) 106 } 107 } 108 109 // ReadHeadHeaderHash retrieves the hash of the current canonical head header. 110 func ReadHeadHeaderHash(db ethdb.KeyValueReader) common.Hash { 111 data, _ := db.Get(headHeaderKey) 112 if len(data) == 0 { 113 return common.Hash{} 114 } 115 return common.BytesToHash(data) 116 } 117 118 // WriteHeadHeaderHash stores the hash of the current canonical head header. 119 func WriteHeadHeaderHash(db ethdb.KeyValueWriter, hash common.Hash) { 120 if err := db.Put(headHeaderKey, hash.Bytes()); err != nil { 121 log.Crit("Failed to store last header's hash", "err", err) 122 } 123 } 124 125 // ReadHeadBlockHash retrieves the hash of the current canonical head block. 126 func ReadHeadBlockHash(db ethdb.KeyValueReader) common.Hash { 127 data, _ := db.Get(headBlockKey) 128 if len(data) == 0 { 129 return common.Hash{} 130 } 131 return common.BytesToHash(data) 132 } 133 134 // WriteHeadBlockHash stores the head block's hash. 135 func WriteHeadBlockHash(db ethdb.KeyValueWriter, hash common.Hash) { 136 if err := db.Put(headBlockKey, hash.Bytes()); err != nil { 137 log.Crit("Failed to store last block's hash", "err", err) 138 } 139 } 140 141 // ReadHeadFastBlockHash retrieves the hash of the current fast-sync head block. 142 func ReadHeadFastBlockHash(db ethdb.KeyValueReader) common.Hash { 143 data, _ := db.Get(headFastBlockKey) 144 if len(data) == 0 { 145 return common.Hash{} 146 } 147 return common.BytesToHash(data) 148 } 149 150 // WriteHeadFastBlockHash stores the hash of the current fast-sync head block. 151 func WriteHeadFastBlockHash(db ethdb.KeyValueWriter, hash common.Hash) { 152 if err := db.Put(headFastBlockKey, hash.Bytes()); err != nil { 153 log.Crit("Failed to store last fast block's hash", "err", err) 154 } 155 } 156 157 // ReadFastTrieProgress retrieves the number of tries nodes fast synced to allow 158 // reporting correct numbers across restarts. 159 func ReadFastTrieProgress(db ethdb.KeyValueReader) uint64 { 160 data, _ := db.Get(fastTrieProgressKey) 161 if len(data) == 0 { 162 return 0 163 } 164 return new(big.Int).SetBytes(data).Uint64() 165 } 166 167 // WriteFastTrieProgress stores the fast sync trie process counter to support 168 // retrieving it across restarts. 169 func WriteFastTrieProgress(db ethdb.KeyValueWriter, count uint64) { 170 if err := db.Put(fastTrieProgressKey, new(big.Int).SetUint64(count).Bytes()); err != nil { 171 log.Crit("Failed to store fast sync trie progress", "err", err) 172 } 173 } 174 175 // ReadHeaderRLP retrieves a block header in its raw RLP database encoding. 176 func ReadHeaderRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue { 177 data, _ := db.Ancient(freezerHeaderTable, number) 178 if len(data) == 0 { 179 data, _ = db.Get(headerKey(number, hash)) 180 // In the background freezer is moving data from leveldb to flatten files. 181 // So during the first check for ancient db, the data is not yet in there, 182 // but when we reach into leveldb, the data was already moved. That would 183 // result in a not found error. 184 if len(data) == 0 { 185 data, _ = db.Ancient(freezerHeaderTable, number) 186 } 187 } 188 return data 189 } 190 191 // HasHeader verifies the existence of a block header corresponding to the hash. 192 func HasHeader(db ethdb.Reader, hash common.Hash, number uint64) bool { 193 if has, err := db.Ancient(freezerHashTable, number); err == nil && common.BytesToHash(has) == hash { 194 return true 195 } 196 if has, err := db.Has(headerKey(number, hash)); !has || err != nil { 197 return false 198 } 199 return true 200 } 201 202 // ReadHeader retrieves the block header corresponding to the hash. 203 func ReadHeader(db ethdb.Reader, hash common.Hash, number uint64) *types.Header { 204 data := ReadHeaderRLP(db, hash, number) 205 if len(data) == 0 { 206 return nil 207 } 208 header := new(types.Header) 209 if err := rlp.Decode(bytes.NewReader(data), header); err != nil { 210 log.Error("Invalid block header RLP", "hash", hash, "err", err) 211 return nil 212 } 213 return header 214 } 215 216 // WriteHeader stores a block header into the database and also stores the hash- 217 // to-number mapping. 218 func WriteHeader(db ethdb.KeyValueWriter, header *types.Header) { 219 var ( 220 hash = header.Hash() 221 number = header.Number.Uint64() 222 ) 223 // Write the hash -> number mapping 224 WriteHeaderNumber(db, hash, number) 225 226 // Write the encoded header 227 data, err := rlp.EncodeToBytes(header) 228 if err != nil { 229 log.Crit("Failed to RLP encode header", "err", err) 230 } 231 key := headerKey(number, hash) 232 if err := db.Put(key, data); err != nil { 233 log.Crit("Failed to store header", "err", err) 234 } 235 } 236 237 // DeleteHeader removes all block header data associated with a hash. 238 func DeleteHeader(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 239 deleteHeaderWithoutNumber(db, hash, number) 240 if err := db.Delete(headerNumberKey(hash)); err != nil { 241 log.Crit("Failed to delete hash to number mapping", "err", err) 242 } 243 } 244 245 // deleteHeaderWithoutNumber removes only the block header but does not remove 246 // the hash to number mapping. 247 func deleteHeaderWithoutNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 248 if err := db.Delete(headerKey(number, hash)); err != nil { 249 log.Crit("Failed to delete header", "err", err) 250 } 251 } 252 253 // ReadBodyRLP retrieves the block body (transactions and uncles) in RLP encoding. 254 func ReadBodyRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue { 255 data, _ := db.Ancient(freezerBodiesTable, number) 256 if len(data) == 0 { 257 data, _ = db.Get(blockBodyKey(number, hash)) 258 // In the background freezer is moving data from leveldb to flatten files. 259 // So during the first check for ancient db, the data is not yet in there, 260 // but when we reach into leveldb, the data was already moved. That would 261 // result in a not found error. 262 if len(data) == 0 { 263 data, _ = db.Ancient(freezerBodiesTable, number) 264 } 265 } 266 return data 267 } 268 269 // WriteBodyRLP stores an RLP encoded block body into the database. 270 func WriteBodyRLP(db ethdb.KeyValueWriter, hash common.Hash, number uint64, rlp rlp.RawValue) { 271 if err := db.Put(blockBodyKey(number, hash), rlp); err != nil { 272 log.Crit("Failed to store block body", "err", err) 273 } 274 } 275 276 // HasBody verifies the existence of a block body corresponding to the hash. 277 func HasBody(db ethdb.Reader, hash common.Hash, number uint64) bool { 278 if has, err := db.Ancient(freezerHashTable, number); err == nil && common.BytesToHash(has) == hash { 279 return true 280 } 281 if has, err := db.Has(blockBodyKey(number, hash)); !has || err != nil { 282 return false 283 } 284 return true 285 } 286 287 // ReadBody retrieves the block body corresponding to the hash. 288 func ReadBody(db ethdb.Reader, hash common.Hash, number uint64) *types.Body { 289 data := ReadBodyRLP(db, hash, number) 290 if len(data) == 0 { 291 return nil 292 } 293 body := new(types.Body) 294 if err := rlp.Decode(bytes.NewReader(data), body); err != nil { 295 log.Error("Invalid block body RLP", "hash", hash, "err", err) 296 return nil 297 } 298 return body 299 } 300 301 // WriteBody stores a block body into the database. 302 func WriteBody(db ethdb.KeyValueWriter, hash common.Hash, number uint64, body *types.Body) { 303 data, err := rlp.EncodeToBytes(body) 304 if err != nil { 305 log.Crit("Failed to RLP encode body", "err", err) 306 } 307 WriteBodyRLP(db, hash, number, data) 308 } 309 310 // DeleteBody removes all block body data associated with a hash. 311 func DeleteBody(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 312 if err := db.Delete(blockBodyKey(number, hash)); err != nil { 313 log.Crit("Failed to delete block body", "err", err) 314 } 315 } 316 317 // ReadTdRLP retrieves a block's total difficulty corresponding to the hash in RLP encoding. 318 func ReadTdRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue { 319 data, _ := db.Ancient(freezerDifficultyTable, number) 320 if len(data) == 0 { 321 data, _ = db.Get(headerTDKey(number, hash)) 322 // In the background freezer is moving data from leveldb to flatten files. 323 // So during the first check for ancient db, the data is not yet in there, 324 // but when we reach into leveldb, the data was already moved. That would 325 // result in a not found error. 326 if len(data) == 0 { 327 data, _ = db.Ancient(freezerDifficultyTable, number) 328 } 329 } 330 return data 331 } 332 333 // ReadTd retrieves a block's total difficulty corresponding to the hash. 334 func ReadTd(db ethdb.Reader, hash common.Hash, number uint64) *big.Int { 335 data := ReadTdRLP(db, hash, number) 336 if len(data) == 0 { 337 return nil 338 } 339 td := new(big.Int) 340 if err := rlp.Decode(bytes.NewReader(data), td); err != nil { 341 log.Error("Invalid block total difficulty RLP", "hash", hash, "err", err) 342 return nil 343 } 344 return td 345 } 346 347 // WriteTd stores the total difficulty of a block into the database. 348 func WriteTd(db ethdb.KeyValueWriter, hash common.Hash, number uint64, td *big.Int) { 349 data, err := rlp.EncodeToBytes(td) 350 if err != nil { 351 log.Crit("Failed to RLP encode block total difficulty", "err", err) 352 } 353 if err := db.Put(headerTDKey(number, hash), data); err != nil { 354 log.Crit("Failed to store block total difficulty", "err", err) 355 } 356 } 357 358 // DeleteTd removes all block total difficulty data associated with a hash. 359 func DeleteTd(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 360 if err := db.Delete(headerTDKey(number, hash)); err != nil { 361 log.Crit("Failed to delete block total difficulty", "err", err) 362 } 363 } 364 365 // HasReceipts verifies the existence of all the transaction receipts belonging 366 // to a block. 367 func HasReceipts(db ethdb.Reader, hash common.Hash, number uint64) bool { 368 if has, err := db.Ancient(freezerHashTable, number); err == nil && common.BytesToHash(has) == hash { 369 return true 370 } 371 if has, err := db.Has(blockReceiptsKey(number, hash)); !has || err != nil { 372 return false 373 } 374 return true 375 } 376 377 // ReadReceiptsRLP retrieves all the transaction receipts belonging to a block in RLP encoding. 378 func ReadReceiptsRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue { 379 data, _ := db.Ancient(freezerReceiptTable, number) 380 if len(data) == 0 { 381 data, _ = db.Get(blockReceiptsKey(number, hash)) 382 // In the background freezer is moving data from leveldb to flatten files. 383 // So during the first check for ancient db, the data is not yet in there, 384 // but when we reach into leveldb, the data was already moved. That would 385 // result in a not found error. 386 if len(data) == 0 { 387 data, _ = db.Ancient(freezerReceiptTable, number) 388 } 389 } 390 return data 391 } 392 393 // ReadRawReceipts retrieves all the transaction receipts belonging to a block. 394 // The receipt metadata fields are not guaranteed to be populated, so they 395 // should not be used. Use ReadReceipts instead if the metadata is needed. 396 func ReadRawReceipts(db ethdb.Reader, hash common.Hash, number uint64) types.Receipts { 397 // Retrieve the flattened receipt slice 398 data := ReadReceiptsRLP(db, hash, number) 399 if len(data) == 0 { 400 return nil 401 } 402 // Convert the receipts from their storage form to their internal representation 403 storageReceipts := []*types.ReceiptForStorage{} 404 if err := rlp.DecodeBytes(data, &storageReceipts); err != nil { 405 log.Error("Invalid receipt array RLP", "hash", hash, "err", err) 406 return nil 407 } 408 receipts := make(types.Receipts, len(storageReceipts)) 409 for i, storageReceipt := range storageReceipts { 410 receipts[i] = (*types.Receipt)(storageReceipt) 411 } 412 return receipts 413 } 414 415 // ReadReceipts retrieves all the transaction receipts belonging to a block, including 416 // its correspoinding metadata fields. If it is unable to populate these metadata 417 // fields then nil is returned. 418 // 419 // The current implementation populates these metadata fields by reading the receipts' 420 // corresponding block body, so if the block body is not found it will return nil even 421 // if the receipt itself is stored. 422 func ReadReceipts(db ethdb.Reader, hash common.Hash, number uint64, config *params.ChainConfig) types.Receipts { 423 // We're deriving many fields from the block body, retrieve beside the receipt 424 receipts := ReadRawReceipts(db, hash, number) 425 if receipts == nil { 426 return nil 427 } 428 body := ReadBody(db, hash, number) 429 if body == nil { 430 log.Error("Missing body but have receipt", "hash", hash, "number", number) 431 return nil 432 } 433 if err := receipts.DeriveFields(config, hash, number, body.Transactions); err != nil { 434 log.Error("Failed to derive block receipts fields", "hash", hash, "number", number, "err", err) 435 return nil 436 } 437 return receipts 438 } 439 440 // WriteReceipts stores all the transaction receipts belonging to a block. 441 func WriteReceipts(db ethdb.KeyValueWriter, hash common.Hash, number uint64, receipts types.Receipts) { 442 // Convert the receipts into their storage form and serialize them 443 storageReceipts := make([]*types.ReceiptForStorage, len(receipts)) 444 for i, receipt := range receipts { 445 storageReceipts[i] = (*types.ReceiptForStorage)(receipt) 446 } 447 bytes, err := rlp.EncodeToBytes(storageReceipts) 448 if err != nil { 449 log.Crit("Failed to encode block receipts", "err", err) 450 } 451 // Store the flattened receipt slice 452 if err := db.Put(blockReceiptsKey(number, hash), bytes); err != nil { 453 log.Crit("Failed to store block receipts", "err", err) 454 } 455 } 456 457 // DeleteReceipts removes all receipt data associated with a block hash. 458 func DeleteReceipts(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 459 if err := db.Delete(blockReceiptsKey(number, hash)); err != nil { 460 log.Crit("Failed to delete block receipts", "err", err) 461 } 462 } 463 464 // ReadBlock retrieves an entire block corresponding to the hash, assembling it 465 // back from the stored header and body. If either the header or body could not 466 // be retrieved nil is returned. 467 // 468 // Note, due to concurrent download of header and block body the header and thus 469 // canonical hash can be stored in the database but the body data not (yet). 470 func ReadBlock(db ethdb.Reader, hash common.Hash, number uint64) *types.Block { 471 header := ReadHeader(db, hash, number) 472 if header == nil { 473 return nil 474 } 475 body := ReadBody(db, hash, number) 476 if body == nil { 477 return nil 478 } 479 return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles) 480 } 481 482 // WriteBlock serializes a block into the database, header and body separately. 483 func WriteBlock(db ethdb.KeyValueWriter, block *types.Block) { 484 WriteBody(db, block.Hash(), block.NumberU64(), block.Body()) 485 WriteHeader(db, block.Header()) 486 } 487 488 // WriteAncientBlock writes entire block data into ancient store and returns the total written size. 489 func WriteAncientBlock(db ethdb.AncientWriter, block *types.Block, receipts types.Receipts, td *big.Int) int { 490 // Encode all block components to RLP format. 491 headerBlob, err := rlp.EncodeToBytes(block.Header()) 492 if err != nil { 493 log.Crit("Failed to RLP encode block header", "err", err) 494 } 495 bodyBlob, err := rlp.EncodeToBytes(block.Body()) 496 if err != nil { 497 log.Crit("Failed to RLP encode body", "err", err) 498 } 499 storageReceipts := make([]*types.ReceiptForStorage, len(receipts)) 500 for i, receipt := range receipts { 501 storageReceipts[i] = (*types.ReceiptForStorage)(receipt) 502 } 503 receiptBlob, err := rlp.EncodeToBytes(storageReceipts) 504 if err != nil { 505 log.Crit("Failed to RLP encode block receipts", "err", err) 506 } 507 tdBlob, err := rlp.EncodeToBytes(td) 508 if err != nil { 509 log.Crit("Failed to RLP encode block total difficulty", "err", err) 510 } 511 // Write all blob to flatten files. 512 err = db.AppendAncient(block.NumberU64(), block.Hash().Bytes(), headerBlob, bodyBlob, receiptBlob, tdBlob) 513 if err != nil { 514 log.Crit("Failed to write block data to ancient store", "err", err) 515 } 516 return len(headerBlob) + len(bodyBlob) + len(receiptBlob) + len(tdBlob) + common.HashLength 517 } 518 519 // DeleteBlock removes all block data associated with a hash. 520 func DeleteBlock(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 521 DeleteReceipts(db, hash, number) 522 DeleteHeader(db, hash, number) 523 DeleteBody(db, hash, number) 524 DeleteTd(db, hash, number) 525 } 526 527 // DeleteBlockWithoutNumber removes all block data associated with a hash, except 528 // the hash to number mapping. 529 func DeleteBlockWithoutNumber(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { 530 DeleteReceipts(db, hash, number) 531 deleteHeaderWithoutNumber(db, hash, number) 532 DeleteBody(db, hash, number) 533 DeleteTd(db, hash, number) 534 } 535 536 // FindCommonAncestor returns the last common ancestor of two block headers 537 func FindCommonAncestor(db ethdb.Reader, a, b *types.Header) *types.Header { 538 for bn := b.Number.Uint64(); a.Number.Uint64() > bn; { 539 a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1) 540 if a == nil { 541 return nil 542 } 543 } 544 for an := a.Number.Uint64(); an < b.Number.Uint64(); { 545 b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1) 546 if b == nil { 547 return nil 548 } 549 } 550 for a.Hash() != b.Hash() { 551 a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1) 552 if a == nil { 553 return nil 554 } 555 b = ReadHeader(db, b.ParentHash, b.Number.Uint64()-1) 556 if b == nil { 557 return nil 558 } 559 } 560 return a 561 }