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