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