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