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