github.com/core-coin/go-core/v2@v2.1.9/light/lightchain.go (about) 1 // Copyright 2016 by the Authors 2 // This file is part of the go-core library. 3 // 4 // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package light implements on-demand retrieval capable state and chain objects 18 // for the Core Light Client. 19 package light 20 21 import ( 22 "context" 23 "errors" 24 "math/big" 25 "sync" 26 "sync/atomic" 27 "time" 28 29 lru "github.com/hashicorp/golang-lru" 30 31 "github.com/core-coin/go-core/v2/xcbdb" 32 33 "github.com/core-coin/go-core/v2/common" 34 "github.com/core-coin/go-core/v2/consensus" 35 "github.com/core-coin/go-core/v2/core" 36 "github.com/core-coin/go-core/v2/core/rawdb" 37 "github.com/core-coin/go-core/v2/core/state" 38 "github.com/core-coin/go-core/v2/core/types" 39 "github.com/core-coin/go-core/v2/event" 40 "github.com/core-coin/go-core/v2/log" 41 "github.com/core-coin/go-core/v2/params" 42 "github.com/core-coin/go-core/v2/rlp" 43 ) 44 45 var ( 46 bodyCacheLimit = 256 47 blockCacheLimit = 256 48 ) 49 50 // LightChain represents a canonical chain that by default only handles block 51 // headers, downloading block bodies and receipts on demand through an ODR 52 // interface. It only does header validation during chain insertion. 53 type LightChain struct { 54 hc *core.HeaderChain 55 indexerConfig *IndexerConfig 56 chainDb xcbdb.Database 57 engine consensus.Engine 58 odr OdrBackend 59 chainFeed event.Feed 60 chainSideFeed event.Feed 61 chainHeadFeed event.Feed 62 scope event.SubscriptionScope 63 genesisBlock *types.Block 64 65 bodyCache *lru.Cache // Cache for the most recent block bodies 66 bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format 67 blockCache *lru.Cache // Cache for the most recent entire blocks 68 69 chainmu sync.RWMutex // protects header inserts 70 quit chan struct{} 71 wg sync.WaitGroup 72 73 // Atomic boolean switches: 74 running int32 // whether LightChain is running or stopped 75 procInterrupt int32 // interrupts chain insert 76 disableCheckFreq int32 // disables header verification 77 } 78 79 // NewLightChain returns a fully initialised light chain using information 80 // available in the database. It initialises the default Core header 81 // validator. 82 func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus.Engine, checkpoint *params.TrustedCheckpoint) (*LightChain, error) { 83 bodyCache, _ := lru.New(bodyCacheLimit) 84 bodyRLPCache, _ := lru.New(bodyCacheLimit) 85 blockCache, _ := lru.New(blockCacheLimit) 86 87 bc := &LightChain{ 88 chainDb: odr.Database(), 89 indexerConfig: odr.IndexerConfig(), 90 odr: odr, 91 quit: make(chan struct{}), 92 bodyCache: bodyCache, 93 bodyRLPCache: bodyRLPCache, 94 blockCache: blockCache, 95 engine: engine, 96 } 97 var err error 98 bc.hc, err = core.NewHeaderChain(odr.Database(), config, bc.engine, bc.getProcInterrupt) 99 if err != nil { 100 return nil, err 101 } 102 bc.genesisBlock, _ = bc.GetBlockByNumber(NoOdr, 0) 103 if bc.genesisBlock == nil { 104 return nil, core.ErrNoGenesis 105 } 106 if checkpoint != nil { 107 bc.AddTrustedCheckpoint(checkpoint) 108 } 109 if err := bc.loadLastState(); err != nil { 110 return nil, err 111 } 112 // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain 113 for hash := range core.BadHashes { 114 if header := bc.GetHeaderByHash(hash); header != nil { 115 log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash) 116 bc.SetHead(header.Number.Uint64() - 1) 117 log.Info("Chain rewind was successful, resuming normal operation") 118 } 119 } 120 return bc, nil 121 } 122 123 // AddTrustedCheckpoint adds a trusted checkpoint to the blockchain 124 func (lc *LightChain) AddTrustedCheckpoint(cp *params.TrustedCheckpoint) { 125 if lc.odr.ChtIndexer() != nil { 126 StoreChtRoot(lc.chainDb, cp.SectionIndex, cp.SectionHead, cp.CHTRoot) 127 lc.odr.ChtIndexer().AddCheckpoint(cp.SectionIndex, cp.SectionHead) 128 } 129 if lc.odr.BloomTrieIndexer() != nil { 130 StoreBloomTrieRoot(lc.chainDb, cp.SectionIndex, cp.SectionHead, cp.BloomRoot) 131 lc.odr.BloomTrieIndexer().AddCheckpoint(cp.SectionIndex, cp.SectionHead) 132 } 133 if lc.odr.BloomIndexer() != nil { 134 lc.odr.BloomIndexer().AddCheckpoint(cp.SectionIndex, cp.SectionHead) 135 } 136 log.Info("Added trusted checkpoint", "block", (cp.SectionIndex+1)*lc.indexerConfig.ChtSize-1, "hash", cp.SectionHead) 137 } 138 139 func (lc *LightChain) getProcInterrupt() bool { 140 return atomic.LoadInt32(&lc.procInterrupt) == 1 141 } 142 143 // Odr returns the ODR backend of the chain 144 func (lc *LightChain) Odr() OdrBackend { 145 return lc.odr 146 } 147 148 // HeaderChain returns the underlying header chain. 149 func (lc *LightChain) HeaderChain() *core.HeaderChain { 150 return lc.hc 151 } 152 153 // loadLastState loads the last known chain state from the database. This method 154 // assumes that the chain manager mutex is held. 155 func (lc *LightChain) loadLastState() error { 156 if head := rawdb.ReadHeadHeaderHash(lc.chainDb); head == (common.Hash{}) { 157 // Corrupt or empty database, init from scratch 158 lc.Reset() 159 } else { 160 header := lc.GetHeaderByHash(head) 161 if header == nil { 162 // Corrupt or empty database, init from scratch 163 lc.Reset() 164 } else { 165 lc.hc.SetCurrentHeader(header) 166 } 167 } 168 // Issue a status log and return 169 header := lc.hc.CurrentHeader() 170 headerTd := lc.GetTd(header.Hash(), header.Number.Uint64()) 171 log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(header.Time), 0))) 172 return nil 173 } 174 175 // SetHead rewinds the local chain to a new head. Everything above the new 176 // head will be deleted and the new one set. 177 func (lc *LightChain) SetHead(head uint64) error { 178 lc.chainmu.Lock() 179 defer lc.chainmu.Unlock() 180 181 lc.hc.SetHead(head, nil, nil) 182 return lc.loadLastState() 183 } 184 185 // EnergyLimit returns the energy limit of the current HEAD block. 186 func (lc *LightChain) EnergyLimit() uint64 { 187 return lc.hc.CurrentHeader().EnergyLimit 188 } 189 190 // Reset purges the entire blockchain, restoring it to its genesis state. 191 func (lc *LightChain) Reset() { 192 lc.ResetWithGenesisBlock(lc.genesisBlock) 193 } 194 195 // ResetWithGenesisBlock purges the entire blockchain, restoring it to the 196 // specified genesis state. 197 func (lc *LightChain) ResetWithGenesisBlock(genesis *types.Block) { 198 // Dump the entire block chain and purge the caches 199 lc.SetHead(0) 200 201 lc.chainmu.Lock() 202 defer lc.chainmu.Unlock() 203 204 // Prepare the genesis block and reinitialise the chain 205 batch := lc.chainDb.NewBatch() 206 rawdb.WriteTd(batch, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()) 207 rawdb.WriteBlock(batch, genesis) 208 rawdb.WriteHeadHeaderHash(batch, genesis.Hash()) 209 if err := batch.Write(); err != nil { 210 log.Crit("Failed to reset genesis block", "err", err) 211 } 212 lc.genesisBlock = genesis 213 lc.hc.SetGenesis(lc.genesisBlock.Header()) 214 lc.hc.SetCurrentHeader(lc.genesisBlock.Header()) 215 } 216 217 // Accessors 218 219 // Engine retrieves the light chain's consensus engine. 220 func (lc *LightChain) Engine() consensus.Engine { return lc.engine } 221 222 // Genesis returns the genesis block 223 func (lc *LightChain) Genesis() *types.Block { 224 return lc.genesisBlock 225 } 226 227 func (lc *LightChain) StateCache() state.Database { 228 panic("not implemented") 229 } 230 231 // GetBody retrieves a block body (transactions and uncles) from the database 232 // or ODR service by hash, caching it if found. 233 func (lc *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) { 234 // Short circuit if the body's already in the cache, retrieve otherwise 235 if cached, ok := lc.bodyCache.Get(hash); ok { 236 body := cached.(*types.Body) 237 return body, nil 238 } 239 number := lc.hc.GetBlockNumber(hash) 240 if number == nil { 241 return nil, errors.New("unknown block") 242 } 243 body, err := GetBody(ctx, lc.odr, hash, *number) 244 if err != nil { 245 return nil, err 246 } 247 // Cache the found body for next time and return 248 lc.bodyCache.Add(hash, body) 249 return body, nil 250 } 251 252 // GetBodyRLP retrieves a block body in RLP encoding from the database or 253 // ODR service by hash, caching it if found. 254 func (lc *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) { 255 // Short circuit if the body's already in the cache, retrieve otherwise 256 if cached, ok := lc.bodyRLPCache.Get(hash); ok { 257 return cached.(rlp.RawValue), nil 258 } 259 number := lc.hc.GetBlockNumber(hash) 260 if number == nil { 261 return nil, errors.New("unknown block") 262 } 263 body, err := GetBodyRLP(ctx, lc.odr, hash, *number) 264 if err != nil { 265 return nil, err 266 } 267 // Cache the found body for next time and return 268 lc.bodyRLPCache.Add(hash, body) 269 return body, nil 270 } 271 272 // HasBlock checks if a block is fully present in the database or not, caching 273 // it if present. 274 func (lc *LightChain) HasBlock(hash common.Hash, number uint64) bool { 275 blk, _ := lc.GetBlock(NoOdr, hash, number) 276 return blk != nil 277 } 278 279 // GetBlock retrieves a block from the database or ODR service by hash and number, 280 // caching it if found. 281 func (lc *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) { 282 // Short circuit if the block's already in the cache, retrieve otherwise 283 if block, ok := lc.blockCache.Get(hash); ok { 284 return block.(*types.Block), nil 285 } 286 block, err := GetBlock(ctx, lc.odr, hash, number) 287 if err != nil { 288 return nil, err 289 } 290 // Cache the found block for next time and return 291 lc.blockCache.Add(block.Hash(), block) 292 return block, nil 293 } 294 295 // GetBlockByHash retrieves a block from the database or ODR service by hash, 296 // caching it if found. 297 func (lc *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { 298 number := lc.hc.GetBlockNumber(hash) 299 if number == nil { 300 return nil, errors.New("unknown block") 301 } 302 return lc.GetBlock(ctx, hash, *number) 303 } 304 305 // GetBlockByNumber retrieves a block from the database or ODR service by 306 // number, caching it (associated with its hash) if found. 307 func (lc *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) { 308 hash, err := GetCanonicalHash(ctx, lc.odr, number) 309 if hash == (common.Hash{}) || err != nil { 310 return nil, err 311 } 312 return lc.GetBlock(ctx, hash, number) 313 } 314 315 // Stop stops the blockchain service. If any imports are currently in progress 316 // it will abort them using the procInterrupt. 317 func (lc *LightChain) Stop() { 318 if !atomic.CompareAndSwapInt32(&lc.running, 0, 1) { 319 return 320 } 321 close(lc.quit) 322 lc.StopInsert() 323 lc.wg.Wait() 324 log.Info("Blockchain stopped") 325 } 326 327 // StopInsert interrupts all insertion methods, causing them to return 328 // errInsertionInterrupted as soon as possible. Insertion is permanently disabled after 329 // calling this method. 330 func (lc *LightChain) StopInsert() { 331 atomic.StoreInt32(&lc.procInterrupt, 1) 332 } 333 334 // Rollback is designed to remove a chain of links from the database that aren't 335 // certain enough to be valid. 336 func (lc *LightChain) Rollback(chain []common.Hash) { 337 lc.chainmu.Lock() 338 defer lc.chainmu.Unlock() 339 340 batch := lc.chainDb.NewBatch() 341 for i := len(chain) - 1; i >= 0; i-- { 342 hash := chain[i] 343 344 // Degrade the chain markers if they are explicitly reverted. 345 // In theory we should update all in-memory markers in the 346 // last step, however the direction of rollback is from high 347 // to low, so it's safe the update in-memory markers directly. 348 if head := lc.hc.CurrentHeader(); head.Hash() == hash { 349 rawdb.WriteHeadHeaderHash(batch, head.ParentHash) 350 lc.hc.SetCurrentHeader(lc.GetHeader(head.ParentHash, head.Number.Uint64()-1)) 351 } 352 } 353 if err := batch.Write(); err != nil { 354 log.Crit("Failed to rollback light chain", "error", err) 355 } 356 } 357 358 // postChainEvents iterates over the events generated by a chain insertion and 359 // posts them into the event feed. 360 func (lc *LightChain) postChainEvents(events []interface{}) { 361 for _, event := range events { 362 switch ev := event.(type) { 363 case core.ChainEvent: 364 if lc.CurrentHeader().Hash() == ev.Hash { 365 lc.chainHeadFeed.Send(core.ChainHeadEvent{Block: ev.Block}) 366 } 367 lc.chainFeed.Send(ev) 368 case core.ChainSideEvent: 369 lc.chainSideFeed.Send(ev) 370 } 371 } 372 } 373 374 // InsertHeaderChain attempts to insert the given header chain in to the local 375 // chain, possibly creating a reorg. If an error is returned, it will return the 376 // index number of the failing header as well an error describing what went wrong. 377 // 378 // The verify parameter can be used to fine tune whether nonce verification 379 // should be done or not. The reason behind the optional check is because some 380 // of the header retrieval mechanisms already need to verfy nonces, as well as 381 // because nonces can be verified sparsely, not needing to check each. 382 // 383 // In the case of a light chain, InsertHeaderChain also creates and posts light 384 // chain events when necessary. 385 func (lc *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) { 386 if atomic.LoadInt32(&lc.disableCheckFreq) == 1 { 387 checkFreq = 0 388 } 389 start := time.Now() 390 if i, err := lc.hc.ValidateHeaderChain(chain, checkFreq); err != nil { 391 return i, err 392 } 393 394 // Make sure only one thread manipulates the chain at once 395 lc.chainmu.Lock() 396 defer lc.chainmu.Unlock() 397 398 lc.wg.Add(1) 399 defer lc.wg.Done() 400 401 status, err := lc.hc.InsertHeaderChain(chain, start) 402 if err != nil || len(chain) == 0 { 403 return 0, err 404 } 405 406 // Create chain event for the new head block of this insertion. 407 var ( 408 events = make([]interface{}, 0, 1) 409 lastHeader = chain[len(chain)-1] 410 block = types.NewBlockWithHeader(lastHeader) 411 ) 412 switch status { 413 case core.CanonStatTy: 414 events = append(events, core.ChainEvent{Block: block, Hash: block.Hash()}) 415 case core.SideStatTy: 416 events = append(events, core.ChainSideEvent{Block: block}) 417 } 418 lc.postChainEvents(events) 419 420 return 0, err 421 } 422 423 // CurrentHeader retrieves the current head header of the canonical chain. The 424 // header is retrieved from the HeaderChain's internal cache. 425 func (lc *LightChain) CurrentHeader() *types.Header { 426 return lc.hc.CurrentHeader() 427 } 428 429 // GetTd retrieves a block's total difficulty in the canonical chain from the 430 // database by hash and number, caching it if found. 431 func (lc *LightChain) GetTd(hash common.Hash, number uint64) *big.Int { 432 return lc.hc.GetTd(hash, number) 433 } 434 435 // GetTdByHash retrieves a block's total difficulty in the canonical chain from the 436 // database by hash, caching it if found. 437 func (lc *LightChain) GetTdByHash(hash common.Hash) *big.Int { 438 return lc.hc.GetTdByHash(hash) 439 } 440 441 // GetHeaderByNumberOdr retrieves the total difficult from the database or 442 // network by hash and number, caching it (associated with its hash) if found. 443 func (lc *LightChain) GetTdOdr(ctx context.Context, hash common.Hash, number uint64) *big.Int { 444 td := lc.GetTd(hash, number) 445 if td != nil { 446 return td 447 } 448 td, _ = GetTd(ctx, lc.odr, hash, number) 449 return td 450 } 451 452 // GetHeader retrieves a block header from the database by hash and number, 453 // caching it if found. 454 func (lc *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header { 455 return lc.hc.GetHeader(hash, number) 456 } 457 458 // GetHeaderByHash retrieves a block header from the database by hash, caching it if 459 // found. 460 func (lc *LightChain) GetHeaderByHash(hash common.Hash) *types.Header { 461 return lc.hc.GetHeaderByHash(hash) 462 } 463 464 // HasHeader checks if a block header is present in the database or not, caching 465 // it if present. 466 func (lc *LightChain) HasHeader(hash common.Hash, number uint64) bool { 467 return lc.hc.HasHeader(hash, number) 468 } 469 470 // GetCanonicalHash returns the canonical hash for a given block number 471 func (bc *LightChain) GetCanonicalHash(number uint64) common.Hash { 472 return bc.hc.GetCanonicalHash(number) 473 } 474 475 // GetBlockHashesFromHash retrieves a number of block hashes starting at a given 476 // hash, fetching towards the genesis block. 477 func (lc *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { 478 return lc.hc.GetBlockHashesFromHash(hash, max) 479 } 480 481 // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or 482 // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the 483 // number of blocks to be individually checked before we reach the canonical chain. 484 // 485 // Note: ancestor == 0 returns the same block, 1 returns its parent and so on. 486 func (lc *LightChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) { 487 return lc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical) 488 } 489 490 // GetHeaderByNumber retrieves a block header from the database by number, 491 // caching it (associated with its hash) if found. 492 func (lc *LightChain) GetHeaderByNumber(number uint64) *types.Header { 493 return lc.hc.GetHeaderByNumber(number) 494 } 495 496 // GetHeaderByNumberOdr retrieves a block header from the database or network 497 // by number, caching it (associated with its hash) if found. 498 func (lc *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) { 499 if header := lc.hc.GetHeaderByNumber(number); header != nil { 500 return header, nil 501 } 502 return GetHeaderByNumber(ctx, lc.odr, number) 503 } 504 505 // Config retrieves the header chain's chain configuration. 506 func (lc *LightChain) Config() *params.ChainConfig { return lc.hc.Config() } 507 508 // SyncCheckpoint fetches the checkpoint point block header according to 509 // the checkpoint provided by the remote peer. 510 // 511 // Note if we are running the clique, fetches the last epoch snapshot header 512 // which covered by checkpoint. 513 func (lc *LightChain) SyncCheckpoint(ctx context.Context, checkpoint *params.TrustedCheckpoint) bool { 514 // Ensure the remote checkpoint head is ahead of us 515 head := lc.CurrentHeader().Number.Uint64() 516 517 latest := (checkpoint.SectionIndex+1)*lc.indexerConfig.ChtSize - 1 518 if clique := lc.hc.Config().Clique; clique != nil { 519 latest -= latest % clique.Epoch // epoch snapshot for clique 520 } 521 if head >= latest { 522 return true 523 } 524 // Retrieve the latest useful header and update to it 525 if header, err := GetHeaderByNumber(ctx, lc.odr, latest); header != nil && err == nil { 526 lc.chainmu.Lock() 527 defer lc.chainmu.Unlock() 528 529 // Ensure the chain didn't move past the latest block while retrieving it 530 if lc.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() { 531 log.Info("Updated latest header based on CHT", "number", header.Number, "hash", header.Hash(), "age", common.PrettyAge(time.Unix(int64(header.Time), 0))) 532 rawdb.WriteHeadHeaderHash(lc.chainDb, header.Hash()) 533 lc.hc.SetCurrentHeader(header) 534 } 535 return true 536 } 537 return false 538 } 539 540 // LockChain locks the chain mutex for reading so that multiple canonical hashes can be 541 // retrieved while it is guaranteed that they belong to the same version of the chain 542 func (lc *LightChain) LockChain() { 543 lc.chainmu.RLock() 544 } 545 546 // UnlockChain unlocks the chain mutex 547 func (lc *LightChain) UnlockChain() { 548 lc.chainmu.RUnlock() 549 } 550 551 // SubscribeChainEvent registers a subscription of ChainEvent. 552 func (lc *LightChain) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription { 553 return lc.scope.Track(lc.chainFeed.Subscribe(ch)) 554 } 555 556 // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent. 557 func (lc *LightChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription { 558 return lc.scope.Track(lc.chainHeadFeed.Subscribe(ch)) 559 } 560 561 // SubscribeChainSideEvent registers a subscription of ChainSideEvent. 562 func (lc *LightChain) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription { 563 return lc.scope.Track(lc.chainSideFeed.Subscribe(ch)) 564 } 565 566 // SubscribeLogsEvent implements the interface of filters.Backend 567 // LightChain does not send logs events, so return an empty subscription. 568 func (lc *LightChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription { 569 return lc.scope.Track(new(event.Feed).Subscribe(ch)) 570 } 571 572 // SubscribeRemovedLogsEvent implements the interface of filters.Backend 573 // LightChain does not send core.RemovedLogsEvent, so return an empty subscription. 574 func (lc *LightChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription { 575 return lc.scope.Track(new(event.Feed).Subscribe(ch)) 576 } 577 578 // DisableCheckFreq disables header validation. This is used for ultralight mode. 579 func (lc *LightChain) DisableCheckFreq() { 580 atomic.StoreInt32(&lc.disableCheckFreq, 1) 581 } 582 583 // EnableCheckFreq enables header validation. 584 func (lc *LightChain) EnableCheckFreq() { 585 atomic.StoreInt32(&lc.disableCheckFreq, 0) 586 }