github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/core/headerchain.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 crand "crypto/rand" 21 "errors" 22 "fmt" 23 "math" 24 "math/big" 25 mrand "math/rand" 26 "sync/atomic" 27 "time" 28 29 lru "github.com/hashicorp/golang-lru" 30 "github.com/zhiqiangxu/go-ethereum/common" 31 "github.com/zhiqiangxu/go-ethereum/consensus" 32 "github.com/zhiqiangxu/go-ethereum/core/rawdb" 33 "github.com/zhiqiangxu/go-ethereum/core/types" 34 "github.com/zhiqiangxu/go-ethereum/ethdb" 35 "github.com/zhiqiangxu/go-ethereum/log" 36 "github.com/zhiqiangxu/go-ethereum/params" 37 ) 38 39 const ( 40 headerCacheLimit = 512 41 tdCacheLimit = 1024 42 numberCacheLimit = 2048 43 ) 44 45 // HeaderChain implements the basic block header chain logic that is shared by 46 // core.BlockChain and light.LightChain. It is not usable in itself, only as 47 // a part of either structure. 48 // 49 // HeaderChain is responsible for maintaining the header chain including the 50 // header query and updating. 51 // 52 // The components maintained by headerchain includes: (1) total difficult 53 // (2) header (3) block hash -> number mapping (4) canonical number -> hash mapping 54 // and (5) head header flag. 55 // 56 // It is not thread safe either, the encapsulating chain structures should do 57 // the necessary mutex locking/unlocking. 58 type HeaderChain struct { 59 config *params.ChainConfig 60 61 chainDb ethdb.Database 62 genesisHeader *types.Header 63 64 currentHeader atomic.Value // Current head of the header chain (may be above the block chain!) 65 currentHeaderHash common.Hash // Hash of the current head of the header chain (prevent recomputing all the time) 66 67 headerCache *lru.Cache // Cache for the most recent block headers 68 tdCache *lru.Cache // Cache for the most recent block total difficulties 69 numberCache *lru.Cache // Cache for the most recent block numbers 70 71 procInterrupt func() bool 72 73 rand *mrand.Rand 74 engine consensus.Engine 75 } 76 77 // NewHeaderChain creates a new HeaderChain structure. ProcInterrupt points 78 // to the parent's interrupt semaphore. 79 func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) { 80 headerCache, _ := lru.New(headerCacheLimit) 81 tdCache, _ := lru.New(tdCacheLimit) 82 numberCache, _ := lru.New(numberCacheLimit) 83 84 // Seed a fast but crypto originating random generator 85 seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64)) 86 if err != nil { 87 return nil, err 88 } 89 90 hc := &HeaderChain{ 91 config: config, 92 chainDb: chainDb, 93 headerCache: headerCache, 94 tdCache: tdCache, 95 numberCache: numberCache, 96 procInterrupt: procInterrupt, 97 rand: mrand.New(mrand.NewSource(seed.Int64())), 98 engine: engine, 99 } 100 101 hc.genesisHeader = hc.GetHeaderByNumber(0) 102 if hc.genesisHeader == nil { 103 return nil, ErrNoGenesis 104 } 105 106 hc.currentHeader.Store(hc.genesisHeader) 107 if head := rawdb.ReadHeadBlockHash(chainDb); head != (common.Hash{}) { 108 if chead := hc.GetHeaderByHash(head); chead != nil { 109 hc.currentHeader.Store(chead) 110 } 111 } 112 hc.currentHeaderHash = hc.CurrentHeader().Hash() 113 headHeaderGauge.Update(hc.CurrentHeader().Number.Int64()) 114 115 return hc, nil 116 } 117 118 // GetBlockNumber retrieves the block number belonging to the given hash 119 // from the cache or database 120 func (hc *HeaderChain) GetBlockNumber(hash common.Hash) *uint64 { 121 if cached, ok := hc.numberCache.Get(hash); ok { 122 number := cached.(uint64) 123 return &number 124 } 125 number := rawdb.ReadHeaderNumber(hc.chainDb, hash) 126 if number != nil { 127 hc.numberCache.Add(hash, *number) 128 } 129 return number 130 } 131 132 // WriteHeader writes a header into the local chain, given that its parent is 133 // already known. If the total difficulty of the newly inserted header becomes 134 // greater than the current known TD, the canonical chain is re-routed. 135 // 136 // Note: This method is not concurrent-safe with inserting blocks simultaneously 137 // into the chain, as side effects caused by reorganisations cannot be emulated 138 // without the real blocks. Hence, writing headers directly should only be done 139 // in two scenarios: pure-header mode of operation (light clients), or properly 140 // separated header/block phases (non-archive clients). 141 func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, err error) { 142 // Cache some values to prevent constant recalculation 143 var ( 144 hash = header.Hash() 145 number = header.Number.Uint64() 146 ) 147 // Calculate the total difficulty of the header 148 ptd := hc.GetTd(header.ParentHash, number-1) 149 if ptd == nil { 150 return NonStatTy, consensus.ErrUnknownAncestor 151 } 152 head := hc.CurrentHeader().Number.Uint64() 153 localTd := hc.GetTd(hc.currentHeaderHash, head) 154 externTd := new(big.Int).Add(header.Difficulty, ptd) 155 156 // Irrelevant of the canonical status, write the td and header to the database 157 // 158 // Note all the components of header(td, hash->number index and header) should 159 // be written atomically. 160 headerBatch := hc.chainDb.NewBatch() 161 rawdb.WriteTd(headerBatch, hash, number, externTd) 162 rawdb.WriteHeader(headerBatch, header) 163 if err := headerBatch.Write(); err != nil { 164 log.Crit("Failed to write header into disk", "err", err) 165 } 166 // If the total difficulty is higher than our known, add it to the canonical chain 167 // Second clause in the if statement reduces the vulnerability to selfish mining. 168 // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf 169 reorg := externTd.Cmp(localTd) > 0 170 if !reorg && externTd.Cmp(localTd) == 0 { 171 if header.Number.Uint64() < head { 172 reorg = true 173 } else if header.Number.Uint64() == head { 174 reorg = mrand.Float64() < 0.5 175 } 176 } 177 if reorg { 178 // If the header can be added into canonical chain, adjust the 179 // header chain markers(canonical indexes and head header flag). 180 // 181 // Note all markers should be written atomically. 182 183 // Delete any canonical number assignments above the new head 184 markerBatch := hc.chainDb.NewBatch() 185 for i := number + 1; ; i++ { 186 hash := rawdb.ReadCanonicalHash(hc.chainDb, i) 187 if hash == (common.Hash{}) { 188 break 189 } 190 rawdb.DeleteCanonicalHash(markerBatch, i) 191 } 192 193 // Overwrite any stale canonical number assignments 194 var ( 195 headHash = header.ParentHash 196 headNumber = header.Number.Uint64() - 1 197 headHeader = hc.GetHeader(headHash, headNumber) 198 ) 199 for rawdb.ReadCanonicalHash(hc.chainDb, headNumber) != headHash { 200 rawdb.WriteCanonicalHash(markerBatch, headHash, headNumber) 201 202 headHash = headHeader.ParentHash 203 headNumber = headHeader.Number.Uint64() - 1 204 headHeader = hc.GetHeader(headHash, headNumber) 205 } 206 // Extend the canonical chain with the new header 207 rawdb.WriteCanonicalHash(markerBatch, hash, number) 208 rawdb.WriteHeadHeaderHash(markerBatch, hash) 209 if err := markerBatch.Write(); err != nil { 210 log.Crit("Failed to write header markers into disk", "err", err) 211 } 212 // Last step update all in-memory head header markers 213 hc.currentHeaderHash = hash 214 hc.currentHeader.Store(types.CopyHeader(header)) 215 headHeaderGauge.Update(header.Number.Int64()) 216 217 status = CanonStatTy 218 } else { 219 status = SideStatTy 220 } 221 hc.tdCache.Add(hash, externTd) 222 hc.headerCache.Add(hash, header) 223 hc.numberCache.Add(hash, number) 224 return 225 } 226 227 // WhCallback is a callback function for inserting individual headers. 228 // A callback is used for two reasons: first, in a LightChain, status should be 229 // processed and light chain events sent, while in a BlockChain this is not 230 // necessary since chain events are sent after inserting blocks. Second, the 231 // header writes should be protected by the parent chain mutex individually. 232 type WhCallback func(*types.Header) error 233 234 func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) { 235 // Do a sanity check that the provided chain is actually ordered and linked 236 for i := 1; i < len(chain); i++ { 237 if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() { 238 // Chain broke ancestry, log a message (programming error) and skip insertion 239 log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(), 240 "parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash()) 241 242 return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].Number, 243 chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4]) 244 } 245 } 246 247 // Generate the list of seal verification requests, and start the parallel verifier 248 seals := make([]bool, len(chain)) 249 if checkFreq != 0 { 250 // In case of checkFreq == 0 all seals are left false. 251 for i := 0; i < len(seals)/checkFreq; i++ { 252 index := i*checkFreq + hc.rand.Intn(checkFreq) 253 if index >= len(seals) { 254 index = len(seals) - 1 255 } 256 seals[index] = true 257 } 258 // Last should always be verified to avoid junk. 259 seals[len(seals)-1] = true 260 } 261 262 abort, results := hc.engine.VerifyHeaders(hc, chain, seals) 263 defer close(abort) 264 265 // Iterate over the headers and ensure they all check out 266 for i, header := range chain { 267 // If the chain is terminating, stop processing blocks 268 if hc.procInterrupt() { 269 log.Debug("Premature abort during headers verification") 270 return 0, errors.New("aborted") 271 } 272 // If the header is a banned one, straight out abort 273 if BadHashes[header.Hash()] { 274 return i, ErrBlacklistedHash 275 } 276 // Otherwise wait for headers checks and ensure they pass 277 if err := <-results; err != nil { 278 return i, err 279 } 280 } 281 282 return 0, nil 283 } 284 285 // InsertHeaderChain attempts to insert the given header chain in to the local 286 // chain, possibly creating a reorg. If an error is returned, it will return the 287 // index number of the failing header as well an error describing what went wrong. 288 // 289 // The verify parameter can be used to fine tune whether nonce verification 290 // should be done or not. The reason behind the optional check is because some 291 // of the header retrieval mechanisms already need to verfy nonces, as well as 292 // because nonces can be verified sparsely, not needing to check each. 293 func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) { 294 // Collect some import statistics to report on 295 stats := struct{ processed, ignored int }{} 296 // All headers passed verification, import them into the database 297 for i, header := range chain { 298 // Short circuit insertion if shutting down 299 if hc.procInterrupt() { 300 log.Debug("Premature abort during headers import") 301 return i, errors.New("aborted") 302 } 303 // If the header's already known, skip it, otherwise store 304 hash := header.Hash() 305 if hc.HasHeader(hash, header.Number.Uint64()) { 306 externTd := hc.GetTd(hash, header.Number.Uint64()) 307 localTd := hc.GetTd(hc.currentHeaderHash, hc.CurrentHeader().Number.Uint64()) 308 if externTd == nil || externTd.Cmp(localTd) <= 0 { 309 stats.ignored++ 310 continue 311 } 312 } 313 if err := writeHeader(header); err != nil { 314 return i, err 315 } 316 stats.processed++ 317 } 318 // Report some public statistics so the user has a clue what's going on 319 last := chain[len(chain)-1] 320 321 context := []interface{}{ 322 "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)), 323 "number", last.Number, "hash", last.Hash(), 324 } 325 if timestamp := time.Unix(int64(last.Time), 0); time.Since(timestamp) > time.Minute { 326 context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...) 327 } 328 if stats.ignored > 0 { 329 context = append(context, []interface{}{"ignored", stats.ignored}...) 330 } 331 log.Info("Imported new block headers", context...) 332 333 return 0, nil 334 } 335 336 // GetBlockHashesFromHash retrieves a number of block hashes starting at a given 337 // hash, fetching towards the genesis block. 338 func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { 339 // Get the origin header from which to fetch 340 header := hc.GetHeaderByHash(hash) 341 if header == nil { 342 return nil 343 } 344 // Iterate the headers until enough is collected or the genesis reached 345 chain := make([]common.Hash, 0, max) 346 for i := uint64(0); i < max; i++ { 347 next := header.ParentHash 348 if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil { 349 break 350 } 351 chain = append(chain, next) 352 if header.Number.Sign() == 0 { 353 break 354 } 355 } 356 return chain 357 } 358 359 // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or 360 // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the 361 // number of blocks to be individually checked before we reach the canonical chain. 362 // 363 // Note: ancestor == 0 returns the same block, 1 returns its parent and so on. 364 func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) { 365 if ancestor > number { 366 return common.Hash{}, 0 367 } 368 if ancestor == 1 { 369 // in this case it is cheaper to just read the header 370 if header := hc.GetHeader(hash, number); header != nil { 371 return header.ParentHash, number - 1 372 } else { 373 return common.Hash{}, 0 374 } 375 } 376 for ancestor != 0 { 377 if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash { 378 ancestorHash := rawdb.ReadCanonicalHash(hc.chainDb, number-ancestor) 379 if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash { 380 number -= ancestor 381 return ancestorHash, number 382 } 383 } 384 if *maxNonCanonical == 0 { 385 return common.Hash{}, 0 386 } 387 *maxNonCanonical-- 388 ancestor-- 389 header := hc.GetHeader(hash, number) 390 if header == nil { 391 return common.Hash{}, 0 392 } 393 hash = header.ParentHash 394 number-- 395 } 396 return hash, number 397 } 398 399 // GetTd retrieves a block's total difficulty in the canonical chain from the 400 // database by hash and number, caching it if found. 401 func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int { 402 // Short circuit if the td's already in the cache, retrieve otherwise 403 if cached, ok := hc.tdCache.Get(hash); ok { 404 return cached.(*big.Int) 405 } 406 td := rawdb.ReadTd(hc.chainDb, hash, number) 407 if td == nil { 408 return nil 409 } 410 // Cache the found body for next time and return 411 hc.tdCache.Add(hash, td) 412 return td 413 } 414 415 // GetTdByHash retrieves a block's total difficulty in the canonical chain from the 416 // database by hash, caching it if found. 417 func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int { 418 number := hc.GetBlockNumber(hash) 419 if number == nil { 420 return nil 421 } 422 return hc.GetTd(hash, *number) 423 } 424 425 // GetHeader retrieves a block header from the database by hash and number, 426 // caching it if found. 427 func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header { 428 // Short circuit if the header's already in the cache, retrieve otherwise 429 if header, ok := hc.headerCache.Get(hash); ok { 430 return header.(*types.Header) 431 } 432 header := rawdb.ReadHeader(hc.chainDb, hash, number) 433 if header == nil { 434 return nil 435 } 436 // Cache the found header for next time and return 437 hc.headerCache.Add(hash, header) 438 return header 439 } 440 441 // GetHeaderByHash retrieves a block header from the database by hash, caching it if 442 // found. 443 func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header { 444 number := hc.GetBlockNumber(hash) 445 if number == nil { 446 return nil 447 } 448 return hc.GetHeader(hash, *number) 449 } 450 451 // HasHeader checks if a block header is present in the database or not. 452 // In theory, if header is present in the database, all relative components 453 // like td and hash->number should be present too. 454 func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool { 455 if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) { 456 return true 457 } 458 return rawdb.HasHeader(hc.chainDb, hash, number) 459 } 460 461 // GetHeaderByNumber retrieves a block header from the database by number, 462 // caching it (associated with its hash) if found. 463 func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header { 464 hash := rawdb.ReadCanonicalHash(hc.chainDb, number) 465 if hash == (common.Hash{}) { 466 return nil 467 } 468 return hc.GetHeader(hash, number) 469 } 470 471 func (hc *HeaderChain) GetCanonicalHash(number uint64) common.Hash { 472 return rawdb.ReadCanonicalHash(hc.chainDb, number) 473 } 474 475 // CurrentHeader retrieves the current head header of the canonical chain. The 476 // header is retrieved from the HeaderChain's internal cache. 477 func (hc *HeaderChain) CurrentHeader() *types.Header { 478 return hc.currentHeader.Load().(*types.Header) 479 } 480 481 // SetCurrentHeader sets the in-memory head header marker of the canonical chan 482 // as the given header. 483 func (hc *HeaderChain) SetCurrentHeader(head *types.Header) { 484 hc.currentHeader.Store(head) 485 hc.currentHeaderHash = head.Hash() 486 headHeaderGauge.Update(head.Number.Int64()) 487 } 488 489 type ( 490 // UpdateHeadBlocksCallback is a callback function that is called by SetHead 491 // before head header is updated. 492 UpdateHeadBlocksCallback func(ethdb.KeyValueWriter, *types.Header) 493 494 // DeleteBlockContentCallback is a callback function that is called by SetHead 495 // before each header is deleted. 496 DeleteBlockContentCallback func(ethdb.KeyValueWriter, common.Hash, uint64) 497 ) 498 499 // SetHead rewinds the local chain to a new head. Everything above the new head 500 // will be deleted and the new one set. 501 func (hc *HeaderChain) SetHead(head uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) { 502 var ( 503 parentHash common.Hash 504 batch = hc.chainDb.NewBatch() 505 ) 506 for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() { 507 hash, num := hdr.Hash(), hdr.Number.Uint64() 508 509 // Rewind block chain to new head. 510 parent := hc.GetHeader(hdr.ParentHash, num-1) 511 if parent == nil { 512 parent = hc.genesisHeader 513 } 514 parentHash = hdr.ParentHash 515 // Notably, since geth has the possibility for setting the head to a low 516 // height which is even lower than ancient head. 517 // In order to ensure that the head is always no higher than the data in 518 // the database(ancient store or active store), we need to update head 519 // first then remove the relative data from the database. 520 // 521 // Update head first(head fast block, head full block) before deleting the data. 522 markerBatch := hc.chainDb.NewBatch() 523 if updateFn != nil { 524 updateFn(markerBatch, parent) 525 } 526 // Update head header then. 527 rawdb.WriteHeadHeaderHash(markerBatch, parentHash) 528 if err := markerBatch.Write(); err != nil { 529 log.Crit("Failed to update chain markers", "error", err) 530 } 531 hc.currentHeader.Store(parent) 532 hc.currentHeaderHash = parentHash 533 headHeaderGauge.Update(parent.Number.Int64()) 534 535 // Remove the relative data from the database. 536 if delFn != nil { 537 delFn(batch, hash, num) 538 } 539 // Rewind header chain to new head. 540 rawdb.DeleteHeader(batch, hash, num) 541 rawdb.DeleteTd(batch, hash, num) 542 rawdb.DeleteCanonicalHash(batch, num) 543 } 544 // Flush all accumulated deletions. 545 if err := batch.Write(); err != nil { 546 log.Crit("Failed to rewind block", "error", err) 547 } 548 // Clear out any stale content from the caches 549 hc.headerCache.Purge() 550 hc.tdCache.Purge() 551 hc.numberCache.Purge() 552 } 553 554 // SetGenesis sets a new genesis block header for the chain 555 func (hc *HeaderChain) SetGenesis(head *types.Header) { 556 hc.genesisHeader = head 557 } 558 559 // Config retrieves the header chain's chain configuration. 560 func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config } 561 562 // Engine retrieves the header chain's consensus engine. 563 func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine } 564 565 // GetBlock implements consensus.ChainReader, and returns nil for every input as 566 // a header chain does not have blocks available for retrieval. 567 func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block { 568 return nil 569 }