github.com/FusionFoundation/efsn/v4@v4.2.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/FusionFoundation/efsn/v4/common" 30 "github.com/FusionFoundation/efsn/v4/consensus" 31 "github.com/FusionFoundation/efsn/v4/consensus/datong" 32 "github.com/FusionFoundation/efsn/v4/core/rawdb" 33 "github.com/FusionFoundation/efsn/v4/core/types" 34 "github.com/FusionFoundation/efsn/v4/ethdb" 35 "github.com/FusionFoundation/efsn/v4/log" 36 "github.com/FusionFoundation/efsn/v4/params" 37 lru "github.com/hashicorp/golang-lru" 38 ) 39 40 const ( 41 headerCacheLimit = 512 42 tdCacheLimit = 1024 43 numberCacheLimit = 2048 44 ) 45 46 // HeaderChain implements the basic block header chain logic that is shared by 47 // core.BlockChain and light.LightChain. It is not usable in itself, only as 48 // a part of either structure. 49 // 50 // HeaderChain is responsible for maintaining the header chain including the 51 // header query and updating. 52 // 53 // The components maintained by headerchain includes: (1) total difficult 54 // (2) header (3) block hash -> number mapping (4) canonical number -> hash mapping 55 // and (5) head header flag. 56 // 57 // It is not thread safe either, the encapsulating chain structures should do 58 // the necessary mutex locking/unlocking. 59 type HeaderChain struct { 60 config *params.ChainConfig 61 62 chainDb ethdb.Database 63 genesisHeader *types.Header 64 65 currentHeader atomic.Value // Current head of the header chain (may be above the block chain!) 66 currentHeaderHash common.Hash // Hash of the current head of the header chain (prevent recomputing all the time) 67 68 headerCache *lru.Cache // Cache for the most recent block headers 69 tdCache *lru.Cache // Cache for the most recent block total difficulties 70 numberCache *lru.Cache // Cache for the most recent block numbers 71 72 procInterrupt func() bool 73 74 rand *mrand.Rand 75 engine consensus.Engine 76 } 77 78 // NewHeaderChain creates a new HeaderChain structure. ProcInterrupt points 79 // to the parent's interrupt semaphore. 80 func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) { 81 headerCache, _ := lru.New(headerCacheLimit) 82 tdCache, _ := lru.New(tdCacheLimit) 83 numberCache, _ := lru.New(numberCacheLimit) 84 85 // Seed a fast but crypto originating random generator 86 seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64)) 87 if err != nil { 88 return nil, err 89 } 90 91 hc := &HeaderChain{ 92 config: config, 93 chainDb: chainDb, 94 headerCache: headerCache, 95 tdCache: tdCache, 96 numberCache: numberCache, 97 procInterrupt: procInterrupt, 98 rand: mrand.New(mrand.NewSource(seed.Int64())), 99 engine: engine, 100 } 101 102 hc.genesisHeader = hc.GetHeaderByNumber(0) 103 if hc.genesisHeader == nil { 104 return nil, ErrNoGenesis 105 } 106 107 hc.currentHeader.Store(hc.genesisHeader) 108 if head := rawdb.ReadHeadBlockHash(chainDb); head != (common.Hash{}) { 109 if chead := hc.GetHeaderByHash(head); chead != nil { 110 hc.currentHeader.Store(chead) 111 } 112 } 113 hc.currentHeaderHash = hc.CurrentHeader().Hash() 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 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 if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) { 170 // If the header can be added into canonical chain, adjust the 171 // header chain markers(canonical indexes and head header flag). 172 // 173 // Note all markers should be written atomically. 174 175 // Delete any canonical number assignments above the new head 176 markerBatch := hc.chainDb.NewBatch() 177 for i := number + 1; ; i++ { 178 hash := rawdb.ReadCanonicalHash(hc.chainDb, i) 179 if hash == (common.Hash{}) { 180 break 181 } 182 rawdb.DeleteCanonicalHash(markerBatch, i) 183 } 184 185 // Overwrite any stale canonical number assignments 186 var ( 187 headHash = header.ParentHash 188 headNumber = header.Number.Uint64() - 1 189 headHeader = hc.GetHeader(headHash, headNumber) 190 ) 191 for rawdb.ReadCanonicalHash(hc.chainDb, headNumber) != headHash { 192 rawdb.WriteCanonicalHash(markerBatch, headHash, headNumber) 193 194 headHash = headHeader.ParentHash 195 headNumber = headHeader.Number.Uint64() - 1 196 headHeader = hc.GetHeader(headHash, headNumber) 197 } 198 // Extend the canonical chain with the new header 199 rawdb.WriteCanonicalHash(markerBatch, hash, number) 200 rawdb.WriteHeadHeaderHash(markerBatch, hash) 201 if err := markerBatch.Write(); err != nil { 202 log.Crit("Failed to write header markers into disk", "err", err) 203 } 204 // Last step update all in-memory head header markers 205 hc.currentHeaderHash = hash 206 hc.currentHeader.Store(types.CopyHeader(header)) 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 228 for i := 1; i < len(chain); i++ { 229 if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() { 230 // Chain broke ancestry, log a message (programming error) and skip insertion 231 log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(), 232 "parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash()) 233 234 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, 235 chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4]) 236 } 237 } 238 239 // Generate the list of seal verification requests, and start the parallel verifier 240 seals := make([]bool, len(chain)) 241 for i := 0; i < len(seals)/checkFreq; i++ { 242 index := i*checkFreq + hc.rand.Intn(checkFreq) 243 if index >= len(seals) { 244 index = len(seals) - 1 245 } 246 seals[index] = true 247 } 248 headers := make([]*types.Header, len(chain)) 249 for i, header := range chain { 250 headers[i] = header 251 } 252 seals[len(seals)-1] = true // Last should always be verified to avoid junk 253 254 // abort, results := hc.engine.VerifyHeaders(hc, chain, seals) 255 // defer close(abort) 256 257 // Iterate over the headers and ensure they all check out 258 for i, header := range chain { 259 // If the chain is terminating, stop processing blocks 260 if hc.procInterrupt() { 261 log.Debug("Premature abort during headers verification") 262 return 0, errors.New("aborted") 263 } 264 // If the header is a banned one, straight out abort 265 if BadHashes[header.Hash()] { 266 return i, ErrBannedHash 267 } 268 // Otherwise wait for headers checks and ensure they pass 269 datong.SetHeaders(headers[:i]) 270 err := hc.engine.VerifyHeader(hc, headers[i], seals[i]) 271 datong.SetHeaders(nil) 272 if err != nil { 273 return i, err 274 } 275 } 276 277 if i, err := datong.CheckPointsInHeaderChain(hc.config.ChainID, chain); err != nil { 278 return i, err 279 } 280 281 return 0, nil 282 } 283 284 // InsertHeaderChain attempts to insert the given header chain in to the local 285 // chain, possibly creating a reorg. If an error is returned, it will return the 286 // index number of the failing header as well an error describing what went wrong. 287 // 288 // The verify parameter can be used to fine tune whether nonce verification 289 // should be done or not. The reason behind the optional check is because some 290 // of the header retrieval mechanisms already need to verfy nonces, as well as 291 // because nonces can be verified sparsely, not needing to check each. 292 func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) { 293 if i, err := datong.CheckPointsInHeaderChain(hc.config.ChainID, chain); err != nil { 294 return i, err 295 } 296 // Collect some import statistics to report on 297 stats := struct{ processed, ignored int }{} 298 // All headers passed verification, import them into the database 299 for i, header := range chain { 300 // Short circuit insertion if shutting down 301 if hc.procInterrupt() { 302 log.Debug("Premature abort during headers import") 303 return i, errors.New("aborted") 304 } 305 // If the header's already known, skip it, otherwise store 306 if hc.HasHeader(header.Hash(), header.Number.Uint64()) { 307 stats.ignored++ 308 continue 309 } 310 if err := writeHeader(header); err != nil { 311 return i, err 312 } 313 stats.processed++ 314 } 315 // Report some public statistics so the user has a clue what's going on 316 last := chain[len(chain)-1] 317 318 context := []interface{}{ 319 "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)), 320 "number", last.Number, "hash", last.Hash(), 321 } 322 if timestamp := time.Unix(int64(last.Time), 0); time.Since(timestamp) > time.Minute { 323 context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...) 324 } 325 if stats.ignored > 0 { 326 context = append(context, []interface{}{"ignored", stats.ignored}...) 327 } 328 log.Info("Imported new block headers", context...) 329 330 return 0, nil 331 } 332 333 // GetBlockHashesFromHash retrieves a number of block hashes starting at a given 334 // hash, fetching towards the genesis block. 335 func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { 336 // Get the origin header from which to fetch 337 header := hc.GetHeaderByHash(hash) 338 if header == nil { 339 return nil 340 } 341 // Iterate the headers until enough is collected or the genesis reached 342 chain := make([]common.Hash, 0, max) 343 for i := uint64(0); i < max; i++ { 344 next := header.ParentHash 345 if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil { 346 break 347 } 348 chain = append(chain, next) 349 if header.Number.Sign() == 0 { 350 break 351 } 352 } 353 return chain 354 } 355 356 // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or 357 // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the 358 // number of blocks to be individually checked before we reach the canonical chain. 359 // 360 // Note: ancestor == 0 returns the same block, 1 returns its parent and so on. 361 func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) { 362 if ancestor > number { 363 return common.Hash{}, 0 364 } 365 if ancestor == 1 { 366 // in this case it is cheaper to just read the header 367 if header := hc.GetHeader(hash, number); header != nil { 368 return header.ParentHash, number - 1 369 } else { 370 return common.Hash{}, 0 371 } 372 } 373 for ancestor != 0 { 374 if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash { 375 number -= ancestor 376 return rawdb.ReadCanonicalHash(hc.chainDb, number), number 377 } 378 if *maxNonCanonical == 0 { 379 return common.Hash{}, 0 380 } 381 *maxNonCanonical-- 382 ancestor-- 383 header := hc.GetHeader(hash, number) 384 if header == nil { 385 return common.Hash{}, 0 386 } 387 hash = header.ParentHash 388 number-- 389 } 390 return hash, number 391 } 392 393 // GetTd retrieves a block's total difficulty in the canonical chain from the 394 // database by hash and number, caching it if found. 395 func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int { 396 // Short circuit if the td's already in the cache, retrieve otherwise 397 if cached, ok := hc.tdCache.Get(hash); ok { 398 return cached.(*big.Int) 399 } 400 td := rawdb.ReadTd(hc.chainDb, hash, number) 401 if td == nil { 402 return nil 403 } 404 // Cache the found body for next time and return 405 hc.tdCache.Add(hash, td) 406 return td 407 } 408 409 // GetTdByHash retrieves a block's total difficulty in the canonical chain from the 410 // database by hash, caching it if found. 411 func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int { 412 number := hc.GetBlockNumber(hash) 413 if number == nil { 414 return nil 415 } 416 return hc.GetTd(hash, *number) 417 } 418 419 // GetHeader retrieves a block header from the database by hash and number, 420 // caching it if found. 421 func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header { 422 // Short circuit if the header's already in the cache, retrieve otherwise 423 if header, ok := hc.headerCache.Get(hash); ok { 424 return header.(*types.Header) 425 } 426 header := rawdb.ReadHeader(hc.chainDb, hash, number) 427 if header == nil { 428 return nil 429 } 430 // Cache the found header for next time and return 431 hc.headerCache.Add(hash, header) 432 return header 433 } 434 435 // GetHeaderByHash retrieves a block header from the database by hash, caching it if 436 // found. 437 func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header { 438 number := hc.GetBlockNumber(hash) 439 if number == nil { 440 return nil 441 } 442 return hc.GetHeader(hash, *number) 443 } 444 445 // HasHeader checks if a block header is present in the database or not. 446 // In theory, if header is present in the database, all relative components 447 // like td and hash->number should be present too. 448 func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool { 449 if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) { 450 return true 451 } 452 return rawdb.HasHeader(hc.chainDb, hash, number) 453 } 454 455 // GetHeaderByNumber retrieves a block header from the database by number, 456 // caching it (associated with its hash) if found. 457 func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header { 458 hash := rawdb.ReadCanonicalHash(hc.chainDb, number) 459 if hash == (common.Hash{}) { 460 return nil 461 } 462 return hc.GetHeader(hash, number) 463 } 464 465 func (hc *HeaderChain) GetCanonicalHash(number uint64) common.Hash { 466 return rawdb.ReadCanonicalHash(hc.chainDb, number) 467 } 468 469 // CurrentHeader retrieves the current head header of the canonical chain. The 470 // header is retrieved from the HeaderChain's internal cache. 471 func (hc *HeaderChain) CurrentHeader() *types.Header { 472 return hc.currentHeader.Load().(*types.Header) 473 } 474 475 // SetCurrentHeader sets the in-memory head header marker of the canonical chan 476 // as the given header. 477 func (hc *HeaderChain) SetCurrentHeader(head *types.Header) { 478 hc.currentHeader.Store(head) 479 hc.currentHeaderHash = head.Hash() 480 } 481 482 // DeleteCallback is a callback function that is called by SetHead before 483 // each header is deleted. 484 type DeleteCallback func(ethdb.KeyValueWriter, common.Hash, uint64) 485 486 // SetHead rewinds the local chain to a new head. Everything above the new head 487 // will be deleted and the new one set. 488 func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback) { 489 var ( 490 parentHash common.Hash 491 batch = hc.chainDb.NewBatch() 492 origin = true 493 ) 494 for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() { 495 num := hdr.Number.Uint64() 496 497 // Rewind block chain to new head. 498 parent := hc.GetHeader(hdr.ParentHash, num-1) 499 if parent == nil { 500 parent = hc.genesisHeader 501 } 502 parentHash = parent.Hash() 503 504 // Notably, since geth has the possibility for setting the head to a low 505 // height which is even lower than ancient head. 506 // In order to ensure that the head is always no higher than the data in 507 // the database (ancient store or active store), we need to update head 508 // first then remove the relative data from the database. 509 // 510 // Update head first(head fast block, head full block) before deleting the data. 511 markerBatch := hc.chainDb.NewBatch() 512 //if updateFn != nil { 513 // newHead, force := updateFn(markerBatch, parent) 514 // if force && newHead < head { 515 // log.Warn("Force rewinding till ancient limit", "head", newHead) 516 // head = newHead 517 // } 518 //} 519 // Update head header then. 520 rawdb.WriteHeadHeaderHash(markerBatch, parentHash) 521 if err := markerBatch.Write(); err != nil { 522 log.Crit("Failed to update chain markers", "error", err) 523 } 524 hc.currentHeader.Store(parent) 525 hc.currentHeaderHash = parentHash 526 headHeaderGauge.Update(parent.Number.Int64()) 527 528 // If this is the first iteration, wipe any leftover data upwards too so 529 // we don't end up with dangling daps in the database 530 var nums []uint64 531 if origin { 532 for n := num + 1; len(rawdb.ReadAllHashes(hc.chainDb, n)) > 0; n++ { 533 nums = append([]uint64{n}, nums...) // suboptimal, but we don't really expect this path 534 } 535 origin = false 536 } 537 nums = append(nums, num) 538 539 // Remove the related data from the database on all sidechains 540 for _, num := range nums { 541 // Gather all the side fork hashes 542 hashes := rawdb.ReadAllHashes(hc.chainDb, num) 543 if len(hashes) == 0 { 544 // No hashes in the database whatsoever, probably frozen already 545 hashes = append(hashes, hdr.Hash()) 546 } 547 for _, hash := range hashes { 548 if delFn != nil { 549 delFn(batch, hash, num) 550 } 551 rawdb.DeleteHeader(batch, hash, num) 552 rawdb.DeleteTd(batch, hash, num) 553 } 554 rawdb.DeleteCanonicalHash(batch, num) 555 } 556 } 557 // Flush all accumulated deletions. 558 if err := batch.Write(); err != nil { 559 log.Crit("Failed to rewind block", "error", err) 560 } 561 // Clear out any stale content from the caches 562 hc.headerCache.Purge() 563 hc.tdCache.Purge() 564 hc.numberCache.Purge() 565 } 566 567 // SetGenesis sets a new genesis block header for the chain 568 func (hc *HeaderChain) SetGenesis(head *types.Header) { 569 hc.genesisHeader = head 570 } 571 572 // Config retrieves the header chain's chain configuration. 573 func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config } 574 575 // Engine retrieves the header chain's consensus engine. 576 func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine } 577 578 // GetBlock implements consensus.ChainReader, and returns nil for every input as 579 // a header chain does not have blocks available for retrieval. 580 func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block { 581 return nil 582 }