github.com/etherite/go-etherite@v0.0.0-20171015192807-5f4dd87b2f6e/core/database_util.go (about) 1 // Copyright 2015 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 core 18 19 import ( 20 "bytes" 21 "encoding/binary" 22 "encoding/json" 23 "errors" 24 "fmt" 25 "math/big" 26 27 "github.com/etherite/go-etherite/common" 28 "github.com/etherite/go-etherite/core/types" 29 "github.com/etherite/go-etherite/ethdb" 30 "github.com/etherite/go-etherite/log" 31 "github.com/etherite/go-etherite/metrics" 32 "github.com/etherite/go-etherite/params" 33 "github.com/etherite/go-etherite/rlp" 34 ) 35 36 // DatabaseReader wraps the Get method of a backing data store. 37 type DatabaseReader interface { 38 Get(key []byte) (value []byte, err error) 39 } 40 41 // DatabaseDeleter wraps the Delete method of a backing data store. 42 type DatabaseDeleter interface { 43 Delete(key []byte) error 44 } 45 46 var ( 47 headHeaderKey = []byte("LastHeader") 48 headBlockKey = []byte("LastBlock") 49 headFastKey = []byte("LastFast") 50 51 // Data item prefixes (use single byte to avoid mixing data types, avoid `i`). 52 headerPrefix = []byte("h") // headerPrefix + num (uint64 big endian) + hash -> header 53 tdSuffix = []byte("t") // headerPrefix + num (uint64 big endian) + hash + tdSuffix -> td 54 numSuffix = []byte("n") // headerPrefix + num (uint64 big endian) + numSuffix -> hash 55 blockHashPrefix = []byte("H") // blockHashPrefix + hash -> num (uint64 big endian) 56 bodyPrefix = []byte("b") // bodyPrefix + num (uint64 big endian) + hash -> block body 57 blockReceiptsPrefix = []byte("r") // blockReceiptsPrefix + num (uint64 big endian) + hash -> block receipts 58 lookupPrefix = []byte("l") // lookupPrefix + hash -> transaction/receipt lookup metadata 59 bloomBitsPrefix = []byte("B") // bloomBitsPrefix + bit (uint16 big endian) + section (uint64 big endian) + hash -> bloom bits 60 61 preimagePrefix = "secure-key-" // preimagePrefix + hash -> preimage 62 configPrefix = []byte("ethereum-config-") // config prefix for the db 63 64 // Chain index prefixes (use `i` + single byte to avoid mixing data types). 65 BloomBitsIndexPrefix = []byte("iB") // BloomBitsIndexPrefix is the data table of a chain indexer to track its progress 66 67 // used by old db, now only used for conversion 68 oldReceiptsPrefix = []byte("receipts-") 69 oldTxMetaSuffix = []byte{0x01} 70 71 ErrChainConfigNotFound = errors.New("ChainConfig not found") // general config not found error 72 73 preimageCounter = metrics.NewCounter("db/preimage/total") 74 preimageHitCounter = metrics.NewCounter("db/preimage/hits") 75 ) 76 77 // txLookupEntry is a positional metadata to help looking up the data content of 78 // a transaction or receipt given only its hash. 79 type txLookupEntry struct { 80 BlockHash common.Hash 81 BlockIndex uint64 82 Index uint64 83 } 84 85 // encodeBlockNumber encodes a block number as big endian uint64 86 func encodeBlockNumber(number uint64) []byte { 87 enc := make([]byte, 8) 88 binary.BigEndian.PutUint64(enc, number) 89 return enc 90 } 91 92 // GetCanonicalHash retrieves a hash assigned to a canonical block number. 93 func GetCanonicalHash(db DatabaseReader, number uint64) common.Hash { 94 data, _ := db.Get(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...)) 95 if len(data) == 0 { 96 return common.Hash{} 97 } 98 return common.BytesToHash(data) 99 } 100 101 // missingNumber is returned by GetBlockNumber if no header with the 102 // given block hash has been stored in the database 103 const missingNumber = uint64(0xffffffffffffffff) 104 105 // GetBlockNumber returns the block number assigned to a block hash 106 // if the corresponding header is present in the database 107 func GetBlockNumber(db DatabaseReader, hash common.Hash) uint64 { 108 data, _ := db.Get(append(blockHashPrefix, hash.Bytes()...)) 109 if len(data) != 8 { 110 return missingNumber 111 } 112 return binary.BigEndian.Uint64(data) 113 } 114 115 // GetHeadHeaderHash retrieves the hash of the current canonical head block's 116 // header. The difference between this and GetHeadBlockHash is that whereas the 117 // last block hash is only updated upon a full block import, the last header 118 // hash is updated already at header import, allowing head tracking for the 119 // light synchronization mechanism. 120 func GetHeadHeaderHash(db DatabaseReader) common.Hash { 121 data, _ := db.Get(headHeaderKey) 122 if len(data) == 0 { 123 return common.Hash{} 124 } 125 return common.BytesToHash(data) 126 } 127 128 // GetHeadBlockHash retrieves the hash of the current canonical head block. 129 func GetHeadBlockHash(db DatabaseReader) common.Hash { 130 data, _ := db.Get(headBlockKey) 131 if len(data) == 0 { 132 return common.Hash{} 133 } 134 return common.BytesToHash(data) 135 } 136 137 // GetHeadFastBlockHash retrieves the hash of the current canonical head block during 138 // fast synchronization. The difference between this and GetHeadBlockHash is that 139 // whereas the last block hash is only updated upon a full block import, the last 140 // fast hash is updated when importing pre-processed blocks. 141 func GetHeadFastBlockHash(db DatabaseReader) common.Hash { 142 data, _ := db.Get(headFastKey) 143 if len(data) == 0 { 144 return common.Hash{} 145 } 146 return common.BytesToHash(data) 147 } 148 149 // GetHeaderRLP retrieves a block header in its raw RLP database encoding, or nil 150 // if the header's not found. 151 func GetHeaderRLP(db DatabaseReader, hash common.Hash, number uint64) rlp.RawValue { 152 data, _ := db.Get(headerKey(hash, number)) 153 return data 154 } 155 156 // GetHeader retrieves the block header corresponding to the hash, nil if none 157 // found. 158 func GetHeader(db DatabaseReader, hash common.Hash, number uint64) *types.Header { 159 data := GetHeaderRLP(db, hash, number) 160 if len(data) == 0 { 161 return nil 162 } 163 header := new(types.Header) 164 if err := rlp.Decode(bytes.NewReader(data), header); err != nil { 165 log.Error("Invalid block header RLP", "hash", hash, "err", err) 166 return nil 167 } 168 return header 169 } 170 171 // GetBodyRLP retrieves the block body (transactions and uncles) in RLP encoding. 172 func GetBodyRLP(db DatabaseReader, hash common.Hash, number uint64) rlp.RawValue { 173 data, _ := db.Get(blockBodyKey(hash, number)) 174 return data 175 } 176 177 func headerKey(hash common.Hash, number uint64) []byte { 178 return append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...) 179 } 180 181 func blockBodyKey(hash common.Hash, number uint64) []byte { 182 return append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...) 183 } 184 185 // GetBody retrieves the block body (transactons, uncles) corresponding to the 186 // hash, nil if none found. 187 func GetBody(db DatabaseReader, hash common.Hash, number uint64) *types.Body { 188 data := GetBodyRLP(db, hash, number) 189 if len(data) == 0 { 190 return nil 191 } 192 body := new(types.Body) 193 if err := rlp.Decode(bytes.NewReader(data), body); err != nil { 194 log.Error("Invalid block body RLP", "hash", hash, "err", err) 195 return nil 196 } 197 return body 198 } 199 200 // GetTd retrieves a block's total difficulty corresponding to the hash, nil if 201 // none found. 202 func GetTd(db DatabaseReader, hash common.Hash, number uint64) *big.Int { 203 data, _ := db.Get(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash[:]...), tdSuffix...)) 204 if len(data) == 0 { 205 return nil 206 } 207 td := new(big.Int) 208 if err := rlp.Decode(bytes.NewReader(data), td); err != nil { 209 log.Error("Invalid block total difficulty RLP", "hash", hash, "err", err) 210 return nil 211 } 212 return td 213 } 214 215 // GetBlock retrieves an entire block corresponding to the hash, assembling it 216 // back from the stored header and body. If either the header or body could not 217 // be retrieved nil is returned. 218 // 219 // Note, due to concurrent download of header and block body the header and thus 220 // canonical hash can be stored in the database but the body data not (yet). 221 func GetBlock(db DatabaseReader, hash common.Hash, number uint64) *types.Block { 222 // Retrieve the block header and body contents 223 header := GetHeader(db, hash, number) 224 if header == nil { 225 return nil 226 } 227 body := GetBody(db, hash, number) 228 if body == nil { 229 return nil 230 } 231 // Reassemble the block and return 232 return types.NewBlockWithHeader(header).WithBody(body.Transactions, body.Uncles) 233 } 234 235 // GetBlockReceipts retrieves the receipts generated by the transactions included 236 // in a block given by its hash. 237 func GetBlockReceipts(db DatabaseReader, hash common.Hash, number uint64) types.Receipts { 238 data, _ := db.Get(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash[:]...)) 239 if len(data) == 0 { 240 return nil 241 } 242 storageReceipts := []*types.ReceiptForStorage{} 243 if err := rlp.DecodeBytes(data, &storageReceipts); err != nil { 244 log.Error("Invalid receipt array RLP", "hash", hash, "err", err) 245 return nil 246 } 247 receipts := make(types.Receipts, len(storageReceipts)) 248 for i, receipt := range storageReceipts { 249 receipts[i] = (*types.Receipt)(receipt) 250 } 251 return receipts 252 } 253 254 // GetTxLookupEntry retrieves the positional metadata associated with a transaction 255 // hash to allow retrieving the transaction or receipt by hash. 256 func GetTxLookupEntry(db DatabaseReader, hash common.Hash) (common.Hash, uint64, uint64) { 257 // Load the positional metadata from disk and bail if it fails 258 data, _ := db.Get(append(lookupPrefix, hash.Bytes()...)) 259 if len(data) == 0 { 260 return common.Hash{}, 0, 0 261 } 262 // Parse and return the contents of the lookup entry 263 var entry txLookupEntry 264 if err := rlp.DecodeBytes(data, &entry); err != nil { 265 log.Error("Invalid lookup entry RLP", "hash", hash, "err", err) 266 return common.Hash{}, 0, 0 267 } 268 return entry.BlockHash, entry.BlockIndex, entry.Index 269 } 270 271 // GetTransaction retrieves a specific transaction from the database, along with 272 // its added positional metadata. 273 func GetTransaction(db DatabaseReader, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) { 274 // Retrieve the lookup metadata and resolve the transaction from the body 275 blockHash, blockNumber, txIndex := GetTxLookupEntry(db, hash) 276 277 if blockHash != (common.Hash{}) { 278 body := GetBody(db, blockHash, blockNumber) 279 if body == nil || len(body.Transactions) <= int(txIndex) { 280 log.Error("Transaction referenced missing", "number", blockNumber, "hash", blockHash, "index", txIndex) 281 return nil, common.Hash{}, 0, 0 282 } 283 return body.Transactions[txIndex], blockHash, blockNumber, txIndex 284 } 285 // Old transaction representation, load the transaction and it's metadata separately 286 data, _ := db.Get(hash.Bytes()) 287 if len(data) == 0 { 288 return nil, common.Hash{}, 0, 0 289 } 290 var tx types.Transaction 291 if err := rlp.DecodeBytes(data, &tx); err != nil { 292 return nil, common.Hash{}, 0, 0 293 } 294 // Retrieve the blockchain positional metadata 295 data, _ = db.Get(append(hash.Bytes(), oldTxMetaSuffix...)) 296 if len(data) == 0 { 297 return nil, common.Hash{}, 0, 0 298 } 299 var entry txLookupEntry 300 if err := rlp.DecodeBytes(data, &entry); err != nil { 301 return nil, common.Hash{}, 0, 0 302 } 303 return &tx, entry.BlockHash, entry.BlockIndex, entry.Index 304 } 305 306 // GetReceipt retrieves a specific transaction receipt from the database, along with 307 // its added positional metadata. 308 func GetReceipt(db DatabaseReader, hash common.Hash) (*types.Receipt, common.Hash, uint64, uint64) { 309 // Retrieve the lookup metadata and resolve the receipt from the receipts 310 blockHash, blockNumber, receiptIndex := GetTxLookupEntry(db, hash) 311 312 if blockHash != (common.Hash{}) { 313 receipts := GetBlockReceipts(db, blockHash, blockNumber) 314 if len(receipts) <= int(receiptIndex) { 315 log.Error("Receipt refereced missing", "number", blockNumber, "hash", blockHash, "index", receiptIndex) 316 return nil, common.Hash{}, 0, 0 317 } 318 return receipts[receiptIndex], blockHash, blockNumber, receiptIndex 319 } 320 // Old receipt representation, load the receipt and set an unknown metadata 321 data, _ := db.Get(append(oldReceiptsPrefix, hash[:]...)) 322 if len(data) == 0 { 323 return nil, common.Hash{}, 0, 0 324 } 325 var receipt types.ReceiptForStorage 326 err := rlp.DecodeBytes(data, &receipt) 327 if err != nil { 328 log.Error("Invalid receipt RLP", "hash", hash, "err", err) 329 } 330 return (*types.Receipt)(&receipt), common.Hash{}, 0, 0 331 } 332 333 // GetBloomBits retrieves the compressed bloom bit vector belonging to the given 334 // section and bit index from the. 335 func GetBloomBits(db DatabaseReader, bit uint, section uint64, head common.Hash) []byte { 336 key := append(append(bloomBitsPrefix, make([]byte, 10)...), head.Bytes()...) 337 338 binary.BigEndian.PutUint16(key[1:], uint16(bit)) 339 binary.BigEndian.PutUint64(key[3:], section) 340 341 bits, _ := db.Get(key) 342 return bits 343 } 344 345 // WriteCanonicalHash stores the canonical hash for the given block number. 346 func WriteCanonicalHash(db ethdb.Putter, hash common.Hash, number uint64) error { 347 key := append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...) 348 if err := db.Put(key, hash.Bytes()); err != nil { 349 log.Crit("Failed to store number to hash mapping", "err", err) 350 } 351 return nil 352 } 353 354 // WriteHeadHeaderHash stores the head header's hash. 355 func WriteHeadHeaderHash(db ethdb.Putter, hash common.Hash) error { 356 if err := db.Put(headHeaderKey, hash.Bytes()); err != nil { 357 log.Crit("Failed to store last header's hash", "err", err) 358 } 359 return nil 360 } 361 362 // WriteHeadBlockHash stores the head block's hash. 363 func WriteHeadBlockHash(db ethdb.Putter, hash common.Hash) error { 364 if err := db.Put(headBlockKey, hash.Bytes()); err != nil { 365 log.Crit("Failed to store last block's hash", "err", err) 366 } 367 return nil 368 } 369 370 // WriteHeadFastBlockHash stores the fast head block's hash. 371 func WriteHeadFastBlockHash(db ethdb.Putter, hash common.Hash) error { 372 if err := db.Put(headFastKey, hash.Bytes()); err != nil { 373 log.Crit("Failed to store last fast block's hash", "err", err) 374 } 375 return nil 376 } 377 378 // WriteHeader serializes a block header into the database. 379 func WriteHeader(db ethdb.Putter, header *types.Header) error { 380 data, err := rlp.EncodeToBytes(header) 381 if err != nil { 382 return err 383 } 384 hash := header.Hash().Bytes() 385 num := header.Number.Uint64() 386 encNum := encodeBlockNumber(num) 387 key := append(blockHashPrefix, hash...) 388 if err := db.Put(key, encNum); err != nil { 389 log.Crit("Failed to store hash to number mapping", "err", err) 390 } 391 key = append(append(headerPrefix, encNum...), hash...) 392 if err := db.Put(key, data); err != nil { 393 log.Crit("Failed to store header", "err", err) 394 } 395 return nil 396 } 397 398 // WriteBody serializes the body of a block into the database. 399 func WriteBody(db ethdb.Putter, hash common.Hash, number uint64, body *types.Body) error { 400 data, err := rlp.EncodeToBytes(body) 401 if err != nil { 402 return err 403 } 404 return WriteBodyRLP(db, hash, number, data) 405 } 406 407 // WriteBodyRLP writes a serialized body of a block into the database. 408 func WriteBodyRLP(db ethdb.Putter, hash common.Hash, number uint64, rlp rlp.RawValue) error { 409 key := append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...) 410 if err := db.Put(key, rlp); err != nil { 411 log.Crit("Failed to store block body", "err", err) 412 } 413 return nil 414 } 415 416 // WriteTd serializes the total difficulty of a block into the database. 417 func WriteTd(db ethdb.Putter, hash common.Hash, number uint64, td *big.Int) error { 418 data, err := rlp.EncodeToBytes(td) 419 if err != nil { 420 return err 421 } 422 key := append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...) 423 if err := db.Put(key, data); err != nil { 424 log.Crit("Failed to store block total difficulty", "err", err) 425 } 426 return nil 427 } 428 429 // WriteBlock serializes a block into the database, header and body separately. 430 func WriteBlock(db ethdb.Putter, block *types.Block) error { 431 // Store the body first to retain database consistency 432 if err := WriteBody(db, block.Hash(), block.NumberU64(), block.Body()); err != nil { 433 return err 434 } 435 // Store the header too, signaling full block ownership 436 if err := WriteHeader(db, block.Header()); err != nil { 437 return err 438 } 439 return nil 440 } 441 442 // WriteBlockReceipts stores all the transaction receipts belonging to a block 443 // as a single receipt slice. This is used during chain reorganisations for 444 // rescheduling dropped transactions. 445 func WriteBlockReceipts(db ethdb.Putter, hash common.Hash, number uint64, receipts types.Receipts) error { 446 // Convert the receipts into their storage form and serialize them 447 storageReceipts := make([]*types.ReceiptForStorage, len(receipts)) 448 for i, receipt := range receipts { 449 storageReceipts[i] = (*types.ReceiptForStorage)(receipt) 450 } 451 bytes, err := rlp.EncodeToBytes(storageReceipts) 452 if err != nil { 453 return err 454 } 455 // Store the flattened receipt slice 456 key := append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...) 457 if err := db.Put(key, bytes); err != nil { 458 log.Crit("Failed to store block receipts", "err", err) 459 } 460 return nil 461 } 462 463 // WriteTxLookupEntries stores a positional metadata for every transaction from 464 // a block, enabling hash based transaction and receipt lookups. 465 func WriteTxLookupEntries(db ethdb.Putter, block *types.Block) error { 466 // Iterate over each transaction and encode its metadata 467 for i, tx := range block.Transactions() { 468 entry := txLookupEntry{ 469 BlockHash: block.Hash(), 470 BlockIndex: block.NumberU64(), 471 Index: uint64(i), 472 } 473 data, err := rlp.EncodeToBytes(entry) 474 if err != nil { 475 return err 476 } 477 if err := db.Put(append(lookupPrefix, tx.Hash().Bytes()...), data); err != nil { 478 return err 479 } 480 } 481 return nil 482 } 483 484 // WriteBloomBits writes the compressed bloom bits vector belonging to the given 485 // section and bit index. 486 func WriteBloomBits(db ethdb.Putter, bit uint, section uint64, head common.Hash, bits []byte) { 487 key := append(append(bloomBitsPrefix, make([]byte, 10)...), head.Bytes()...) 488 489 binary.BigEndian.PutUint16(key[1:], uint16(bit)) 490 binary.BigEndian.PutUint64(key[3:], section) 491 492 if err := db.Put(key, bits); err != nil { 493 log.Crit("Failed to store bloom bits", "err", err) 494 } 495 } 496 497 // DeleteCanonicalHash removes the number to hash canonical mapping. 498 func DeleteCanonicalHash(db DatabaseDeleter, number uint64) { 499 db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), numSuffix...)) 500 } 501 502 // DeleteHeader removes all block header data associated with a hash. 503 func DeleteHeader(db DatabaseDeleter, hash common.Hash, number uint64) { 504 db.Delete(append(blockHashPrefix, hash.Bytes()...)) 505 db.Delete(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...)) 506 } 507 508 // DeleteBody removes all block body data associated with a hash. 509 func DeleteBody(db DatabaseDeleter, hash common.Hash, number uint64) { 510 db.Delete(append(append(bodyPrefix, encodeBlockNumber(number)...), hash.Bytes()...)) 511 } 512 513 // DeleteTd removes all block total difficulty data associated with a hash. 514 func DeleteTd(db DatabaseDeleter, hash common.Hash, number uint64) { 515 db.Delete(append(append(append(headerPrefix, encodeBlockNumber(number)...), hash.Bytes()...), tdSuffix...)) 516 } 517 518 // DeleteBlock removes all block data associated with a hash. 519 func DeleteBlock(db DatabaseDeleter, hash common.Hash, number uint64) { 520 DeleteBlockReceipts(db, hash, number) 521 DeleteHeader(db, hash, number) 522 DeleteBody(db, hash, number) 523 DeleteTd(db, hash, number) 524 } 525 526 // DeleteBlockReceipts removes all receipt data associated with a block hash. 527 func DeleteBlockReceipts(db DatabaseDeleter, hash common.Hash, number uint64) { 528 db.Delete(append(append(blockReceiptsPrefix, encodeBlockNumber(number)...), hash.Bytes()...)) 529 } 530 531 // DeleteTxLookupEntry removes all transaction data associated with a hash. 532 func DeleteTxLookupEntry(db DatabaseDeleter, hash common.Hash) { 533 db.Delete(append(lookupPrefix, hash.Bytes()...)) 534 } 535 536 // PreimageTable returns a Database instance with the key prefix for preimage entries. 537 func PreimageTable(db ethdb.Database) ethdb.Database { 538 return ethdb.NewTable(db, preimagePrefix) 539 } 540 541 // WritePreimages writes the provided set of preimages to the database. `number` is the 542 // current block number, and is used for debug messages only. 543 func WritePreimages(db ethdb.Database, number uint64, preimages map[common.Hash][]byte) error { 544 table := PreimageTable(db) 545 batch := table.NewBatch() 546 hitCount := 0 547 for hash, preimage := range preimages { 548 if _, err := table.Get(hash.Bytes()); err != nil { 549 batch.Put(hash.Bytes(), preimage) 550 hitCount++ 551 } 552 } 553 preimageCounter.Inc(int64(len(preimages))) 554 preimageHitCounter.Inc(int64(hitCount)) 555 if hitCount > 0 { 556 if err := batch.Write(); err != nil { 557 return fmt.Errorf("preimage write fail for block %d: %v", number, err) 558 } 559 } 560 return nil 561 } 562 563 // GetBlockChainVersion reads the version number from db. 564 func GetBlockChainVersion(db DatabaseReader) int { 565 var vsn uint 566 enc, _ := db.Get([]byte("BlockchainVersion")) 567 rlp.DecodeBytes(enc, &vsn) 568 return int(vsn) 569 } 570 571 // WriteBlockChainVersion writes vsn as the version number to db. 572 func WriteBlockChainVersion(db ethdb.Putter, vsn int) { 573 enc, _ := rlp.EncodeToBytes(uint(vsn)) 574 db.Put([]byte("BlockchainVersion"), enc) 575 } 576 577 // WriteChainConfig writes the chain config settings to the database. 578 func WriteChainConfig(db ethdb.Putter, hash common.Hash, cfg *params.ChainConfig) error { 579 // short circuit and ignore if nil config. GetChainConfig 580 // will return a default. 581 if cfg == nil { 582 return nil 583 } 584 585 jsonChainConfig, err := json.Marshal(cfg) 586 if err != nil { 587 return err 588 } 589 590 return db.Put(append(configPrefix, hash[:]...), jsonChainConfig) 591 } 592 593 // GetChainConfig will fetch the network settings based on the given hash. 594 func GetChainConfig(db DatabaseReader, hash common.Hash) (*params.ChainConfig, error) { 595 jsonChainConfig, _ := db.Get(append(configPrefix, hash[:]...)) 596 if len(jsonChainConfig) == 0 { 597 return nil, ErrChainConfigNotFound 598 } 599 600 var config params.ChainConfig 601 if err := json.Unmarshal(jsonChainConfig, &config); err != nil { 602 return nil, err 603 } 604 605 return &config, nil 606 } 607 608 // FindCommonAncestor returns the last common ancestor of two block headers 609 func FindCommonAncestor(db DatabaseReader, a, b *types.Header) *types.Header { 610 for bn := b.Number.Uint64(); a.Number.Uint64() > bn; { 611 a = GetHeader(db, a.ParentHash, a.Number.Uint64()-1) 612 if a == nil { 613 return nil 614 } 615 } 616 for an := a.Number.Uint64(); an < b.Number.Uint64(); { 617 b = GetHeader(db, b.ParentHash, b.Number.Uint64()-1) 618 if b == nil { 619 return nil 620 } 621 } 622 for a.Hash() != b.Hash() { 623 a = GetHeader(db, a.ParentHash, a.Number.Uint64()-1) 624 if a == nil { 625 return nil 626 } 627 b = GetHeader(db, b.ParentHash, b.Number.Uint64()-1) 628 if b == nil { 629 return nil 630 } 631 } 632 return a 633 }