github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/light/lightchain.go (about) 1 // Copyright 2016 The Spectrum Authors 2 // This file is part of the Spectrum library. 3 // 4 // The Spectrum 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 Spectrum 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 Spectrum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package light 18 19 import ( 20 "context" 21 "math/big" 22 "sync" 23 "sync/atomic" 24 "time" 25 26 "github.com/SmartMeshFoundation/Spectrum/common" 27 "github.com/SmartMeshFoundation/Spectrum/consensus" 28 "github.com/SmartMeshFoundation/Spectrum/core" 29 "github.com/SmartMeshFoundation/Spectrum/core/types" 30 "github.com/SmartMeshFoundation/Spectrum/ethdb" 31 "github.com/SmartMeshFoundation/Spectrum/event" 32 "github.com/SmartMeshFoundation/Spectrum/log" 33 "github.com/SmartMeshFoundation/Spectrum/params" 34 "github.com/SmartMeshFoundation/Spectrum/rlp" 35 "github.com/hashicorp/golang-lru" 36 ) 37 38 var ( 39 bodyCacheLimit = 256 40 blockCacheLimit = 256 41 ) 42 43 // LightChain represents a canonical chain that by default only handles block 44 // headers, downloading block bodies and receipts on demand through an ODR 45 // interface. It only does header validation during chain insertion. 46 type LightChain struct { 47 hc *core.HeaderChain 48 chainDb ethdb.Database 49 odr OdrBackend 50 chainFeed event.Feed 51 chainSideFeed event.Feed 52 chainHeadFeed event.Feed 53 scope event.SubscriptionScope 54 genesisBlock *types.Block 55 56 mu sync.RWMutex 57 chainmu sync.RWMutex 58 59 bodyCache *lru.Cache // Cache for the most recent block bodies 60 bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format 61 blockCache *lru.Cache // Cache for the most recent entire blocks 62 63 quit chan struct{} 64 running int32 // running must be called automically 65 // procInterrupt must be atomically called 66 procInterrupt int32 // interrupt signaler for block processing 67 wg sync.WaitGroup 68 69 engine consensus.Engine 70 } 71 72 // NewLightChain returns a fully initialised light chain using information 73 // available in the database. It initialises the default Ethereum header 74 // validator. 75 func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus.Engine) (*LightChain, error) { 76 bodyCache, _ := lru.New(bodyCacheLimit) 77 bodyRLPCache, _ := lru.New(bodyCacheLimit) 78 blockCache, _ := lru.New(blockCacheLimit) 79 80 bc := &LightChain{ 81 chainDb: odr.Database(), 82 odr: odr, 83 quit: make(chan struct{}), 84 bodyCache: bodyCache, 85 bodyRLPCache: bodyRLPCache, 86 blockCache: blockCache, 87 engine: engine, 88 } 89 var err error 90 bc.hc, err = core.NewHeaderChain(odr.Database(), config, bc.engine, bc.getProcInterrupt) 91 if err != nil { 92 return nil, err 93 } 94 bc.genesisBlock, _ = bc.GetBlockByNumber(NoOdr, 0) 95 if bc.genesisBlock == nil { 96 return nil, core.ErrNoGenesis 97 } 98 if cp, ok := trustedCheckpoints[bc.genesisBlock.Hash()]; ok { 99 bc.addTrustedCheckpoint(cp) 100 } 101 102 if err := bc.loadLastState(); err != nil { 103 return nil, err 104 } 105 // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain 106 for hash := range core.BadHashes { 107 if header := bc.GetHeaderByHash(hash); header != nil { 108 log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash) 109 bc.SetHead(header.Number.Uint64() - 1) 110 log.Error("Chain rewind was successful, resuming normal operation") 111 } 112 } 113 return bc, nil 114 } 115 116 // addTrustedCheckpoint adds a trusted checkpoint to the blockchain 117 func (self *LightChain) addTrustedCheckpoint(cp trustedCheckpoint) { 118 if self.odr.ChtIndexer() != nil { 119 StoreChtRoot(self.chainDb, cp.sectionIdx, cp.sectionHead, cp.chtRoot) 120 self.odr.ChtIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead) 121 } 122 if self.odr.BloomTrieIndexer() != nil { 123 StoreBloomTrieRoot(self.chainDb, cp.sectionIdx, cp.sectionHead, cp.bloomTrieRoot) 124 self.odr.BloomTrieIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead) 125 } 126 if self.odr.BloomIndexer() != nil { 127 self.odr.BloomIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead) 128 } 129 log.Info("Added trusted checkpoint", "chain name", cp.name) 130 } 131 132 func (self *LightChain) getProcInterrupt() bool { 133 return atomic.LoadInt32(&self.procInterrupt) == 1 134 } 135 136 // Odr returns the ODR backend of the chain 137 func (self *LightChain) Odr() OdrBackend { 138 return self.odr 139 } 140 141 // loadLastState loads the last known chain state from the database. This method 142 // assumes that the chain manager mutex is held. 143 func (self *LightChain) loadLastState() error { 144 if head := core.GetHeadHeaderHash(self.chainDb); head == (common.Hash{}) { 145 // Corrupt or empty database, init from scratch 146 self.Reset() 147 } else { 148 if header := self.GetHeaderByHash(head); header != nil { 149 self.hc.SetCurrentHeader(header) 150 } 151 } 152 153 // Issue a status log and return 154 header := self.hc.CurrentHeader() 155 headerTd := self.GetTd(header.Hash(), header.Number.Uint64()) 156 log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd) 157 158 return nil 159 } 160 161 // SetHead rewinds the local chain to a new head. Everything above the new 162 // head will be deleted and the new one set. 163 func (bc *LightChain) SetHead(head uint64) { 164 bc.mu.Lock() 165 defer bc.mu.Unlock() 166 167 bc.hc.SetHead(head, nil) 168 bc.loadLastState() 169 } 170 171 // GasLimit returns the gas limit of the current HEAD block. 172 func (self *LightChain) GasLimit() *big.Int { 173 self.mu.RLock() 174 defer self.mu.RUnlock() 175 176 return self.hc.CurrentHeader().GasLimit 177 } 178 179 // LastBlockHash return the hash of the HEAD block. 180 func (self *LightChain) LastBlockHash() common.Hash { 181 self.mu.RLock() 182 defer self.mu.RUnlock() 183 184 return self.hc.CurrentHeader().Hash() 185 } 186 187 // Status returns status information about the current chain such as the HEAD Td, 188 // the HEAD hash and the hash of the genesis block. 189 func (self *LightChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) { 190 self.mu.RLock() 191 defer self.mu.RUnlock() 192 193 header := self.hc.CurrentHeader() 194 hash := header.Hash() 195 return self.GetTd(hash, header.Number.Uint64()), hash, self.genesisBlock.Hash() 196 } 197 198 // Reset purges the entire blockchain, restoring it to its genesis state. 199 func (bc *LightChain) Reset() { 200 bc.ResetWithGenesisBlock(bc.genesisBlock) 201 } 202 203 // ResetWithGenesisBlock purges the entire blockchain, restoring it to the 204 // specified genesis state. 205 func (bc *LightChain) ResetWithGenesisBlock(genesis *types.Block) { 206 // Dump the entire block chain and purge the caches 207 bc.SetHead(0) 208 209 bc.mu.Lock() 210 defer bc.mu.Unlock() 211 212 // Prepare the genesis block and reinitialise the chain 213 if err := core.WriteTd(bc.chainDb, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil { 214 log.Crit("Failed to write genesis block TD", "err", err) 215 } 216 if err := core.WriteBlock(bc.chainDb, genesis); err != nil { 217 log.Crit("Failed to write genesis block", "err", err) 218 } 219 bc.genesisBlock = genesis 220 bc.hc.SetGenesis(bc.genesisBlock.Header()) 221 bc.hc.SetCurrentHeader(bc.genesisBlock.Header()) 222 } 223 224 // Accessors 225 226 // Engine retrieves the light chain's consensus engine. 227 func (bc *LightChain) Engine() consensus.Engine { return bc.engine } 228 229 // Genesis returns the genesis block 230 func (bc *LightChain) Genesis() *types.Block { 231 return bc.genesisBlock 232 } 233 234 // GetBody retrieves a block body (transactions and uncles) from the database 235 // or ODR service by hash, caching it if found. 236 func (self *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) { 237 // Short circuit if the body's already in the cache, retrieve otherwise 238 if cached, ok := self.bodyCache.Get(hash); ok { 239 body := cached.(*types.Body) 240 return body, nil 241 } 242 body, err := GetBody(ctx, self.odr, hash, self.hc.GetBlockNumber(hash)) 243 if err != nil { 244 return nil, err 245 } 246 // Cache the found body for next time and return 247 self.bodyCache.Add(hash, body) 248 return body, nil 249 } 250 251 // GetBodyRLP retrieves a block body in RLP encoding from the database or 252 // ODR service by hash, caching it if found. 253 func (self *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) { 254 // Short circuit if the body's already in the cache, retrieve otherwise 255 if cached, ok := self.bodyRLPCache.Get(hash); ok { 256 return cached.(rlp.RawValue), nil 257 } 258 body, err := GetBodyRLP(ctx, self.odr, hash, self.hc.GetBlockNumber(hash)) 259 if err != nil { 260 return nil, err 261 } 262 // Cache the found body for next time and return 263 self.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 (bc *LightChain) HasBlock(hash common.Hash, number uint64) bool { 270 blk, _ := bc.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 (self *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 := self.blockCache.Get(hash); ok { 279 return block.(*types.Block), nil 280 } 281 block, err := GetBlock(ctx, self.odr, hash, number) 282 if err != nil { 283 return nil, err 284 } 285 // Cache the found block for next time and return 286 self.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 (self *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { 293 return self.GetBlock(ctx, hash, self.hc.GetBlockNumber(hash)) 294 } 295 296 // GetBlockByNumber retrieves a block from the database or ODR service by 297 // number, caching it (associated with its hash) if found. 298 func (self *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) { 299 hash, err := GetCanonicalHash(ctx, self.odr, number) 300 if hash == (common.Hash{}) || err != nil { 301 return nil, err 302 } 303 return self.GetBlock(ctx, hash, number) 304 } 305 306 // Stop stops the blockchain service. If any imports are currently in progress 307 // it will abort them using the procInterrupt. 308 func (bc *LightChain) Stop() { 309 if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) { 310 return 311 } 312 close(bc.quit) 313 atomic.StoreInt32(&bc.procInterrupt, 1) 314 315 bc.wg.Wait() 316 log.Info("Blockchain manager stopped") 317 } 318 319 // Rollback is designed to remove a chain of links from the database that aren't 320 // certain enough to be valid. 321 func (self *LightChain) Rollback(chain []common.Hash) { 322 self.mu.Lock() 323 defer self.mu.Unlock() 324 325 for i := len(chain) - 1; i >= 0; i-- { 326 hash := chain[i] 327 328 if head := self.hc.CurrentHeader(); head.Hash() == hash { 329 self.hc.SetCurrentHeader(self.GetHeader(head.ParentHash, head.Number.Uint64()-1)) 330 } 331 } 332 } 333 334 // postChainEvents iterates over the events generated by a chain insertion and 335 // posts them into the event feed. 336 func (self *LightChain) postChainEvents(events []interface{}) { 337 for _, event := range events { 338 switch ev := event.(type) { 339 case core.ChainEvent: 340 if self.LastBlockHash() == ev.Hash { 341 self.chainHeadFeed.Send(core.ChainHeadEvent{Block: ev.Block}) 342 } 343 self.chainFeed.Send(ev) 344 case core.ChainSideEvent: 345 self.chainSideFeed.Send(ev) 346 } 347 } 348 } 349 350 // InsertHeaderChain attempts to insert the given header chain in to the local 351 // chain, possibly creating a reorg. If an error is returned, it will return the 352 // index number of the failing header as well an error describing what went wrong. 353 // 354 // The verify parameter can be used to fine tune whether nonce verification 355 // should be done or not. The reason behind the optional check is because some 356 // of the header retrieval mechanisms already need to verfy nonces, as well as 357 // because nonces can be verified sparsely, not needing to check each. 358 // 359 // In the case of a light chain, InsertHeaderChain also creates and posts light 360 // chain events when necessary. 361 func (self *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) { 362 start := time.Now() 363 if i, err := self.hc.ValidateHeaderChain(chain, checkFreq); err != nil { 364 return i, err 365 } 366 367 // Make sure only one thread manipulates the chain at once 368 self.chainmu.Lock() 369 defer func() { 370 self.chainmu.Unlock() 371 time.Sleep(time.Millisecond * 10) // ugly hack; do not hog chain lock in case syncing is CPU-limited by validation 372 }() 373 374 self.wg.Add(1) 375 defer self.wg.Done() 376 377 var events []interface{} 378 whFunc := func(header *types.Header) error { 379 self.mu.Lock() 380 defer self.mu.Unlock() 381 382 status, err := self.hc.WriteHeader(header) 383 384 switch status { 385 case core.CanonStatTy: 386 log.Debug("Inserted new header", "number", header.Number, "hash", header.Hash()) 387 events = append(events, core.ChainEvent{Block: types.NewBlockWithHeader(header), Hash: header.Hash()}) 388 389 case core.SideStatTy: 390 log.Debug("Inserted forked header", "number", header.Number, "hash", header.Hash()) 391 events = append(events, core.ChainSideEvent{Block: types.NewBlockWithHeader(header)}) 392 } 393 return err 394 } 395 i, err := self.hc.InsertHeaderChain(chain, whFunc, start) 396 go self.postChainEvents(events) 397 return i, err 398 } 399 400 // CurrentHeader retrieves the current head header of the canonical chain. The 401 // header is retrieved from the HeaderChain's internal cache. 402 func (self *LightChain) CurrentHeader() *types.Header { 403 self.mu.RLock() 404 defer self.mu.RUnlock() 405 406 return self.hc.CurrentHeader() 407 } 408 409 // GetTd retrieves a block's total difficulty in the canonical chain from the 410 // database by hash and number, caching it if found. 411 func (self *LightChain) GetTd(hash common.Hash, number uint64) *big.Int { 412 return self.hc.GetTd(hash, number) 413 } 414 415 // GetTdByHash retrieves a block's total difficulty in the canonical chain from the 416 // database by hash, caching it if found. 417 func (self *LightChain) GetTdByHash(hash common.Hash) *big.Int { 418 return self.hc.GetTdByHash(hash) 419 } 420 421 // GetHeader retrieves a block header from the database by hash and number, 422 // caching it if found. 423 func (self *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header { 424 return self.hc.GetHeader(hash, number) 425 } 426 427 // GetHeaderByHash retrieves a block header from the database by hash, caching it if 428 // found. 429 func (self *LightChain) GetHeaderByHash(hash common.Hash) *types.Header { 430 return self.hc.GetHeaderByHash(hash) 431 } 432 433 // HasHeader checks if a block header is present in the database or not, caching 434 // it if present. 435 func (bc *LightChain) HasHeader(hash common.Hash, number uint64) bool { 436 return bc.hc.HasHeader(hash, number) 437 } 438 439 // GetBlockHashesFromHash retrieves a number of block hashes starting at a given 440 // hash, fetching towards the genesis block. 441 func (self *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { 442 return self.hc.GetBlockHashesFromHash(hash, max) 443 } 444 445 // GetHeaderByNumber retrieves a block header from the database by number, 446 // caching it (associated with its hash) if found. 447 func (self *LightChain) GetHeaderByNumber(number uint64) *types.Header { 448 return self.hc.GetHeaderByNumber(number) 449 } 450 451 // GetHeaderByNumberOdr retrieves a block header from the database or network 452 // by number, caching it (associated with its hash) if found. 453 func (self *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) { 454 if header := self.hc.GetHeaderByNumber(number); header != nil { 455 return header, nil 456 } 457 return GetHeaderByNumber(ctx, self.odr, number) 458 } 459 460 // Config retrieves the header chain's chain configuration. 461 func (self *LightChain) Config() *params.ChainConfig { return self.hc.Config() } 462 463 func (self *LightChain) SyncCht(ctx context.Context) bool { 464 if self.odr.ChtIndexer() == nil { 465 return false 466 } 467 headNum := self.CurrentHeader().Number.Uint64() 468 chtCount, _, _ := self.odr.ChtIndexer().Sections() 469 if headNum+1 < chtCount*ChtFrequency { 470 num := chtCount*ChtFrequency - 1 471 header, err := GetHeaderByNumber(ctx, self.odr, num) 472 if header != nil && err == nil { 473 self.mu.Lock() 474 if self.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() { 475 self.hc.SetCurrentHeader(header) 476 } 477 self.mu.Unlock() 478 return true 479 } 480 } 481 return false 482 } 483 484 // LockChain locks the chain mutex for reading so that multiple canonical hashes can be 485 // retrieved while it is guaranteed that they belong to the same version of the chain 486 func (self *LightChain) LockChain() { 487 self.chainmu.RLock() 488 } 489 490 // UnlockChain unlocks the chain mutex 491 func (self *LightChain) UnlockChain() { 492 self.chainmu.RUnlock() 493 } 494 495 // SubscribeChainEvent registers a subscription of ChainEvent. 496 func (self *LightChain) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription { 497 return self.scope.Track(self.chainFeed.Subscribe(ch)) 498 } 499 500 // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent. 501 func (self *LightChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription { 502 return self.scope.Track(self.chainHeadFeed.Subscribe(ch)) 503 } 504 505 // SubscribeChainSideEvent registers a subscription of ChainSideEvent. 506 func (self *LightChain) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription { 507 return self.scope.Track(self.chainSideFeed.Subscribe(ch)) 508 } 509 510 // SubscribeLogsEvent implements the interface of filters.Backend 511 // LightChain does not send logs events, so return an empty subscription. 512 func (self *LightChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription { 513 return self.scope.Track(new(event.Feed).Subscribe(ch)) 514 } 515 516 // SubscribeRemovedLogsEvent implements the interface of filters.Backend 517 // LightChain does not send core.RemovedLogsEvent, so return an empty subscription. 518 func (self *LightChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription { 519 return self.scope.Track(new(event.Feed).Subscribe(ch)) 520 }