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