github.com/JFJun/bsc@v1.0.0/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 "github.com/JFJun/bsc/common" 30 "github.com/JFJun/bsc/consensus" 31 "github.com/JFJun/bsc/core/rawdb" 32 "github.com/JFJun/bsc/core/types" 33 "github.com/JFJun/bsc/ethdb" 34 "github.com/JFJun/bsc/log" 35 "github.com/JFJun/bsc/params" 36 lru "github.com/hashicorp/golang-lru" 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 localTd := hc.GetTd(hc.currentHeaderHash, hc.CurrentHeader().Number.Uint64()) 153 externTd := new(big.Int).Add(header.Difficulty, ptd) 154 155 // Irrelevant of the canonical status, write the td and header to the database 156 // 157 // Note all the components of header(td, hash->number index and header) should 158 // be written atomically. 159 headerBatch := hc.chainDb.NewBatch() 160 rawdb.WriteTd(headerBatch, hash, number, externTd) 161 rawdb.WriteHeader(headerBatch, header) 162 if err := headerBatch.Write(); err != nil { 163 log.Crit("Failed to write header into disk", "err", err) 164 } 165 // If the total difficulty is higher than our known, add it to the canonical chain 166 // Second clause in the if statement reduces the vulnerability to selfish mining. 167 // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf 168 if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) { 169 // If the header can be added into canonical chain, adjust the 170 // header chain markers(canonical indexes and head header flag). 171 // 172 // Note all markers should be written atomically. 173 174 // Delete any canonical number assignments above the new head 175 markerBatch := hc.chainDb.NewBatch() 176 for i := number + 1; ; i++ { 177 hash := rawdb.ReadCanonicalHash(hc.chainDb, i) 178 if hash == (common.Hash{}) { 179 break 180 } 181 rawdb.DeleteCanonicalHash(markerBatch, i) 182 } 183 184 // Overwrite any stale canonical number assignments 185 var ( 186 headHash = header.ParentHash 187 headNumber = header.Number.Uint64() - 1 188 headHeader = hc.GetHeader(headHash, headNumber) 189 ) 190 for rawdb.ReadCanonicalHash(hc.chainDb, headNumber) != headHash { 191 rawdb.WriteCanonicalHash(markerBatch, headHash, headNumber) 192 193 headHash = headHeader.ParentHash 194 headNumber = headHeader.Number.Uint64() - 1 195 headHeader = hc.GetHeader(headHash, headNumber) 196 } 197 // Extend the canonical chain with the new header 198 rawdb.WriteCanonicalHash(markerBatch, hash, number) 199 rawdb.WriteHeadHeaderHash(markerBatch, hash) 200 if err := markerBatch.Write(); err != nil { 201 log.Crit("Failed to write header markers into disk", "err", err) 202 } 203 // Last step update all in-memory head header markers 204 hc.currentHeaderHash = hash 205 hc.currentHeader.Store(types.CopyHeader(header)) 206 headHeaderGauge.Update(header.Number.Int64()) 207 208 status = CanonStatTy 209 } else { 210 status = SideStatTy 211 } 212 hc.tdCache.Add(hash, externTd) 213 hc.headerCache.Add(hash, header) 214 hc.numberCache.Add(hash, number) 215 return 216 } 217 218 // WhCallback is a callback function for inserting individual headers. 219 // A callback is used for two reasons: first, in a LightChain, status should be 220 // processed and light chain events sent, while in a BlockChain this is not 221 // necessary since chain events are sent after inserting blocks. Second, the 222 // header writes should be protected by the parent chain mutex individually. 223 type WhCallback func(*types.Header) error 224 225 func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) { 226 // Do a sanity check that the provided chain is actually ordered and linked 227 for i := 1; i < len(chain); i++ { 228 if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() { 229 // Chain broke ancestry, log a message (programming error) and skip insertion 230 log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(), 231 "parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash()) 232 233 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, 234 chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4]) 235 } 236 } 237 238 // Generate the list of seal verification requests, and start the parallel verifier 239 seals := make([]bool, len(chain)) 240 if checkFreq != 0 { 241 // In case of checkFreq == 0 all seals are left false. 242 for i := 0; i < len(seals)/checkFreq; i++ { 243 index := i*checkFreq + hc.rand.Intn(checkFreq) 244 if index >= len(seals) { 245 index = len(seals) - 1 246 } 247 seals[index] = true 248 } 249 // Last should always be verified to avoid junk. 250 seals[len(seals)-1] = true 251 } 252 253 abort, results := hc.engine.VerifyHeaders(hc, chain, seals) 254 defer close(abort) 255 256 // Iterate over the headers and ensure they all check out 257 for i, header := range chain { 258 // If the chain is terminating, stop processing blocks 259 if hc.procInterrupt() { 260 log.Debug("Premature abort during headers verification") 261 return 0, errors.New("aborted") 262 } 263 // If the header is a banned one, straight out abort 264 if BadHashes[header.Hash()] { 265 return i, ErrBlacklistedHash 266 } 267 // Otherwise wait for headers checks and ensure they pass 268 if err := <-results; err != nil { 269 return i, err 270 } 271 } 272 273 return 0, nil 274 } 275 276 // InsertHeaderChain attempts to insert the given header chain in to the local 277 // chain, possibly creating a reorg. If an error is returned, it will return the 278 // index number of the failing header as well an error describing what went wrong. 279 // 280 // The verify parameter can be used to fine tune whether nonce verification 281 // should be done or not. The reason behind the optional check is because some 282 // of the header retrieval mechanisms already need to verfy nonces, as well as 283 // because nonces can be verified sparsely, not needing to check each. 284 func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) { 285 // Collect some import statistics to report on 286 stats := struct{ processed, ignored int }{} 287 // All headers passed verification, import them into the database 288 for i, header := range chain { 289 // Short circuit insertion if shutting down 290 if hc.procInterrupt() { 291 log.Debug("Premature abort during headers import") 292 return i, errors.New("aborted") 293 } 294 // If the header's already known, skip it, otherwise store 295 hash := header.Hash() 296 if hc.HasHeader(hash, header.Number.Uint64()) { 297 externTd := hc.GetTd(hash, header.Number.Uint64()) 298 localTd := hc.GetTd(hc.currentHeaderHash, hc.CurrentHeader().Number.Uint64()) 299 if externTd == nil || externTd.Cmp(localTd) <= 0 { 300 stats.ignored++ 301 continue 302 } 303 } 304 if err := writeHeader(header); err != nil { 305 return i, err 306 } 307 stats.processed++ 308 } 309 // Report some public statistics so the user has a clue what's going on 310 last := chain[len(chain)-1] 311 312 context := []interface{}{ 313 "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)), 314 "number", last.Number, "hash", last.Hash(), 315 } 316 if timestamp := time.Unix(int64(last.Time), 0); time.Since(timestamp) > time.Minute { 317 context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...) 318 } 319 if stats.ignored > 0 { 320 context = append(context, []interface{}{"ignored", stats.ignored}...) 321 } 322 log.Info("Imported new block headers", context...) 323 324 return 0, nil 325 } 326 327 // GetBlockHashesFromHash retrieves a number of block hashes starting at a given 328 // hash, fetching towards the genesis block. 329 func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { 330 // Get the origin header from which to fetch 331 header := hc.GetHeaderByHash(hash) 332 if header == nil { 333 return nil 334 } 335 // Iterate the headers until enough is collected or the genesis reached 336 chain := make([]common.Hash, 0, max) 337 for i := uint64(0); i < max; i++ { 338 next := header.ParentHash 339 if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil { 340 break 341 } 342 chain = append(chain, next) 343 if header.Number.Sign() == 0 { 344 break 345 } 346 } 347 return chain 348 } 349 350 // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or 351 // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the 352 // number of blocks to be individually checked before we reach the canonical chain. 353 // 354 // Note: ancestor == 0 returns the same block, 1 returns its parent and so on. 355 func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) { 356 if ancestor > number { 357 return common.Hash{}, 0 358 } 359 if ancestor == 1 { 360 // in this case it is cheaper to just read the header 361 if header := hc.GetHeader(hash, number); header != nil { 362 return header.ParentHash, number - 1 363 } else { 364 return common.Hash{}, 0 365 } 366 } 367 for ancestor != 0 { 368 if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash { 369 ancestorHash := rawdb.ReadCanonicalHash(hc.chainDb, number-ancestor) 370 if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash { 371 number -= ancestor 372 return ancestorHash, number 373 } 374 } 375 if *maxNonCanonical == 0 { 376 return common.Hash{}, 0 377 } 378 *maxNonCanonical-- 379 ancestor-- 380 header := hc.GetHeader(hash, number) 381 if header == nil { 382 return common.Hash{}, 0 383 } 384 hash = header.ParentHash 385 number-- 386 } 387 return hash, number 388 } 389 390 // GetTd retrieves a block's total difficulty in the canonical chain from the 391 // database by hash and number, caching it if found. 392 func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int { 393 // Short circuit if the td's already in the cache, retrieve otherwise 394 if cached, ok := hc.tdCache.Get(hash); ok { 395 return cached.(*big.Int) 396 } 397 td := rawdb.ReadTd(hc.chainDb, hash, number) 398 if td == nil { 399 return nil 400 } 401 // Cache the found body for next time and return 402 hc.tdCache.Add(hash, td) 403 return td 404 } 405 406 // GetTdByHash retrieves a block's total difficulty in the canonical chain from the 407 // database by hash, caching it if found. 408 func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int { 409 number := hc.GetBlockNumber(hash) 410 if number == nil { 411 return nil 412 } 413 return hc.GetTd(hash, *number) 414 } 415 416 // GetHeader retrieves a block header from the database by hash and number, 417 // caching it if found. 418 func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header { 419 // Short circuit if the header's already in the cache, retrieve otherwise 420 if header, ok := hc.headerCache.Get(hash); ok { 421 return header.(*types.Header) 422 } 423 header := rawdb.ReadHeader(hc.chainDb, hash, number) 424 if header == nil { 425 return nil 426 } 427 // Cache the found header for next time and return 428 hc.headerCache.Add(hash, header) 429 return header 430 } 431 432 // GetHeaderByHash retrieves a block header from the database by hash, caching it if 433 // found. 434 func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header { 435 number := hc.GetBlockNumber(hash) 436 if number == nil { 437 return nil 438 } 439 return hc.GetHeader(hash, *number) 440 } 441 442 // HasHeader checks if a block header is present in the database or not. 443 // In theory, if header is present in the database, all relative components 444 // like td and hash->number should be present too. 445 func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool { 446 if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) { 447 return true 448 } 449 return rawdb.HasHeader(hc.chainDb, hash, number) 450 } 451 452 // GetHeaderByNumber retrieves a block header from the database by number, 453 // caching it (associated with its hash) if found. 454 func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header { 455 hash := rawdb.ReadCanonicalHash(hc.chainDb, number) 456 if hash == (common.Hash{}) { 457 return nil 458 } 459 return hc.GetHeader(hash, number) 460 } 461 462 func (hc *HeaderChain) GetCanonicalHash(number uint64) common.Hash { 463 return rawdb.ReadCanonicalHash(hc.chainDb, number) 464 } 465 466 // CurrentHeader retrieves the current head header of the canonical chain. The 467 // header is retrieved from the HeaderChain's internal cache. 468 func (hc *HeaderChain) CurrentHeader() *types.Header { 469 return hc.currentHeader.Load().(*types.Header) 470 } 471 472 // SetCurrentHeader sets the in-memory head header marker of the canonical chan 473 // as the given header. 474 func (hc *HeaderChain) SetCurrentHeader(head *types.Header) { 475 hc.currentHeader.Store(head) 476 hc.currentHeaderHash = head.Hash() 477 headHeaderGauge.Update(head.Number.Int64()) 478 } 479 480 type ( 481 // UpdateHeadBlocksCallback is a callback function that is called by SetHead 482 // before head header is updated. 483 UpdateHeadBlocksCallback func(ethdb.KeyValueWriter, *types.Header) 484 485 // DeleteBlockContentCallback is a callback function that is called by SetHead 486 // before each header is deleted. 487 DeleteBlockContentCallback func(ethdb.KeyValueWriter, common.Hash, uint64) 488 ) 489 490 // SetHead rewinds the local chain to a new head. Everything above the new head 491 // will be deleted and the new one set. 492 func (hc *HeaderChain) SetHead(head uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) { 493 var ( 494 parentHash common.Hash 495 batch = hc.chainDb.NewBatch() 496 ) 497 for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() { 498 hash, num := hdr.Hash(), hdr.Number.Uint64() 499 500 // Rewind block chain to new head. 501 parent := hc.GetHeader(hdr.ParentHash, num-1) 502 if parent == nil { 503 parent = hc.genesisHeader 504 } 505 parentHash = hdr.ParentHash 506 // Notably, since geth has the possibility for setting the head to a low 507 // height which is even lower than ancient head. 508 // In order to ensure that the head is always no higher than the data in 509 // the database(ancient store or active store), we need to update head 510 // first then remove the relative data from the database. 511 // 512 // Update head first(head fast block, head full block) before deleting the data. 513 markerBatch := hc.chainDb.NewBatch() 514 if updateFn != nil { 515 updateFn(markerBatch, parent) 516 } 517 // Update head header then. 518 rawdb.WriteHeadHeaderHash(markerBatch, parentHash) 519 if err := markerBatch.Write(); err != nil { 520 log.Crit("Failed to update chain markers", "error", err) 521 } 522 hc.currentHeader.Store(parent) 523 hc.currentHeaderHash = parentHash 524 headHeaderGauge.Update(parent.Number.Int64()) 525 526 // Remove the relative data from the database. 527 if delFn != nil { 528 delFn(batch, hash, num) 529 } 530 // Rewind header chain to new head. 531 rawdb.DeleteHeader(batch, hash, num) 532 rawdb.DeleteTd(batch, hash, num) 533 rawdb.DeleteCanonicalHash(batch, num) 534 } 535 // Flush all accumulated deletions. 536 if err := batch.Write(); err != nil { 537 log.Crit("Failed to rewind block", "error", err) 538 } 539 // Clear out any stale content from the caches 540 hc.headerCache.Purge() 541 hc.tdCache.Purge() 542 hc.numberCache.Purge() 543 } 544 545 // SetGenesis sets a new genesis block header for the chain 546 func (hc *HeaderChain) SetGenesis(head *types.Header) { 547 hc.genesisHeader = head 548 } 549 550 // Config retrieves the header chain's chain configuration. 551 func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config } 552 553 // Engine retrieves the header chain's consensus engine. 554 func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine } 555 556 // GetBlock implements consensus.ChainReader, and returns nil for every input as 557 // a header chain does not have blocks available for retrieval. 558 func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block { 559 return nil 560 }