github.com/lukasz-zimnoch/go-ethereum@v1.9.7/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 // loadLastState loads the last known chain state from the database. This method 147 // assumes that the chain manager mutex is held. 148 func (lc *LightChain) loadLastState() error { 149 if head := rawdb.ReadHeadHeaderHash(lc.chainDb); head == (common.Hash{}) { 150 // Corrupt or empty database, init from scratch 151 lc.Reset() 152 } else { 153 if header := lc.GetHeaderByHash(head); header != nil { 154 lc.hc.SetCurrentHeader(header) 155 } 156 } 157 158 // Issue a status log and return 159 header := lc.hc.CurrentHeader() 160 headerTd := lc.GetTd(header.Hash(), header.Number.Uint64()) 161 log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(header.Time), 0))) 162 163 return nil 164 } 165 166 // SetHead rewinds the local chain to a new head. Everything above the new 167 // head will be deleted and the new one set. 168 func (lc *LightChain) SetHead(head uint64) error { 169 lc.chainmu.Lock() 170 defer lc.chainmu.Unlock() 171 172 lc.hc.SetHead(head, nil, nil) 173 return lc.loadLastState() 174 } 175 176 // GasLimit returns the gas limit of the current HEAD block. 177 func (lc *LightChain) GasLimit() uint64 { 178 return lc.hc.CurrentHeader().GasLimit 179 } 180 181 // Reset purges the entire blockchain, restoring it to its genesis state. 182 func (lc *LightChain) Reset() { 183 lc.ResetWithGenesisBlock(lc.genesisBlock) 184 } 185 186 // ResetWithGenesisBlock purges the entire blockchain, restoring it to the 187 // specified genesis state. 188 func (lc *LightChain) ResetWithGenesisBlock(genesis *types.Block) { 189 // Dump the entire block chain and purge the caches 190 lc.SetHead(0) 191 192 lc.chainmu.Lock() 193 defer lc.chainmu.Unlock() 194 195 // Prepare the genesis block and reinitialise the chain 196 rawdb.WriteTd(lc.chainDb, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()) 197 rawdb.WriteBlock(lc.chainDb, genesis) 198 199 lc.genesisBlock = genesis 200 lc.hc.SetGenesis(lc.genesisBlock.Header()) 201 lc.hc.SetCurrentHeader(lc.genesisBlock.Header()) 202 } 203 204 // Accessors 205 206 // Engine retrieves the light chain's consensus engine. 207 func (lc *LightChain) Engine() consensus.Engine { return lc.engine } 208 209 // Genesis returns the genesis block 210 func (lc *LightChain) Genesis() *types.Block { 211 return lc.genesisBlock 212 } 213 214 func (lc *LightChain) StateCache() state.Database { 215 panic("not implemented") 216 } 217 218 // GetBody retrieves a block body (transactions and uncles) from the database 219 // or ODR service by hash, caching it if found. 220 func (lc *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) { 221 // Short circuit if the body's already in the cache, retrieve otherwise 222 if cached, ok := lc.bodyCache.Get(hash); ok { 223 body := cached.(*types.Body) 224 return body, nil 225 } 226 number := lc.hc.GetBlockNumber(hash) 227 if number == nil { 228 return nil, errors.New("unknown block") 229 } 230 body, err := GetBody(ctx, lc.odr, hash, *number) 231 if err != nil { 232 return nil, err 233 } 234 // Cache the found body for next time and return 235 lc.bodyCache.Add(hash, body) 236 return body, nil 237 } 238 239 // GetBodyRLP retrieves a block body in RLP encoding from the database or 240 // ODR service by hash, caching it if found. 241 func (lc *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) { 242 // Short circuit if the body's already in the cache, retrieve otherwise 243 if cached, ok := lc.bodyRLPCache.Get(hash); ok { 244 return cached.(rlp.RawValue), nil 245 } 246 number := lc.hc.GetBlockNumber(hash) 247 if number == nil { 248 return nil, errors.New("unknown block") 249 } 250 body, err := GetBodyRLP(ctx, lc.odr, hash, *number) 251 if err != nil { 252 return nil, err 253 } 254 // Cache the found body for next time and return 255 lc.bodyRLPCache.Add(hash, body) 256 return body, nil 257 } 258 259 // HasBlock checks if a block is fully present in the database or not, caching 260 // it if present. 261 func (lc *LightChain) HasBlock(hash common.Hash, number uint64) bool { 262 blk, _ := lc.GetBlock(NoOdr, hash, number) 263 return blk != nil 264 } 265 266 // GetBlock retrieves a block from the database or ODR service by hash and number, 267 // caching it if found. 268 func (lc *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) { 269 // Short circuit if the block's already in the cache, retrieve otherwise 270 if block, ok := lc.blockCache.Get(hash); ok { 271 return block.(*types.Block), nil 272 } 273 block, err := GetBlock(ctx, lc.odr, hash, number) 274 if err != nil { 275 return nil, err 276 } 277 // Cache the found block for next time and return 278 lc.blockCache.Add(block.Hash(), block) 279 return block, nil 280 } 281 282 // GetBlockByHash retrieves a block from the database or ODR service by hash, 283 // caching it if found. 284 func (lc *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { 285 number := lc.hc.GetBlockNumber(hash) 286 if number == nil { 287 return nil, errors.New("unknown block") 288 } 289 return lc.GetBlock(ctx, hash, *number) 290 } 291 292 // GetBlockByNumber retrieves a block from the database or ODR service by 293 // number, caching it (associated with its hash) if found. 294 func (lc *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) { 295 hash, err := GetCanonicalHash(ctx, lc.odr, number) 296 if hash == (common.Hash{}) || err != nil { 297 return nil, err 298 } 299 return lc.GetBlock(ctx, hash, number) 300 } 301 302 // Stop stops the blockchain service. If any imports are currently in progress 303 // it will abort them using the procInterrupt. 304 func (lc *LightChain) Stop() { 305 if !atomic.CompareAndSwapInt32(&lc.running, 0, 1) { 306 return 307 } 308 close(lc.quit) 309 atomic.StoreInt32(&lc.procInterrupt, 1) 310 311 lc.wg.Wait() 312 log.Info("Blockchain manager stopped") 313 } 314 315 // Rollback is designed to remove a chain of links from the database that aren't 316 // certain enough to be valid. 317 func (lc *LightChain) Rollback(chain []common.Hash) { 318 lc.chainmu.Lock() 319 defer lc.chainmu.Unlock() 320 321 for i := len(chain) - 1; i >= 0; i-- { 322 hash := chain[i] 323 324 if head := lc.hc.CurrentHeader(); head.Hash() == hash { 325 lc.hc.SetCurrentHeader(lc.GetHeader(head.ParentHash, head.Number.Uint64()-1)) 326 } 327 } 328 } 329 330 // postChainEvents iterates over the events generated by a chain insertion and 331 // posts them into the event feed. 332 func (lc *LightChain) postChainEvents(events []interface{}) { 333 for _, event := range events { 334 switch ev := event.(type) { 335 case core.ChainEvent: 336 if lc.CurrentHeader().Hash() == ev.Hash { 337 lc.chainHeadFeed.Send(core.ChainHeadEvent{Block: ev.Block}) 338 } 339 lc.chainFeed.Send(ev) 340 case core.ChainSideEvent: 341 lc.chainSideFeed.Send(ev) 342 } 343 } 344 } 345 346 // InsertHeaderChain attempts to insert the given header chain in to the local 347 // chain, possibly creating a reorg. If an error is returned, it will return the 348 // index number of the failing header as well an error describing what went wrong. 349 // 350 // The verify parameter can be used to fine tune whether nonce verification 351 // should be done or not. The reason behind the optional check is because some 352 // of the header retrieval mechanisms already need to verfy nonces, as well as 353 // because nonces can be verified sparsely, not needing to check each. 354 // 355 // In the case of a light chain, InsertHeaderChain also creates and posts light 356 // chain events when necessary. 357 func (lc *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) { 358 if atomic.LoadInt32(&lc.disableCheckFreq) == 1 { 359 checkFreq = 0 360 } 361 start := time.Now() 362 if i, err := lc.hc.ValidateHeaderChain(chain, checkFreq); err != nil { 363 return i, err 364 } 365 366 // Make sure only one thread manipulates the chain at once 367 lc.chainmu.Lock() 368 defer lc.chainmu.Unlock() 369 370 lc.wg.Add(1) 371 defer lc.wg.Done() 372 373 var events []interface{} 374 whFunc := func(header *types.Header) error { 375 status, err := lc.hc.WriteHeader(header) 376 377 switch status { 378 case core.CanonStatTy: 379 log.Debug("Inserted new header", "number", header.Number, "hash", header.Hash()) 380 events = append(events, core.ChainEvent{Block: types.NewBlockWithHeader(header), Hash: header.Hash()}) 381 382 case core.SideStatTy: 383 log.Debug("Inserted forked header", "number", header.Number, "hash", header.Hash()) 384 events = append(events, core.ChainSideEvent{Block: types.NewBlockWithHeader(header)}) 385 } 386 return err 387 } 388 i, err := lc.hc.InsertHeaderChain(chain, whFunc, start) 389 lc.postChainEvents(events) 390 return i, err 391 } 392 393 // CurrentHeader retrieves the current head header of the canonical chain. The 394 // header is retrieved from the HeaderChain's internal cache. 395 func (lc *LightChain) CurrentHeader() *types.Header { 396 return lc.hc.CurrentHeader() 397 } 398 399 // GetTd retrieves a block's total difficulty in the canonical chain from the 400 // database by hash and number, caching it if found. 401 func (lc *LightChain) GetTd(hash common.Hash, number uint64) *big.Int { 402 return lc.hc.GetTd(hash, number) 403 } 404 405 // GetTdByHash retrieves a block's total difficulty in the canonical chain from the 406 // database by hash, caching it if found. 407 func (lc *LightChain) GetTdByHash(hash common.Hash) *big.Int { 408 return lc.hc.GetTdByHash(hash) 409 } 410 411 // GetHeader retrieves a block header from the database by hash and number, 412 // caching it if found. 413 func (lc *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header { 414 return lc.hc.GetHeader(hash, number) 415 } 416 417 // GetHeaderByHash retrieves a block header from the database by hash, caching it if 418 // found. 419 func (lc *LightChain) GetHeaderByHash(hash common.Hash) *types.Header { 420 return lc.hc.GetHeaderByHash(hash) 421 } 422 423 // HasHeader checks if a block header is present in the database or not, caching 424 // it if present. 425 func (lc *LightChain) HasHeader(hash common.Hash, number uint64) bool { 426 return lc.hc.HasHeader(hash, number) 427 } 428 429 // GetCanonicalHash returns the canonical hash for a given block number 430 func (bc *LightChain) GetCanonicalHash(number uint64) common.Hash { 431 return bc.hc.GetCanonicalHash(number) 432 } 433 434 // GetBlockHashesFromHash retrieves a number of block hashes starting at a given 435 // hash, fetching towards the genesis block. 436 func (lc *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { 437 return lc.hc.GetBlockHashesFromHash(hash, max) 438 } 439 440 // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or 441 // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the 442 // number of blocks to be individually checked before we reach the canonical chain. 443 // 444 // Note: ancestor == 0 returns the same block, 1 returns its parent and so on. 445 func (lc *LightChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) { 446 return lc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical) 447 } 448 449 // GetHeaderByNumber retrieves a block header from the database by number, 450 // caching it (associated with its hash) if found. 451 func (lc *LightChain) GetHeaderByNumber(number uint64) *types.Header { 452 return lc.hc.GetHeaderByNumber(number) 453 } 454 455 // GetHeaderByNumberOdr retrieves a block header from the database or network 456 // by number, caching it (associated with its hash) if found. 457 func (lc *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) { 458 if header := lc.hc.GetHeaderByNumber(number); header != nil { 459 return header, nil 460 } 461 return GetHeaderByNumber(ctx, lc.odr, number) 462 } 463 464 // Config retrieves the header chain's chain configuration. 465 func (lc *LightChain) Config() *params.ChainConfig { return lc.hc.Config() } 466 467 // SyncCheckpoint fetches the checkpoint point block header according to 468 // the checkpoint provided by the remote peer. 469 // 470 // Note if we are running the clique, fetches the last epoch snapshot header 471 // which covered by checkpoint. 472 func (lc *LightChain) SyncCheckpoint(ctx context.Context, checkpoint *params.TrustedCheckpoint) bool { 473 // Ensure the remote checkpoint head is ahead of us 474 head := lc.CurrentHeader().Number.Uint64() 475 476 latest := (checkpoint.SectionIndex+1)*lc.indexerConfig.ChtSize - 1 477 if clique := lc.hc.Config().Clique; clique != nil { 478 latest -= latest % clique.Epoch // epoch snapshot for clique 479 } 480 if head >= latest { 481 return true 482 } 483 // Retrieve the latest useful header and update to it 484 if header, err := GetHeaderByNumber(ctx, lc.odr, latest); header != nil && err == nil { 485 lc.chainmu.Lock() 486 defer lc.chainmu.Unlock() 487 488 // Ensure the chain didn't move past the latest block while retrieving it 489 if lc.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() { 490 log.Info("Updated latest header based on CHT", "number", header.Number, "hash", header.Hash(), "age", common.PrettyAge(time.Unix(int64(header.Time), 0))) 491 lc.hc.SetCurrentHeader(header) 492 } 493 return true 494 } 495 return false 496 } 497 498 // LockChain locks the chain mutex for reading so that multiple canonical hashes can be 499 // retrieved while it is guaranteed that they belong to the same version of the chain 500 func (lc *LightChain) LockChain() { 501 lc.chainmu.RLock() 502 } 503 504 // UnlockChain unlocks the chain mutex 505 func (lc *LightChain) UnlockChain() { 506 lc.chainmu.RUnlock() 507 } 508 509 // SubscribeChainEvent registers a subscription of ChainEvent. 510 func (lc *LightChain) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription { 511 return lc.scope.Track(lc.chainFeed.Subscribe(ch)) 512 } 513 514 // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent. 515 func (lc *LightChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription { 516 return lc.scope.Track(lc.chainHeadFeed.Subscribe(ch)) 517 } 518 519 // SubscribeChainSideEvent registers a subscription of ChainSideEvent. 520 func (lc *LightChain) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription { 521 return lc.scope.Track(lc.chainSideFeed.Subscribe(ch)) 522 } 523 524 // SubscribeLogsEvent implements the interface of filters.Backend 525 // LightChain does not send logs events, so return an empty subscription. 526 func (lc *LightChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription { 527 return lc.scope.Track(new(event.Feed).Subscribe(ch)) 528 } 529 530 // SubscribeRemovedLogsEvent implements the interface of filters.Backend 531 // LightChain does not send core.RemovedLogsEvent, so return an empty subscription. 532 func (lc *LightChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription { 533 return lc.scope.Track(new(event.Feed).Subscribe(ch)) 534 } 535 536 // DisableCheckFreq disables header validation. This is used for ultralight mode. 537 func (lc *LightChain) DisableCheckFreq() { 538 atomic.StoreInt32(&lc.disableCheckFreq, 1) 539 } 540 541 // EnableCheckFreq enables header validation. 542 func (lc *LightChain) EnableCheckFreq() { 543 atomic.StoreInt32(&lc.disableCheckFreq, 0) 544 }