github.com/devfans/go-ethereum@v1.5.10-0.20170326212234-7419d0c38291/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 "math/big" 22 "sync" 23 "sync/atomic" 24 "time" 25 26 "github.com/ethereum/go-ethereum/common" 27 "github.com/ethereum/go-ethereum/core" 28 "github.com/ethereum/go-ethereum/core/types" 29 "github.com/ethereum/go-ethereum/ethdb" 30 "github.com/ethereum/go-ethereum/event" 31 "github.com/ethereum/go-ethereum/log" 32 "github.com/ethereum/go-ethereum/params" 33 "github.com/ethereum/go-ethereum/pow" 34 "github.com/ethereum/go-ethereum/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 eventMux *event.TypeMux 51 genesisBlock *types.Block 52 53 mu sync.RWMutex 54 chainmu sync.RWMutex 55 procmu sync.RWMutex 56 57 bodyCache *lru.Cache // Cache for the most recent block bodies 58 bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format 59 blockCache *lru.Cache // Cache for the most recent entire blocks 60 61 quit chan struct{} 62 running int32 // running must be called automically 63 // procInterrupt must be atomically called 64 procInterrupt int32 // interrupt signaler for block processing 65 wg sync.WaitGroup 66 67 pow pow.PoW 68 validator core.HeaderValidator 69 } 70 71 // NewLightChain returns a fully initialised light chain using information 72 // available in the database. It initialises the default Ethereum header 73 // validator. 74 func NewLightChain(odr OdrBackend, config *params.ChainConfig, pow pow.PoW, mux *event.TypeMux) (*LightChain, error) { 75 bodyCache, _ := lru.New(bodyCacheLimit) 76 bodyRLPCache, _ := lru.New(bodyCacheLimit) 77 blockCache, _ := lru.New(blockCacheLimit) 78 79 bc := &LightChain{ 80 chainDb: odr.Database(), 81 odr: odr, 82 eventMux: mux, 83 quit: make(chan struct{}), 84 bodyCache: bodyCache, 85 bodyRLPCache: bodyRLPCache, 86 blockCache: blockCache, 87 pow: pow, 88 } 89 90 var err error 91 bc.hc, err = core.NewHeaderChain(odr.Database(), config, bc.Validator, bc.getProcInterrupt) 92 bc.SetValidator(core.NewHeaderValidator(config, bc.hc, pow)) 93 if err != nil { 94 return nil, err 95 } 96 97 bc.genesisBlock, _ = bc.GetBlockByNumber(NoOdr, 0) 98 if bc.genesisBlock == nil { 99 return nil, core.ErrNoGenesis 100 } 101 102 if bc.genesisBlock.Hash() == params.MainNetGenesisHash { 103 // add trusted CHT 104 WriteTrustedCht(bc.chainDb, TrustedCht{Number: 805, Root: common.HexToHash("85e4286fe0a730390245c49de8476977afdae0eb5530b277f62a52b12313d50f")}) 105 log.Info("Added trusted CHT for mainnet") 106 } 107 108 if err := bc.loadLastState(); err != nil { 109 return nil, err 110 } 111 // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain 112 for hash := range core.BadHashes { 113 if header := bc.GetHeaderByHash(hash); header != nil { 114 log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash) 115 bc.SetHead(header.Number.Uint64() - 1) 116 log.Error("Chain rewind was successful, resuming normal operation") 117 } 118 } 119 return bc, nil 120 } 121 122 func (self *LightChain) getProcInterrupt() bool { 123 return atomic.LoadInt32(&self.procInterrupt) == 1 124 } 125 126 // Odr returns the ODR backend of the chain 127 func (self *LightChain) Odr() OdrBackend { 128 return self.odr 129 } 130 131 // loadLastState loads the last known chain state from the database. This method 132 // assumes that the chain manager mutex is held. 133 func (self *LightChain) loadLastState() error { 134 if head := core.GetHeadHeaderHash(self.chainDb); head == (common.Hash{}) { 135 // Corrupt or empty database, init from scratch 136 self.Reset() 137 } else { 138 if header := self.GetHeaderByHash(head); header != nil { 139 self.hc.SetCurrentHeader(header) 140 } 141 } 142 143 // Issue a status log and return 144 header := self.hc.CurrentHeader() 145 headerTd := self.GetTd(header.Hash(), header.Number.Uint64()) 146 log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd) 147 148 // Try to be smart and issue a pow verification for the head to pre-generate caches 149 go self.pow.Verify(types.NewBlockWithHeader(header)) 150 151 return nil 152 } 153 154 // SetHead rewinds the local chain to a new head. Everything above the new 155 // head will be deleted and the new one set. 156 func (bc *LightChain) SetHead(head uint64) { 157 bc.mu.Lock() 158 defer bc.mu.Unlock() 159 160 bc.hc.SetHead(head, nil) 161 bc.loadLastState() 162 } 163 164 // GasLimit returns the gas limit of the current HEAD block. 165 func (self *LightChain) GasLimit() *big.Int { 166 self.mu.RLock() 167 defer self.mu.RUnlock() 168 169 return self.hc.CurrentHeader().GasLimit 170 } 171 172 // LastBlockHash return the hash of the HEAD block. 173 func (self *LightChain) LastBlockHash() common.Hash { 174 self.mu.RLock() 175 defer self.mu.RUnlock() 176 177 return self.hc.CurrentHeader().Hash() 178 } 179 180 // Status returns status information about the current chain such as the HEAD Td, 181 // the HEAD hash and the hash of the genesis block. 182 func (self *LightChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) { 183 self.mu.RLock() 184 defer self.mu.RUnlock() 185 186 header := self.hc.CurrentHeader() 187 hash := header.Hash() 188 return self.GetTd(hash, header.Number.Uint64()), hash, self.genesisBlock.Hash() 189 } 190 191 // SetValidator sets the validator which is used to validate incoming headers. 192 func (self *LightChain) SetValidator(validator core.HeaderValidator) { 193 self.procmu.Lock() 194 defer self.procmu.Unlock() 195 self.validator = validator 196 } 197 198 // Validator returns the current header validator. 199 func (self *LightChain) Validator() core.HeaderValidator { 200 self.procmu.RLock() 201 defer self.procmu.RUnlock() 202 return self.validator 203 } 204 205 // State returns a new mutable state based on the current HEAD block. 206 func (self *LightChain) State() *LightState { 207 return NewLightState(StateTrieID(self.hc.CurrentHeader()), self.odr) 208 } 209 210 // Reset purges the entire blockchain, restoring it to its genesis state. 211 func (bc *LightChain) Reset() { 212 bc.ResetWithGenesisBlock(bc.genesisBlock) 213 } 214 215 // ResetWithGenesisBlock purges the entire blockchain, restoring it to the 216 // specified genesis state. 217 func (bc *LightChain) ResetWithGenesisBlock(genesis *types.Block) { 218 // Dump the entire block chain and purge the caches 219 bc.SetHead(0) 220 221 bc.mu.Lock() 222 defer bc.mu.Unlock() 223 224 // Prepare the genesis block and reinitialise the chain 225 if err := core.WriteTd(bc.chainDb, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil { 226 log.Crit("Failed to write genesis block TD", "err", err) 227 } 228 if err := core.WriteBlock(bc.chainDb, genesis); err != nil { 229 log.Crit("Failed to write genesis block", "err", err) 230 } 231 bc.genesisBlock = genesis 232 bc.hc.SetGenesis(bc.genesisBlock.Header()) 233 bc.hc.SetCurrentHeader(bc.genesisBlock.Header()) 234 } 235 236 // Accessors 237 238 // Genesis returns the genesis block 239 func (bc *LightChain) Genesis() *types.Block { 240 return bc.genesisBlock 241 } 242 243 // GetBody retrieves a block body (transactions and uncles) from the database 244 // or ODR service by hash, caching it if found. 245 func (self *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) { 246 // Short circuit if the body's already in the cache, retrieve otherwise 247 if cached, ok := self.bodyCache.Get(hash); ok { 248 body := cached.(*types.Body) 249 return body, nil 250 } 251 body, err := GetBody(ctx, self.odr, hash, self.hc.GetBlockNumber(hash)) 252 if err != nil { 253 return nil, err 254 } 255 // Cache the found body for next time and return 256 self.bodyCache.Add(hash, body) 257 return body, nil 258 } 259 260 // GetBodyRLP retrieves a block body in RLP encoding from the database or 261 // ODR service by hash, caching it if found. 262 func (self *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) { 263 // Short circuit if the body's already in the cache, retrieve otherwise 264 if cached, ok := self.bodyRLPCache.Get(hash); ok { 265 return cached.(rlp.RawValue), nil 266 } 267 body, err := GetBodyRLP(ctx, self.odr, hash, self.hc.GetBlockNumber(hash)) 268 if err != nil { 269 return nil, err 270 } 271 // Cache the found body for next time and return 272 self.bodyRLPCache.Add(hash, body) 273 return body, nil 274 } 275 276 // HasBlock checks if a block is fully present in the database or not, caching 277 // it if present. 278 func (bc *LightChain) HasBlock(hash common.Hash) bool { 279 blk, _ := bc.GetBlockByHash(NoOdr, hash) 280 return blk != nil 281 } 282 283 // GetBlock retrieves a block from the database or ODR service by hash and number, 284 // caching it if found. 285 func (self *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) { 286 // Short circuit if the block's already in the cache, retrieve otherwise 287 if block, ok := self.blockCache.Get(hash); ok { 288 return block.(*types.Block), nil 289 } 290 block, err := GetBlock(ctx, self.odr, hash, number) 291 if err != nil { 292 return nil, err 293 } 294 // Cache the found block for next time and return 295 self.blockCache.Add(block.Hash(), block) 296 return block, nil 297 } 298 299 // GetBlockByHash retrieves a block from the database or ODR service by hash, 300 // caching it if found. 301 func (self *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { 302 return self.GetBlock(ctx, hash, self.hc.GetBlockNumber(hash)) 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 (self *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) { 308 hash, err := GetCanonicalHash(ctx, self.odr, number) 309 if hash == (common.Hash{}) || err != nil { 310 return nil, err 311 } 312 return self.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 (bc *LightChain) Stop() { 318 if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) { 319 return 320 } 321 close(bc.quit) 322 atomic.StoreInt32(&bc.procInterrupt, 1) 323 324 bc.wg.Wait() 325 log.Info("Blockchain manager stopped") 326 } 327 328 // Rollback is designed to remove a chain of links from the database that aren't 329 // certain enough to be valid. 330 func (self *LightChain) Rollback(chain []common.Hash) { 331 self.mu.Lock() 332 defer self.mu.Unlock() 333 334 for i := len(chain) - 1; i >= 0; i-- { 335 hash := chain[i] 336 337 if head := self.hc.CurrentHeader(); head.Hash() == hash { 338 self.hc.SetCurrentHeader(self.GetHeader(head.ParentHash, head.Number.Uint64()-1)) 339 } 340 } 341 } 342 343 // postChainEvents iterates over the events generated by a chain insertion and 344 // posts them into the event mux. 345 func (self *LightChain) postChainEvents(events []interface{}) { 346 for _, event := range events { 347 if event, ok := event.(core.ChainEvent); ok { 348 if self.LastBlockHash() == event.Hash { 349 self.eventMux.Post(core.ChainHeadEvent{Block: event.Block}) 350 } 351 } 352 // Fire the insertion events individually too 353 self.eventMux.Post(event) 354 } 355 } 356 357 // InsertHeaderChain attempts to insert the given header chain in to the local 358 // chain, possibly creating a reorg. If an error is returned, it will return the 359 // index number of the failing header as well an error describing what went wrong. 360 // 361 // The verify parameter can be used to fine tune whether nonce verification 362 // should be done or not. The reason behind the optional check is because some 363 // of the header retrieval mechanisms already need to verfy nonces, as well as 364 // because nonces can be verified sparsely, not needing to check each. 365 // 366 // In the case of a light chain, InsertHeaderChain also creates and posts light 367 // chain events when necessary. 368 func (self *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) { 369 start := time.Now() 370 if i, err := self.hc.ValidateHeaderChain(chain, checkFreq); err != nil { 371 return i, err 372 } 373 374 // Make sure only one thread manipulates the chain at once 375 self.chainmu.Lock() 376 defer func() { 377 self.chainmu.Unlock() 378 time.Sleep(time.Millisecond * 10) // ugly hack; do not hog chain lock in case syncing is CPU-limited by validation 379 }() 380 381 self.wg.Add(1) 382 defer self.wg.Done() 383 384 var events []interface{} 385 whFunc := func(header *types.Header) error { 386 self.mu.Lock() 387 defer self.mu.Unlock() 388 389 status, err := self.hc.WriteHeader(header) 390 391 switch status { 392 case core.CanonStatTy: 393 log.Debug("Inserted new header", "number", header.Number, "hash", header.Hash()) 394 events = append(events, core.ChainEvent{Block: types.NewBlockWithHeader(header), Hash: header.Hash()}) 395 396 case core.SideStatTy: 397 log.Debug("Inserted forked header", "number", header.Number, "hash", header.Hash()) 398 events = append(events, core.ChainSideEvent{Block: types.NewBlockWithHeader(header)}) 399 400 case core.SplitStatTy: 401 events = append(events, core.ChainSplitEvent{Block: types.NewBlockWithHeader(header)}) 402 } 403 return err 404 } 405 i, err := self.hc.InsertHeaderChain(chain, whFunc, start) 406 go self.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 (self *LightChain) CurrentHeader() *types.Header { 413 self.mu.RLock() 414 defer self.mu.RUnlock() 415 416 return self.hc.CurrentHeader() 417 } 418 419 // GetTd retrieves a block's total difficulty in the canonical chain from the 420 // database by hash and number, caching it if found. 421 func (self *LightChain) GetTd(hash common.Hash, number uint64) *big.Int { 422 return self.hc.GetTd(hash, number) 423 } 424 425 // GetTdByHash retrieves a block's total difficulty in the canonical chain from the 426 // database by hash, caching it if found. 427 func (self *LightChain) GetTdByHash(hash common.Hash) *big.Int { 428 return self.hc.GetTdByHash(hash) 429 } 430 431 // GetHeader retrieves a block header from the database by hash and number, 432 // caching it if found. 433 func (self *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header { 434 return self.hc.GetHeader(hash, number) 435 } 436 437 // GetHeaderByHash retrieves a block header from the database by hash, caching it if 438 // found. 439 func (self *LightChain) GetHeaderByHash(hash common.Hash) *types.Header { 440 return self.hc.GetHeaderByHash(hash) 441 } 442 443 // HasHeader checks if a block header is present in the database or not, caching 444 // it if present. 445 func (bc *LightChain) HasHeader(hash common.Hash) bool { 446 return bc.hc.HasHeader(hash) 447 } 448 449 // GetBlockHashesFromHash retrieves a number of block hashes starting at a given 450 // hash, fetching towards the genesis block. 451 func (self *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { 452 return self.hc.GetBlockHashesFromHash(hash, max) 453 } 454 455 // GetHeaderByNumber retrieves a block header from the database by number, 456 // caching it (associated with its hash) if found. 457 func (self *LightChain) GetHeaderByNumber(number uint64) *types.Header { 458 return self.hc.GetHeaderByNumber(number) 459 } 460 461 // GetHeaderByNumberOdr retrieves a block header from the database or network 462 // by number, caching it (associated with its hash) if found. 463 func (self *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) { 464 if header := self.hc.GetHeaderByNumber(number); header != nil { 465 return header, nil 466 } 467 return GetHeaderByNumber(ctx, self.odr, number) 468 } 469 470 func (self *LightChain) SyncCht(ctx context.Context) bool { 471 headNum := self.CurrentHeader().Number.Uint64() 472 cht := GetTrustedCht(self.chainDb) 473 if headNum+1 < cht.Number*ChtFrequency { 474 num := cht.Number*ChtFrequency - 1 475 header, err := GetHeaderByNumber(ctx, self.odr, num) 476 if header != nil && err == nil { 477 self.mu.Lock() 478 if self.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() { 479 self.hc.SetCurrentHeader(header) 480 } 481 self.mu.Unlock() 482 return true 483 } 484 } 485 return false 486 } 487 488 // LockChain locks the chain mutex for reading so that multiple canonical hashes can be 489 // retrieved while it is guaranteed that they belong to the same version of the chain 490 func (self *LightChain) LockChain() { 491 self.chainmu.RLock() 492 } 493 494 // UnlockChain unlocks the chain mutex 495 func (self *LightChain) UnlockChain() { 496 self.chainmu.RUnlock() 497 }