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