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