github.com/luckypickle/go-ethereum-vet@v1.14.2/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/hashicorp/golang-lru" 30 "github.com/luckypickle/go-ethereum-vet/common" 31 "github.com/luckypickle/go-ethereum-vet/consensus" 32 "github.com/luckypickle/go-ethereum-vet/core/rawdb" 33 "github.com/luckypickle/go-ethereum-vet/core/types" 34 "github.com/luckypickle/go-ethereum-vet/ethdb" 35 "github.com/luckypickle/go-ethereum-vet/log" 36 "github.com/luckypickle/go-ethereum-vet/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 // 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 // 71 // getValidator should return the parent's validator 72 // procInterrupt points to the parent's interrupt semaphore 73 // wg points to the parent's shutdown wait group 74 func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) { 75 headerCache, _ := lru.New(headerCacheLimit) 76 tdCache, _ := lru.New(tdCacheLimit) 77 numberCache, _ := lru.New(numberCacheLimit) 78 79 // Seed a fast but crypto originating random generator 80 seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64)) 81 if err != nil { 82 return nil, err 83 } 84 85 hc := &HeaderChain{ 86 config: config, 87 chainDb: chainDb, 88 headerCache: headerCache, 89 tdCache: tdCache, 90 numberCache: numberCache, 91 procInterrupt: procInterrupt, 92 rand: mrand.New(mrand.NewSource(seed.Int64())), 93 engine: engine, 94 } 95 96 hc.genesisHeader = hc.GetHeaderByNumber(0) 97 if hc.genesisHeader == nil { 98 return nil, ErrNoGenesis 99 } 100 101 hc.currentHeader.Store(hc.genesisHeader) 102 if head := rawdb.ReadHeadBlockHash(chainDb); head != (common.Hash{}) { 103 if chead := hc.GetHeaderByHash(head); chead != nil { 104 hc.currentHeader.Store(chead) 105 } 106 } 107 hc.currentHeaderHash = hc.CurrentHeader().Hash() 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 190 status = CanonStatTy 191 } else { 192 status = SideStatTy 193 } 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 for i := 0; i < len(seals)/checkFreq; i++ { 224 index := i*checkFreq + hc.rand.Intn(checkFreq) 225 if index >= len(seals) { 226 index = len(seals) - 1 227 } 228 seals[index] = true 229 } 230 seals[len(seals)-1] = true // Last should always be verified to avoid junk 231 232 abort, results := hc.engine.VerifyHeaders(hc, chain, seals) 233 defer close(abort) 234 235 // Iterate over the headers and ensure they all check out 236 for i, header := range chain { 237 // If the chain is terminating, stop processing blocks 238 if hc.procInterrupt() { 239 log.Debug("Premature abort during headers verification") 240 return 0, errors.New("aborted") 241 } 242 // If the header is a banned one, straight out abort 243 if BadHashes[header.Hash()] { 244 return i, ErrBlacklistedHash 245 } 246 // Otherwise wait for headers checks and ensure they pass 247 if err := <-results; err != nil { 248 return i, err 249 } 250 } 251 252 return 0, nil 253 } 254 255 // InsertHeaderChain attempts to insert the given header chain in to the local 256 // chain, possibly creating a reorg. If an error is returned, it will return the 257 // index number of the failing header as well an error describing what went wrong. 258 // 259 // The verify parameter can be used to fine tune whether nonce verification 260 // should be done or not. The reason behind the optional check is because some 261 // of the header retrieval mechanisms already need to verfy nonces, as well as 262 // because nonces can be verified sparsely, not needing to check each. 263 func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) { 264 // Collect some import statistics to report on 265 stats := struct{ processed, ignored int }{} 266 // All headers passed verification, import them into the database 267 for i, header := range chain { 268 // Short circuit insertion if shutting down 269 if hc.procInterrupt() { 270 log.Debug("Premature abort during headers import") 271 return i, errors.New("aborted") 272 } 273 // If the header's already known, skip it, otherwise store 274 if hc.HasHeader(header.Hash(), header.Number.Uint64()) { 275 stats.ignored++ 276 continue 277 } 278 if err := writeHeader(header); err != nil { 279 return i, err 280 } 281 stats.processed++ 282 } 283 // Report some public statistics so the user has a clue what's going on 284 last := chain[len(chain)-1] 285 log.Info("Imported new block headers", "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)), 286 "number", last.Number, "hash", last.Hash(), "ignored", stats.ignored) 287 288 return 0, nil 289 } 290 291 // GetBlockHashesFromHash retrieves a number of block hashes starting at a given 292 // hash, fetching towards the genesis block. 293 func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { 294 // Get the origin header from which to fetch 295 header := hc.GetHeaderByHash(hash) 296 if header == nil { 297 return nil 298 } 299 // Iterate the headers until enough is collected or the genesis reached 300 chain := make([]common.Hash, 0, max) 301 for i := uint64(0); i < max; i++ { 302 next := header.ParentHash 303 if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil { 304 break 305 } 306 chain = append(chain, next) 307 if header.Number.Sign() == 0 { 308 break 309 } 310 } 311 return chain 312 } 313 314 // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or 315 // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the 316 // number of blocks to be individually checked before we reach the canonical chain. 317 // 318 // Note: ancestor == 0 returns the same block, 1 returns its parent and so on. 319 func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) { 320 if ancestor > number { 321 return common.Hash{}, 0 322 } 323 if ancestor == 1 { 324 // in this case it is cheaper to just read the header 325 if header := hc.GetHeader(hash, number); header != nil { 326 return header.ParentHash, number - 1 327 } else { 328 return common.Hash{}, 0 329 } 330 } 331 for ancestor != 0 { 332 if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash { 333 number -= ancestor 334 return rawdb.ReadCanonicalHash(hc.chainDb, number), number 335 } 336 if *maxNonCanonical == 0 { 337 return common.Hash{}, 0 338 } 339 *maxNonCanonical-- 340 ancestor-- 341 header := hc.GetHeader(hash, number) 342 if header == nil { 343 return common.Hash{}, 0 344 } 345 hash = header.ParentHash 346 number-- 347 } 348 return hash, number 349 } 350 351 // GetTd retrieves a block's total difficulty in the canonical chain from the 352 // database by hash and number, caching it if found. 353 func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int { 354 // Short circuit if the td's already in the cache, retrieve otherwise 355 if cached, ok := hc.tdCache.Get(hash); ok { 356 return cached.(*big.Int) 357 } 358 td := rawdb.ReadTd(hc.chainDb, hash, number) 359 if td == nil { 360 return nil 361 } 362 // Cache the found body for next time and return 363 hc.tdCache.Add(hash, td) 364 return td 365 } 366 367 // GetTdByHash retrieves a block's total difficulty in the canonical chain from the 368 // database by hash, caching it if found. 369 func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int { 370 number := hc.GetBlockNumber(hash) 371 if number == nil { 372 return nil 373 } 374 return hc.GetTd(hash, *number) 375 } 376 377 // WriteTd stores a block's total difficulty into the database, also caching it 378 // along the way. 379 func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) error { 380 rawdb.WriteTd(hc.chainDb, hash, number, td) 381 hc.tdCache.Add(hash, new(big.Int).Set(td)) 382 return nil 383 } 384 385 // GetHeader retrieves a block header from the database by hash and number, 386 // caching it if found. 387 func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header { 388 // Short circuit if the header's already in the cache, retrieve otherwise 389 if header, ok := hc.headerCache.Get(hash); ok { 390 return header.(*types.Header) 391 } 392 header := rawdb.ReadHeader(hc.chainDb, hash, number) 393 if header == nil { 394 return nil 395 } 396 // Cache the found header for next time and return 397 hc.headerCache.Add(hash, header) 398 return header 399 } 400 401 // GetHeaderByHash retrieves a block header from the database by hash, caching it if 402 // found. 403 func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header { 404 number := hc.GetBlockNumber(hash) 405 if number == nil { 406 return nil 407 } 408 return hc.GetHeader(hash, *number) 409 } 410 411 // HasHeader checks if a block header is present in the database or not. 412 func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool { 413 if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) { 414 return true 415 } 416 return rawdb.HasHeader(hc.chainDb, hash, number) 417 } 418 419 // GetHeaderByNumber retrieves a block header from the database by number, 420 // caching it (associated with its hash) if found. 421 func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header { 422 hash := rawdb.ReadCanonicalHash(hc.chainDb, number) 423 if hash == (common.Hash{}) { 424 return nil 425 } 426 return hc.GetHeader(hash, number) 427 } 428 429 // CurrentHeader retrieves the current head header of the canonical chain. The 430 // header is retrieved from the HeaderChain's internal cache. 431 func (hc *HeaderChain) CurrentHeader() *types.Header { 432 return hc.currentHeader.Load().(*types.Header) 433 } 434 435 // SetCurrentHeader sets the current head header of the canonical chain. 436 func (hc *HeaderChain) SetCurrentHeader(head *types.Header) { 437 rawdb.WriteHeadHeaderHash(hc.chainDb, head.Hash()) 438 439 hc.currentHeader.Store(head) 440 hc.currentHeaderHash = head.Hash() 441 } 442 443 // DeleteCallback is a callback function that is called by SetHead before 444 // each header is deleted. 445 type DeleteCallback func(rawdb.DatabaseDeleter, common.Hash, uint64) 446 447 // SetHead rewinds the local chain to a new head. Everything above the new head 448 // will be deleted and the new one set. 449 func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback) { 450 height := uint64(0) 451 452 if hdr := hc.CurrentHeader(); hdr != nil { 453 height = hdr.Number.Uint64() 454 } 455 batch := hc.chainDb.NewBatch() 456 for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() { 457 hash := hdr.Hash() 458 num := hdr.Number.Uint64() 459 if delFn != nil { 460 delFn(batch, hash, num) 461 } 462 rawdb.DeleteHeader(batch, hash, num) 463 rawdb.DeleteTd(batch, hash, num) 464 465 hc.currentHeader.Store(hc.GetHeader(hdr.ParentHash, hdr.Number.Uint64()-1)) 466 } 467 // Roll back the canonical chain numbering 468 for i := height; i > head; i-- { 469 rawdb.DeleteCanonicalHash(batch, i) 470 } 471 batch.Write() 472 473 // Clear out any stale content from the caches 474 hc.headerCache.Purge() 475 hc.tdCache.Purge() 476 hc.numberCache.Purge() 477 478 if hc.CurrentHeader() == nil { 479 hc.currentHeader.Store(hc.genesisHeader) 480 } 481 hc.currentHeaderHash = hc.CurrentHeader().Hash() 482 483 rawdb.WriteHeadHeaderHash(hc.chainDb, hc.currentHeaderHash) 484 } 485 486 // SetGenesis sets a new genesis block header for the chain 487 func (hc *HeaderChain) SetGenesis(head *types.Header) { 488 hc.genesisHeader = head 489 } 490 491 // Config retrieves the header chain's chain configuration. 492 func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config } 493 494 // Engine retrieves the header chain's consensus engine. 495 func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine } 496 497 // GetBlock implements consensus.ChainReader, and returns nil for every input as 498 // a header chain does not have blocks available for retrieval. 499 func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block { 500 return nil 501 }