cmd/geth, cmd/utils, core, rpc: renamed to blockchain

* Renamed ChainManager to BlockChain
* Checkpointing is no longer required and never really properly worked
when the state was corrupted.
This commit is contained in:
Jeffrey Wilcke 2015-08-31 17:09:50 +02:00
parent 361082ec4b
commit 7c7692933c
35 changed files with 267 additions and 302 deletions

View File

@ -118,7 +118,7 @@ func runOneBlockTest(ctx *cli.Context, test *tests.BlockTest) (*eth.Ethereum, er
return ethereum, fmt.Errorf("InsertPreState: %v", err) return ethereum, fmt.Errorf("InsertPreState: %v", err)
} }
cm := ethereum.ChainManager() cm := ethereum.BlockChain()
validBlocks, err := test.TryBlocksInsert(cm) validBlocks, err := test.TryBlocksInsert(cm)
if err != nil { if err != nil {
return ethereum, fmt.Errorf("Block Test load error: %v", err) return ethereum, fmt.Errorf("Block Test load error: %v", err)

View File

@ -196,7 +196,7 @@ func TestBlockChain(t *testing.T) {
tmpfile := filepath.Join(extmp, "export.chain") tmpfile := filepath.Join(extmp, "export.chain")
tmpfileq := strconv.Quote(tmpfile) tmpfileq := strconv.Quote(tmpfile)
ethereum.ChainManager().Reset() ethereum.BlockChain().Reset()
checkEvalJSON(t, repl, `admin.exportChain(`+tmpfileq+`)`, `true`) checkEvalJSON(t, repl, `admin.exportChain(`+tmpfileq+`)`, `true`)
if _, err := os.Stat(tmpfile); err != nil { if _, err := os.Stat(tmpfile); err != nil {

View File

@ -48,7 +48,7 @@ import (
const ( const (
ClientIdentifier = "Geth" ClientIdentifier = "Geth"
Version = "1.2.0" Version = "1.2.0-dev"
VersionMajor = 1 VersionMajor = 1
VersionMinor = 2 VersionMinor = 2
VersionPatch = 0 VersionPatch = 0

View File

@ -169,7 +169,7 @@ func FormatTransactionData(data string) []byte {
return d return d
} }
func ImportChain(chain *core.ChainManager, fn string) error { func ImportChain(chain *core.BlockChain, fn string) error {
// Watch for Ctrl-C while the import is running. // Watch for Ctrl-C while the import is running.
// If a signal is received, the import will stop at the next batch. // If a signal is received, the import will stop at the next batch.
interrupt := make(chan os.Signal, 1) interrupt := make(chan os.Signal, 1)
@ -244,7 +244,7 @@ func ImportChain(chain *core.ChainManager, fn string) error {
return nil return nil
} }
func hasAllBlocks(chain *core.ChainManager, bs []*types.Block) bool { func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
for _, b := range bs { for _, b := range bs {
if !chain.HasBlock(b.Hash()) { if !chain.HasBlock(b.Hash()) {
return false return false
@ -253,21 +253,21 @@ func hasAllBlocks(chain *core.ChainManager, bs []*types.Block) bool {
return true return true
} }
func ExportChain(chainmgr *core.ChainManager, fn string) error { func ExportChain(blockchain *core.BlockChain, fn string) error {
glog.Infoln("Exporting blockchain to", fn) glog.Infoln("Exporting blockchain to", fn)
fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
if err != nil { if err != nil {
return err return err
} }
defer fh.Close() defer fh.Close()
if err := chainmgr.Export(fh); err != nil { if err := blockchain.Export(fh); err != nil {
return err return err
} }
glog.Infoln("Exported blockchain to", fn) glog.Infoln("Exported blockchain to", fn)
return nil return nil
} }
func ExportAppendChain(chainmgr *core.ChainManager, fn string, first uint64, last uint64) error { func ExportAppendChain(blockchain *core.BlockChain, fn string, first uint64, last uint64) error {
glog.Infoln("Exporting blockchain to", fn) glog.Infoln("Exporting blockchain to", fn)
// TODO verify mode perms // TODO verify mode perms
fh, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm) fh, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm)
@ -275,7 +275,7 @@ func ExportAppendChain(chainmgr *core.ChainManager, fn string, first uint64, las
return err return err
} }
defer fh.Close() defer fh.Close()
if err := chainmgr.ExportN(fh, first, last); err != nil { if err := blockchain.ExportN(fh, first, last); err != nil {
return err return err
} }
glog.Infoln("Exported blockchain to", fn) glog.Infoln("Exported blockchain to", fn)

View File

@ -508,7 +508,7 @@ func SetupEth(ctx *cli.Context) {
} }
// MakeChain creates a chain manager from set command line flags. // MakeChain creates a chain manager from set command line flags.
func MakeChain(ctx *cli.Context) (chain *core.ChainManager, chainDb ethdb.Database) { func MakeChain(ctx *cli.Context) (chain *core.BlockChain, chainDb ethdb.Database) {
datadir := MustDataDir(ctx) datadir := MustDataDir(ctx)
cache := ctx.GlobalInt(CacheFlag.Name) cache := ctx.GlobalInt(CacheFlag.Name)
@ -527,7 +527,7 @@ func MakeChain(ctx *cli.Context) (chain *core.ChainManager, chainDb ethdb.Databa
eventMux := new(event.TypeMux) eventMux := new(event.TypeMux)
pow := ethash.New() pow := ethash.New()
//genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB) //genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
chain, err = core.NewChainManager(chainDb, pow, eventMux) chain, err = core.NewBlockChain(chainDb, pow, eventMux)
if err != nil { if err != nil {
Fatalf("Could not start chainmanager: %v", err) Fatalf("Could not start chainmanager: %v", err)
} }

View File

@ -168,7 +168,7 @@ func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) {
// Time the insertion of the new chain. // Time the insertion of the new chain.
// State and blocks are stored in the same DB. // State and blocks are stored in the same DB.
evmux := new(event.TypeMux) evmux := new(event.TypeMux)
chainman, _ := NewChainManager(db, FakePow{}, evmux) chainman, _ := NewBlockChain(db, FakePow{}, evmux)
chainman.SetProcessor(NewBlockProcessor(db, FakePow{}, chainman, evmux)) chainman.SetProcessor(NewBlockProcessor(db, FakePow{}, chainman, evmux))
defer chainman.Stop() defer chainman.Stop()
b.ReportAllocs() b.ReportAllocs()

View File

@ -47,7 +47,7 @@ type BlockProcessor struct {
// Mutex for locking the block processor. Blocks can only be handled one at a time // Mutex for locking the block processor. Blocks can only be handled one at a time
mutex sync.Mutex mutex sync.Mutex
// Canonical block chain // Canonical block chain
bc *ChainManager bc *BlockChain
// non-persistent key/value memory storage // non-persistent key/value memory storage
mem map[string]*big.Int mem map[string]*big.Int
// Proof of work used for validating // Proof of work used for validating
@ -70,12 +70,12 @@ type GasPool interface {
SubGas(gas, price *big.Int) error SubGas(gas, price *big.Int) error
} }
func NewBlockProcessor(db ethdb.Database, pow pow.PoW, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor { func NewBlockProcessor(db ethdb.Database, pow pow.PoW, blockchain *BlockChain, eventMux *event.TypeMux) *BlockProcessor {
sm := &BlockProcessor{ sm := &BlockProcessor{
chainDb: db, chainDb: db,
mem: make(map[string]*big.Int), mem: make(map[string]*big.Int),
Pow: pow, Pow: pow,
bc: chainManager, bc: blockchain,
eventMux: eventMux, eventMux: eventMux,
} }
return sm return sm
@ -124,7 +124,7 @@ func (self *BlockProcessor) ApplyTransaction(gp GasPool, statedb *state.StateDB,
return receipt, gas, err return receipt, gas, err
} }
func (self *BlockProcessor) ChainManager() *ChainManager { func (self *BlockProcessor) BlockChain() *BlockChain {
return self.bc return self.bc
} }
@ -347,7 +347,7 @@ func (sm *BlockProcessor) VerifyUncles(statedb *state.StateDB, block, parent *ty
// GetBlockReceipts returns the receipts beloniging to the block hash // GetBlockReceipts returns the receipts beloniging to the block hash
func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) types.Receipts { func (sm *BlockProcessor) GetBlockReceipts(bhash common.Hash) types.Receipts {
if block := sm.ChainManager().GetBlock(bhash); block != nil { if block := sm.BlockChain().GetBlock(bhash); block != nil {
return GetBlockReceipts(sm.chainDb, block.Hash()) return GetBlockReceipts(sm.chainDb, block.Hash())
} }

View File

@ -30,16 +30,16 @@ import (
"github.com/ethereum/go-ethereum/pow/ezp" "github.com/ethereum/go-ethereum/pow/ezp"
) )
func proc() (*BlockProcessor, *ChainManager) { func proc() (*BlockProcessor, *BlockChain) {
db, _ := ethdb.NewMemDatabase() db, _ := ethdb.NewMemDatabase()
var mux event.TypeMux var mux event.TypeMux
WriteTestNetGenesisBlock(db, 0) WriteTestNetGenesisBlock(db, 0)
chainMan, err := NewChainManager(db, thePow(), &mux) blockchain, err := NewBlockChain(db, thePow(), &mux)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
} }
return NewBlockProcessor(db, ezp.New(), chainMan, &mux), chainMan return NewBlockProcessor(db, ezp.New(), blockchain, &mux), blockchain
} }
func TestNumber(t *testing.T) { func TestNumber(t *testing.T) {

View File

@ -55,11 +55,9 @@ const (
blockCacheLimit = 256 blockCacheLimit = 256
maxFutureBlocks = 256 maxFutureBlocks = 256
maxTimeFutureBlocks = 30 maxTimeFutureBlocks = 30
checkpointLimit = 200
) )
type ChainManager struct { type BlockChain struct {
//eth EthManager
chainDb ethdb.Database chainDb ethdb.Database
processor types.BlockProcessor processor types.BlockProcessor
eventMux *event.TypeMux eventMux *event.TypeMux
@ -69,7 +67,6 @@ type ChainManager struct {
chainmu sync.RWMutex chainmu sync.RWMutex
tsmu sync.RWMutex tsmu sync.RWMutex
checkpoint int // checkpoint counts towards the new checkpoint
td *big.Int td *big.Int
currentBlock *types.Block currentBlock *types.Block
currentGasLimit *big.Int currentGasLimit *big.Int
@ -90,7 +87,7 @@ type ChainManager struct {
pow pow.PoW pow pow.PoW
} }
func NewChainManager(chainDb ethdb.Database, pow pow.PoW, mux *event.TypeMux) (*ChainManager, error) { func NewBlockChain(chainDb ethdb.Database, pow pow.PoW, mux *event.TypeMux) (*BlockChain, error) {
headerCache, _ := lru.New(headerCacheLimit) headerCache, _ := lru.New(headerCacheLimit)
bodyCache, _ := lru.New(bodyCacheLimit) bodyCache, _ := lru.New(bodyCacheLimit)
bodyRLPCache, _ := lru.New(bodyCacheLimit) bodyRLPCache, _ := lru.New(bodyCacheLimit)
@ -98,7 +95,7 @@ func NewChainManager(chainDb ethdb.Database, pow pow.PoW, mux *event.TypeMux) (*
blockCache, _ := lru.New(blockCacheLimit) blockCache, _ := lru.New(blockCacheLimit)
futureBlocks, _ := lru.New(maxFutureBlocks) futureBlocks, _ := lru.New(maxFutureBlocks)
bc := &ChainManager{ bc := &BlockChain{
chainDb: chainDb, chainDb: chainDb,
eventMux: mux, eventMux: mux,
quit: make(chan struct{}), quit: make(chan struct{}),
@ -144,7 +141,7 @@ func NewChainManager(chainDb ethdb.Database, pow pow.PoW, mux *event.TypeMux) (*
return bc, nil return bc, nil
} }
func (bc *ChainManager) SetHead(head *types.Block) { func (bc *BlockChain) SetHead(head *types.Block) {
bc.mu.Lock() bc.mu.Lock()
defer bc.mu.Unlock() defer bc.mu.Unlock()
@ -163,80 +160,55 @@ func (bc *ChainManager) SetHead(head *types.Block) {
bc.setLastState() bc.setLastState()
} }
func (self *ChainManager) Td() *big.Int { func (self *BlockChain) Td() *big.Int {
self.mu.RLock() self.mu.RLock()
defer self.mu.RUnlock() defer self.mu.RUnlock()
return new(big.Int).Set(self.td) return new(big.Int).Set(self.td)
} }
func (self *ChainManager) GasLimit() *big.Int { func (self *BlockChain) GasLimit() *big.Int {
self.mu.RLock() self.mu.RLock()
defer self.mu.RUnlock() defer self.mu.RUnlock()
return self.currentBlock.GasLimit() return self.currentBlock.GasLimit()
} }
func (self *ChainManager) LastBlockHash() common.Hash { func (self *BlockChain) LastBlockHash() common.Hash {
self.mu.RLock() self.mu.RLock()
defer self.mu.RUnlock() defer self.mu.RUnlock()
return self.currentBlock.Hash() return self.currentBlock.Hash()
} }
func (self *ChainManager) CurrentBlock() *types.Block { func (self *BlockChain) CurrentBlock() *types.Block {
self.mu.RLock() self.mu.RLock()
defer self.mu.RUnlock() defer self.mu.RUnlock()
return self.currentBlock return self.currentBlock
} }
func (self *ChainManager) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) { func (self *BlockChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
self.mu.RLock() self.mu.RLock()
defer self.mu.RUnlock() defer self.mu.RUnlock()
return new(big.Int).Set(self.td), self.currentBlock.Hash(), self.genesisBlock.Hash() return new(big.Int).Set(self.td), self.currentBlock.Hash(), self.genesisBlock.Hash()
} }
func (self *ChainManager) SetProcessor(proc types.BlockProcessor) { func (self *BlockChain) SetProcessor(proc types.BlockProcessor) {
self.processor = proc self.processor = proc
} }
func (self *ChainManager) State() *state.StateDB { func (self *BlockChain) State() *state.StateDB {
return state.New(self.CurrentBlock().Root(), self.chainDb) return state.New(self.CurrentBlock().Root(), self.chainDb)
} }
func (bc *ChainManager) recover() bool { func (bc *BlockChain) setLastState() error {
data, _ := bc.chainDb.Get([]byte("checkpoint"))
if len(data) != 0 {
block := bc.GetBlock(common.BytesToHash(data))
if block != nil {
if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil {
glog.Fatalf("failed to write database head number: %v", err)
}
if err := WriteHeadBlockHash(bc.chainDb, block.Hash()); err != nil {
glog.Fatalf("failed to write database head hash: %v", err)
}
bc.currentBlock = block
return true
}
}
return false
}
func (bc *ChainManager) setLastState() error {
head := GetHeadBlockHash(bc.chainDb) head := GetHeadBlockHash(bc.chainDb)
if head != (common.Hash{}) { if head != (common.Hash{}) {
block := bc.GetBlock(head) block := bc.GetBlock(head)
if block != nil { if block != nil {
bc.currentBlock = block bc.currentBlock = block
} else {
glog.Infof("LastBlock (%x) not found. Recovering...\n", head)
if bc.recover() {
glog.Infof("Recover successful")
} else {
glog.Fatalf("Recover failed. Please report")
}
} }
} else { } else {
bc.Reset() bc.Reset()
@ -252,13 +224,13 @@ func (bc *ChainManager) setLastState() error {
} }
// Reset purges the entire blockchain, restoring it to its genesis state. // Reset purges the entire blockchain, restoring it to its genesis state.
func (bc *ChainManager) Reset() { func (bc *BlockChain) Reset() {
bc.ResetWithGenesisBlock(bc.genesisBlock) bc.ResetWithGenesisBlock(bc.genesisBlock)
} }
// ResetWithGenesisBlock purges the entire blockchain, restoring it to the // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
// specified genesis state. // specified genesis state.
func (bc *ChainManager) ResetWithGenesisBlock(genesis *types.Block) { func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) {
bc.mu.Lock() bc.mu.Lock()
defer bc.mu.Unlock() defer bc.mu.Unlock()
@ -286,7 +258,7 @@ func (bc *ChainManager) ResetWithGenesisBlock(genesis *types.Block) {
} }
// Export writes the active chain to the given writer. // Export writes the active chain to the given writer.
func (self *ChainManager) Export(w io.Writer) error { func (self *BlockChain) Export(w io.Writer) error {
if err := self.ExportN(w, uint64(0), self.currentBlock.NumberU64()); err != nil { if err := self.ExportN(w, uint64(0), self.currentBlock.NumberU64()); err != nil {
return err return err
} }
@ -294,7 +266,7 @@ func (self *ChainManager) Export(w io.Writer) error {
} }
// ExportN writes a subset of the active chain to the given writer. // ExportN writes a subset of the active chain to the given writer.
func (self *ChainManager) ExportN(w io.Writer, first uint64, last uint64) error { func (self *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
self.mu.RLock() self.mu.RLock()
defer self.mu.RUnlock() defer self.mu.RUnlock()
@ -320,40 +292,28 @@ func (self *ChainManager) ExportN(w io.Writer, first uint64, last uint64) error
// insert injects a block into the current chain block chain. Note, this function // insert injects a block into the current chain block chain. Note, this function
// assumes that the `mu` mutex is held! // assumes that the `mu` mutex is held!
func (bc *ChainManager) insert(block *types.Block) { func (bc *BlockChain) insert(block *types.Block) {
// Add the block to the canonical chain number scheme and mark as the head // Add the block to the canonical chain number scheme and mark as the head
if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil { if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil {
glog.Fatalf("failed to insert block number: %v", err) glog.Fatalf("failed to insert block number: %v", err)
} }
if err := WriteHeadBlockHash(bc.chainDb, block.Hash()); err != nil {
glog.Fatalf("failed to insert block number: %v", err)
}
// Add a new restore point if we reached some limit
bc.checkpoint++
if bc.checkpoint > checkpointLimit {
if err := bc.chainDb.Put([]byte("checkpoint"), block.Hash().Bytes()); err != nil {
glog.Fatalf("failed to create checkpoint: %v", err)
}
bc.checkpoint = 0
}
// Update the internal internal state with the head block
bc.currentBlock = block bc.currentBlock = block
} }
// Accessors // Accessors
func (bc *ChainManager) Genesis() *types.Block { func (bc *BlockChain) Genesis() *types.Block {
return bc.genesisBlock return bc.genesisBlock
} }
// HasHeader checks if a block header is present in the database or not, caching // HasHeader checks if a block header is present in the database or not, caching
// it if present. // it if present.
func (bc *ChainManager) HasHeader(hash common.Hash) bool { func (bc *BlockChain) HasHeader(hash common.Hash) bool {
return bc.GetHeader(hash) != nil return bc.GetHeader(hash) != nil
} }
// GetHeader retrieves a block header from the database by hash, caching it if // GetHeader retrieves a block header from the database by hash, caching it if
// found. // found.
func (self *ChainManager) GetHeader(hash common.Hash) *types.Header { func (self *BlockChain) GetHeader(hash common.Hash) *types.Header {
// Short circuit if the header's already in the cache, retrieve otherwise // Short circuit if the header's already in the cache, retrieve otherwise
if header, ok := self.headerCache.Get(hash); ok { if header, ok := self.headerCache.Get(hash); ok {
return header.(*types.Header) return header.(*types.Header)
@ -369,7 +329,7 @@ func (self *ChainManager) GetHeader(hash common.Hash) *types.Header {
// GetHeaderByNumber retrieves a block header from the database by number, // GetHeaderByNumber retrieves a block header from the database by number,
// caching it (associated with its hash) if found. // caching it (associated with its hash) if found.
func (self *ChainManager) GetHeaderByNumber(number uint64) *types.Header { func (self *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
hash := GetCanonicalHash(self.chainDb, number) hash := GetCanonicalHash(self.chainDb, number)
if hash == (common.Hash{}) { if hash == (common.Hash{}) {
return nil return nil
@ -379,7 +339,7 @@ func (self *ChainManager) GetHeaderByNumber(number uint64) *types.Header {
// GetBody retrieves a block body (transactions and uncles) from the database by // GetBody retrieves a block body (transactions and uncles) from the database by
// hash, caching it if found. // hash, caching it if found.
func (self *ChainManager) GetBody(hash common.Hash) *types.Body { func (self *BlockChain) GetBody(hash common.Hash) *types.Body {
// Short circuit if the body's already in the cache, retrieve otherwise // Short circuit if the body's already in the cache, retrieve otherwise
if cached, ok := self.bodyCache.Get(hash); ok { if cached, ok := self.bodyCache.Get(hash); ok {
body := cached.(*types.Body) body := cached.(*types.Body)
@ -396,7 +356,7 @@ func (self *ChainManager) GetBody(hash common.Hash) *types.Body {
// GetBodyRLP retrieves a block body in RLP encoding from the database by hash, // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
// caching it if found. // caching it if found.
func (self *ChainManager) GetBodyRLP(hash common.Hash) rlp.RawValue { func (self *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
// Short circuit if the body's already in the cache, retrieve otherwise // Short circuit if the body's already in the cache, retrieve otherwise
if cached, ok := self.bodyRLPCache.Get(hash); ok { if cached, ok := self.bodyRLPCache.Get(hash); ok {
return cached.(rlp.RawValue) return cached.(rlp.RawValue)
@ -412,7 +372,7 @@ func (self *ChainManager) GetBodyRLP(hash common.Hash) rlp.RawValue {
// GetTd retrieves a block's total difficulty in the canonical chain from the // GetTd retrieves a block's total difficulty in the canonical chain from the
// database by hash, caching it if found. // database by hash, caching it if found.
func (self *ChainManager) GetTd(hash common.Hash) *big.Int { func (self *BlockChain) GetTd(hash common.Hash) *big.Int {
// Short circuit if the td's already in the cache, retrieve otherwise // Short circuit if the td's already in the cache, retrieve otherwise
if cached, ok := self.tdCache.Get(hash); ok { if cached, ok := self.tdCache.Get(hash); ok {
return cached.(*big.Int) return cached.(*big.Int)
@ -428,12 +388,12 @@ func (self *ChainManager) GetTd(hash common.Hash) *big.Int {
// HasBlock checks if a block is fully present in the database or not, caching // HasBlock checks if a block is fully present in the database or not, caching
// it if present. // it if present.
func (bc *ChainManager) HasBlock(hash common.Hash) bool { func (bc *BlockChain) HasBlock(hash common.Hash) bool {
return bc.GetBlock(hash) != nil return bc.GetBlock(hash) != nil
} }
// GetBlock retrieves a block from the database by hash, caching it if found. // GetBlock retrieves a block from the database by hash, caching it if found.
func (self *ChainManager) GetBlock(hash common.Hash) *types.Block { func (self *BlockChain) GetBlock(hash common.Hash) *types.Block {
// Short circuit if the block's already in the cache, retrieve otherwise // Short circuit if the block's already in the cache, retrieve otherwise
if block, ok := self.blockCache.Get(hash); ok { if block, ok := self.blockCache.Get(hash); ok {
return block.(*types.Block) return block.(*types.Block)
@ -449,7 +409,7 @@ func (self *ChainManager) GetBlock(hash common.Hash) *types.Block {
// GetBlockByNumber retrieves a block from the database by number, caching it // GetBlockByNumber retrieves a block from the database by number, caching it
// (associated with its hash) if found. // (associated with its hash) if found.
func (self *ChainManager) GetBlockByNumber(number uint64) *types.Block { func (self *BlockChain) GetBlockByNumber(number uint64) *types.Block {
hash := GetCanonicalHash(self.chainDb, number) hash := GetCanonicalHash(self.chainDb, number)
if hash == (common.Hash{}) { if hash == (common.Hash{}) {
return nil return nil
@ -459,7 +419,7 @@ func (self *ChainManager) GetBlockByNumber(number uint64) *types.Block {
// GetBlockHashesFromHash retrieves a number of block hashes starting at a given // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
// hash, fetching towards the genesis block. // hash, fetching towards the genesis block.
func (self *ChainManager) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { func (self *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
// Get the origin header from which to fetch // Get the origin header from which to fetch
header := self.GetHeader(hash) header := self.GetHeader(hash)
if header == nil { if header == nil {
@ -481,7 +441,7 @@ func (self *ChainManager) GetBlockHashesFromHash(hash common.Hash, max uint64) [
// [deprecated by eth/62] // [deprecated by eth/62]
// GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
func (self *ChainManager) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) { func (self *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
block := self.GetBlock(hash) block := self.GetBlock(hash)
if block == nil { if block == nil {
@ -493,7 +453,7 @@ func (self *ChainManager) GetBlocksFromHash(hash common.Hash, n int) (blocks []*
return return
} }
func (self *ChainManager) GetUnclesInChain(block *types.Block, length int) (uncles []*types.Header) { func (self *BlockChain) GetUnclesInChain(block *types.Block, length int) (uncles []*types.Header) {
for i := 0; block != nil && i < length; i++ { for i := 0; block != nil && i < length; i++ {
uncles = append(uncles, block.Uncles()...) uncles = append(uncles, block.Uncles()...)
block = self.GetBlock(block.ParentHash()) block = self.GetBlock(block.ParentHash())
@ -504,11 +464,11 @@ func (self *ChainManager) GetUnclesInChain(block *types.Block, length int) (uncl
// setTotalDifficulty updates the TD of the chain manager. Note, this function // setTotalDifficulty updates the TD of the chain manager. Note, this function
// assumes that the `mu` mutex is held! // assumes that the `mu` mutex is held!
func (bc *ChainManager) setTotalDifficulty(td *big.Int) { func (bc *BlockChain) setTotalDifficulty(td *big.Int) {
bc.td = new(big.Int).Set(td) bc.td = new(big.Int).Set(td)
} }
func (bc *ChainManager) Stop() { func (bc *BlockChain) Stop() {
if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) { if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
return return
} }
@ -527,7 +487,7 @@ type queueEvent struct {
splitCount int splitCount int
} }
func (self *ChainManager) procFutureBlocks() { func (self *BlockChain) procFutureBlocks() {
blocks := make([]*types.Block, self.futureBlocks.Len()) blocks := make([]*types.Block, self.futureBlocks.Len())
for i, hash := range self.futureBlocks.Keys() { for i, hash := range self.futureBlocks.Keys() {
block, _ := self.futureBlocks.Get(hash) block, _ := self.futureBlocks.Get(hash)
@ -549,7 +509,7 @@ const (
) )
// WriteBlock writes the block to the chain. // WriteBlock writes the block to the chain.
func (self *ChainManager) WriteBlock(block *types.Block) (status writeStatus, err error) { func (self *BlockChain) WriteBlock(block *types.Block) (status writeStatus, err error) {
self.wg.Add(1) self.wg.Add(1)
defer self.wg.Done() defer self.wg.Done()
@ -599,7 +559,7 @@ func (self *ChainManager) WriteBlock(block *types.Block) (status writeStatus, er
// InsertChain will attempt to insert the given chain in to the canonical chain or, otherwise, create a fork. It an error is returned // InsertChain will attempt to insert the given chain in to the canonical chain or, otherwise, create a fork. It an error is returned
// it will return the index number of the failing block as well an error describing what went wrong (for possible errors see core/errors.go). // it will return the index number of the failing block as well an error describing what went wrong (for possible errors see core/errors.go).
func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) { func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) {
self.wg.Add(1) self.wg.Add(1)
defer self.wg.Done() defer self.wg.Done()
@ -730,7 +690,7 @@ func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
// reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them // reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
// to be part of the new canonical chain and accumulates potential missing transactions and post an // to be part of the new canonical chain and accumulates potential missing transactions and post an
// event about them // event about them
func (self *ChainManager) reorg(oldBlock, newBlock *types.Block) error { func (self *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
self.mu.Lock() self.mu.Lock()
defer self.mu.Unlock() defer self.mu.Unlock()
@ -811,7 +771,7 @@ func (self *ChainManager) reorg(oldBlock, newBlock *types.Block) error {
return nil return nil
} }
func (self *ChainManager) update() { func (self *BlockChain) update() {
events := self.eventMux.Subscribe(queueEvent{}) events := self.eventMux.Subscribe(queueEvent{})
futureTimer := time.Tick(5 * time.Second) futureTimer := time.Tick(5 * time.Second)
out: out:

View File

@ -48,19 +48,19 @@ func thePow() pow.PoW {
return pow return pow
} }
func theChainManager(db ethdb.Database, t *testing.T) *ChainManager { func theBlockChain(db ethdb.Database, t *testing.T) *BlockChain {
var eventMux event.TypeMux var eventMux event.TypeMux
WriteTestNetGenesisBlock(db, 0) WriteTestNetGenesisBlock(db, 0)
chainMan, err := NewChainManager(db, thePow(), &eventMux) blockchain, err := NewBlockChain(db, thePow(), &eventMux)
if err != nil { if err != nil {
t.Error("failed creating chainmanager:", err) t.Error("failed creating chainmanager:", err)
t.FailNow() t.FailNow()
return nil return nil
} }
blockMan := NewBlockProcessor(db, nil, chainMan, &eventMux) blockMan := NewBlockProcessor(db, nil, blockchain, &eventMux)
chainMan.SetProcessor(blockMan) blockchain.SetProcessor(blockMan)
return chainMan return blockchain
} }
// Test fork of length N starting from block i // Test fork of length N starting from block i
@ -104,7 +104,7 @@ func testFork(t *testing.T, bman *BlockProcessor, i, N int, f func(td1, td2 *big
// Loop over parents making sure reconstruction is done properly // Loop over parents making sure reconstruction is done properly
} }
func printChain(bc *ChainManager) { func printChain(bc *BlockChain) {
for i := bc.CurrentBlock().Number().Uint64(); i > 0; i-- { for i := bc.CurrentBlock().Number().Uint64(); i > 0; i-- {
b := bc.GetBlockByNumber(uint64(i)) b := bc.GetBlockByNumber(uint64(i))
fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty()) fmt.Printf("\t%x %v\n", b.Hash(), b.Difficulty())
@ -144,8 +144,8 @@ func loadChain(fn string, t *testing.T) (types.Blocks, error) {
return chain, nil return chain, nil
} }
func insertChain(done chan bool, chainMan *ChainManager, chain types.Blocks, t *testing.T) { func insertChain(done chan bool, blockchain *BlockChain, chain types.Blocks, t *testing.T) {
_, err := chainMan.InsertChain(chain) _, err := blockchain.InsertChain(chain)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
t.FailNow() t.FailNow()
@ -294,23 +294,23 @@ func TestChainInsertions(t *testing.T) {
t.FailNow() t.FailNow()
} }
chainMan := theChainManager(db, t) blockchain := theBlockChain(db, t)
const max = 2 const max = 2
done := make(chan bool, max) done := make(chan bool, max)
go insertChain(done, chainMan, chain1, t) go insertChain(done, blockchain, chain1, t)
go insertChain(done, chainMan, chain2, t) go insertChain(done, blockchain, chain2, t)
for i := 0; i < max; i++ { for i := 0; i < max; i++ {
<-done <-done
} }
if chain2[len(chain2)-1].Hash() != chainMan.CurrentBlock().Hash() { if chain2[len(chain2)-1].Hash() != blockchain.CurrentBlock().Hash() {
t.Error("chain2 is canonical and shouldn't be") t.Error("chain2 is canonical and shouldn't be")
} }
if chain1[len(chain1)-1].Hash() != chainMan.CurrentBlock().Hash() { if chain1[len(chain1)-1].Hash() != blockchain.CurrentBlock().Hash() {
t.Error("chain1 isn't canonical and should be") t.Error("chain1 isn't canonical and should be")
} }
} }
@ -337,7 +337,7 @@ func TestChainMultipleInsertions(t *testing.T) {
} }
} }
chainMan := theChainManager(db, t) blockchain := theBlockChain(db, t)
done := make(chan bool, max) done := make(chan bool, max)
for i, chain := range chains { for i, chain := range chains {
@ -345,7 +345,7 @@ func TestChainMultipleInsertions(t *testing.T) {
i := i i := i
chain := chain chain := chain
go func() { go func() {
insertChain(done, chainMan, chain, t) insertChain(done, blockchain, chain, t)
fmt.Println(i, "done") fmt.Println(i, "done")
}() }()
} }
@ -354,7 +354,7 @@ func TestChainMultipleInsertions(t *testing.T) {
<-done <-done
} }
if chains[longest][len(chains[longest])-1].Hash() != chainMan.CurrentBlock().Hash() { if chains[longest][len(chains[longest])-1].Hash() != blockchain.CurrentBlock().Hash() {
t.Error("Invalid canonical chain") t.Error("Invalid canonical chain")
} }
} }
@ -382,9 +382,9 @@ func makeChainWithDiff(genesis *types.Block, d []int, seed byte) []*types.Block
return chain return chain
} }
func chm(genesis *types.Block, db ethdb.Database) *ChainManager { func chm(genesis *types.Block, db ethdb.Database) *BlockChain {
var eventMux event.TypeMux var eventMux event.TypeMux
bc := &ChainManager{chainDb: db, genesisBlock: genesis, eventMux: &eventMux, pow: FakePow{}} bc := &BlockChain{chainDb: db, genesisBlock: genesis, eventMux: &eventMux, pow: FakePow{}}
bc.headerCache, _ = lru.New(100) bc.headerCache, _ = lru.New(100)
bc.bodyCache, _ = lru.New(100) bc.bodyCache, _ = lru.New(100)
bc.bodyRLPCache, _ = lru.New(100) bc.bodyRLPCache, _ = lru.New(100)
@ -459,7 +459,7 @@ func TestReorgBadHashes(t *testing.T) {
BadHashes[chain[3].Header().Hash()] = true BadHashes[chain[3].Header().Hash()] = true
var eventMux event.TypeMux var eventMux event.TypeMux
ncm, err := NewChainManager(db, FakePow{}, &eventMux) ncm, err := NewBlockChain(db, FakePow{}, &eventMux)
if err != nil { if err != nil {
t.Errorf("NewChainManager err: %s", err) t.Errorf("NewChainManager err: %s", err)
} }
@ -593,7 +593,7 @@ func TestChainTxReorgs(t *testing.T) {
}) })
// Import the chain. This runs all block validation rules. // Import the chain. This runs all block validation rules.
evmux := &event.TypeMux{} evmux := &event.TypeMux{}
chainman, _ := NewChainManager(db, FakePow{}, evmux) chainman, _ := NewBlockChain(db, FakePow{}, evmux)
chainman.SetProcessor(NewBlockProcessor(db, FakePow{}, chainman, evmux)) chainman.SetProcessor(NewBlockProcessor(db, FakePow{}, chainman, evmux))
if i, err := chainman.InsertChain(chain); err != nil { if i, err := chainman.InsertChain(chain); err != nil {
t.Fatalf("failed to insert original chain[%d]: %v", i, err) t.Fatalf("failed to insert original chain[%d]: %v", i, err)

View File

@ -153,7 +153,7 @@ func (b *BlockGen) OffsetTime(seconds int64) {
// and their coinbase will be the zero address. // and their coinbase will be the zero address.
// //
// Blocks created by GenerateChain do not contain valid proof of work // Blocks created by GenerateChain do not contain valid proof of work
// values. Inserting them into ChainManager requires use of FakePow or // values. Inserting them into BlockChain requires use of FakePow or
// a similar non-validating proof of work implementation. // a similar non-validating proof of work implementation.
func GenerateChain(parent *types.Block, db ethdb.Database, n int, gen func(int, *BlockGen)) []*types.Block { func GenerateChain(parent *types.Block, db ethdb.Database, n int, gen func(int, *BlockGen)) []*types.Block {
statedb := state.New(parent.Root(), db) statedb := state.New(parent.Root(), db)
@ -205,7 +205,7 @@ func newCanonical(n int, db ethdb.Database) (*BlockProcessor, error) {
evmux := &event.TypeMux{} evmux := &event.TypeMux{}
WriteTestNetGenesisBlock(db, 0) WriteTestNetGenesisBlock(db, 0)
chainman, _ := NewChainManager(db, FakePow{}, evmux) chainman, _ := NewBlockChain(db, FakePow{}, evmux)
bman := NewBlockProcessor(db, FakePow{}, chainman, evmux) bman := NewBlockProcessor(db, FakePow{}, chainman, evmux)
bman.bc.SetProcessor(bman) bman.bc.SetProcessor(bman)
parent := bman.bc.CurrentBlock() parent := bman.bc.CurrentBlock()

View File

@ -77,7 +77,7 @@ func ExampleGenerateChain() {
// Import the chain. This runs all block validation rules. // Import the chain. This runs all block validation rules.
evmux := &event.TypeMux{} evmux := &event.TypeMux{}
chainman, _ := NewChainManager(db, FakePow{}, evmux) chainman, _ := NewBlockChain(db, FakePow{}, evmux)
chainman.SetProcessor(NewBlockProcessor(db, FakePow{}, chainman, evmux)) chainman.SetProcessor(NewBlockProcessor(db, FakePow{}, chainman, evmux))
if i, err := chainman.InsertChain(chain); err != nil { if i, err := chainman.InsertChain(chain); err != nil {
fmt.Printf("insert error (block %d): %v\n", i, err) fmt.Printf("insert error (block %d): %v\n", i, err)

View File

@ -34,7 +34,7 @@ type TestManager struct {
db ethdb.Database db ethdb.Database
txPool *TxPool txPool *TxPool
blockChain *ChainManager blockChain *BlockChain
Blocks []*types.Block Blocks []*types.Block
} }
@ -54,7 +54,7 @@ func (s *TestManager) Peers() *list.List {
return list.New() return list.New()
} }
func (s *TestManager) ChainManager() *ChainManager { func (s *TestManager) BlockChain() *BlockChain {
return s.blockChain return s.blockChain
} }
@ -89,7 +89,7 @@ func NewTestManager() *TestManager {
testManager.eventMux = new(event.TypeMux) testManager.eventMux = new(event.TypeMux)
testManager.db = db testManager.db = db
// testManager.txPool = NewTxPool(testManager) // testManager.txPool = NewTxPool(testManager)
// testManager.blockChain = NewChainManager(testManager) // testManager.blockChain = NewBlockChain(testManager)
// testManager.stateManager = NewStateManager(testManager) // testManager.stateManager = NewStateManager(testManager)
return testManager return testManager

View File

@ -26,7 +26,7 @@ import (
type Backend interface { type Backend interface {
AccountManager() *accounts.Manager AccountManager() *accounts.Manager
BlockProcessor() *BlockProcessor BlockProcessor() *BlockProcessor
ChainManager() *ChainManager BlockChain() *BlockChain
TxPool() *TxPool TxPool() *TxPool
ChainDb() ethdb.Database ChainDb() ethdb.Database
DappDb() ethdb.Database DappDb() ethdb.Database

View File

@ -38,7 +38,7 @@ const (
) )
var ( var (
Pow256 = common.BigPow(2, 256) // Pew256 is 2**256 Pow256 = common.BigPow(2, 256) // Pow256 is 2**256
U256 = common.U256 // Shortcut to common.U256 U256 = common.U256 // Shortcut to common.U256
S256 = common.S256 // Shortcut to common.S256 S256 = common.S256 // Shortcut to common.S256
@ -46,7 +46,7 @@ var (
Zero = common.Big0 // Shortcut to common.Big0 Zero = common.Big0 // Shortcut to common.Big0
One = common.Big1 // Shortcut to common.Big1 One = common.Big1 // Shortcut to common.Big1
max = big.NewInt(math.MaxInt64) // Maximum 256 bit integer max = big.NewInt(math.MaxInt64) // Maximum 64 bit integer
) )
// NewVm returns a new VM based on the Environment // NewVm returns a new VM based on the Environment

View File

@ -118,8 +118,8 @@ func (self *Contract) SetCode(code []byte) {
self.Code = code self.Code = code
} }
// SetCallCode sets the address of the code address and sets the code // SetCallCode sets the code of the contract and address of the backing data
// of the contract according to the backing database. // object
func (self *Contract) SetCallCode(addr *common.Address, code []byte) { func (self *Contract) SetCallCode(addr *common.Address, code []byte) {
self.Code = code self.Code = code
self.CodeAddr = addr self.CodeAddr = addr

View File

@ -18,15 +18,15 @@
Package vm implements the Ethereum Virtual Machine. Package vm implements the Ethereum Virtual Machine.
The vm package implements two EVMs, a byte code VM and a JIT VM. The BC The vm package implements two EVMs, a byte code VM and a JIT VM. The BC
(Byte Code) VM loops over a set of bytes and executes them according to a set (Byte Code) VM loops over a set of bytes and executes them according to the set
of rules defined in the Ethereum yellow paper. When the BC VM is invokes it of rules defined in the Ethereum yellow paper. When the BC VM is invoked it
invokes the JIT VM in a seperate goroutine and compiles the byte code in JIT invokes the JIT VM in a seperate goroutine and compiles the byte code in JIT
instructions. instructions.
The JIT VM, when invoked, loops around a set of pre-defined instructions until The JIT VM, when invoked, loops around a set of pre-defined instructions until
it either runs of gas, causes an internel error, returns or stops. At a later it either runs of gas, causes an internal error, returns or stops. At a later
stage the JIT VM will see some additional features that will cause sets of stage the JIT VM will see some additional features that will cause sets of
instructions to be compiled down to segments. Segments are sets of instructions instructions to be compiled down to segments. Segments are sets of instructions
that can be ran in one go saving precious time during execution. that can be run in one go saving precious time during execution.
*/ */
package vm package vm

View File

@ -26,7 +26,7 @@ import (
// it's own isolated environment. // it's own isolated environment.
// Environment is an EVM requirement and helper which allows access to outside // Environment is an EVM requirement and helper which allows access to outside
// information such like states. // information such as states.
type Environment interface { type Environment interface {
// The state database // The state database
Db() Database Db() Database
@ -50,7 +50,7 @@ type Environment interface {
GasLimit() *big.Int GasLimit() *big.Int
// Determines whether it's possible to transact // Determines whether it's possible to transact
CanTransfer(from common.Address, balance *big.Int) bool CanTransfer(from common.Address, balance *big.Int) bool
// Transfer from to to with amount set // Transfers amount from one account to the other
Transfer(from, to Account, amount *big.Int) error Transfer(from, to Account, amount *big.Int) error
// Adds a LOG to the state // Adds a LOG to the state
AddLog(*Log) AddLog(*Log)

View File

@ -18,7 +18,7 @@ package vm
import "fmt" import "fmt"
// Memory implements ethereum RAM backed by a simple byte slice // Memory implements a simple memory model for the ethereum virtual machine.
type Memory struct { type Memory struct {
store []byte store []byte
} }

View File

@ -30,13 +30,13 @@ type VMEnv struct {
header *types.Header header *types.Header
msg Message msg Message
depth int depth int
chain *ChainManager chain *BlockChain
typ vm.Type typ vm.Type
// structured logging // structured logging
logs []vm.StructLog logs []vm.StructLog
} }
func NewEnv(state *state.StateDB, chain *ChainManager, msg Message, header *types.Header) *VMEnv { func NewEnv(state *state.StateDB, chain *BlockChain, msg Message, header *types.Header) *VMEnv {
return &VMEnv{ return &VMEnv{
chain: chain, chain: chain,
state: state, state: state,

View File

@ -217,7 +217,7 @@ type Ethereum struct {
// State manager for processing new blocks and managing the over all states // State manager for processing new blocks and managing the over all states
blockProcessor *core.BlockProcessor blockProcessor *core.BlockProcessor
txPool *core.TxPool txPool *core.TxPool
chainManager *core.ChainManager blockchain *core.BlockChain
accountManager *accounts.Manager accountManager *accounts.Manager
whisper *whisper.Whisper whisper *whisper.Whisper
pow *ethash.Ethash pow *ethash.Ethash
@ -365,7 +365,7 @@ func New(config *Config) (*Ethereum, error) {
eth.pow = ethash.New() eth.pow = ethash.New()
} }
//genesis := core.GenesisBlock(uint64(config.GenesisNonce), stateDb) //genesis := core.GenesisBlock(uint64(config.GenesisNonce), stateDb)
eth.chainManager, err = core.NewChainManager(chainDb, eth.pow, eth.EventMux()) eth.blockchain, err = core.NewBlockChain(chainDb, eth.pow, eth.EventMux())
if err != nil { if err != nil {
if err == core.ErrNoGenesis { if err == core.ErrNoGenesis {
return nil, fmt.Errorf(`Genesis block not found. Please supply a genesis block with the "--genesis /path/to/file" argument`) return nil, fmt.Errorf(`Genesis block not found. Please supply a genesis block with the "--genesis /path/to/file" argument`)
@ -373,11 +373,11 @@ func New(config *Config) (*Ethereum, error) {
return nil, err return nil, err
} }
eth.txPool = core.NewTxPool(eth.EventMux(), eth.chainManager.State, eth.chainManager.GasLimit) eth.txPool = core.NewTxPool(eth.EventMux(), eth.blockchain.State, eth.blockchain.GasLimit)
eth.blockProcessor = core.NewBlockProcessor(chainDb, eth.pow, eth.chainManager, eth.EventMux()) eth.blockProcessor = core.NewBlockProcessor(chainDb, eth.pow, eth.blockchain, eth.EventMux())
eth.chainManager.SetProcessor(eth.blockProcessor) eth.blockchain.SetProcessor(eth.blockProcessor)
eth.protocolManager = NewProtocolManager(config.NetworkId, eth.eventMux, eth.txPool, eth.pow, eth.chainManager, chainDb) eth.protocolManager = NewProtocolManager(config.NetworkId, eth.eventMux, eth.txPool, eth.pow, eth.blockchain, chainDb)
eth.miner = miner.New(eth, eth.EventMux(), eth.pow) eth.miner = miner.New(eth, eth.EventMux(), eth.pow)
eth.miner.SetGasPrice(config.GasPrice) eth.miner.SetGasPrice(config.GasPrice)
@ -441,7 +441,7 @@ func (s *Ethereum) NodeInfo() *NodeInfo {
DiscPort: int(node.UDP), DiscPort: int(node.UDP),
TCPPort: int(node.TCP), TCPPort: int(node.TCP),
ListenAddr: s.net.ListenAddr, ListenAddr: s.net.ListenAddr,
Td: s.ChainManager().Td().String(), Td: s.BlockChain().Td().String(),
} }
} }
@ -478,7 +478,7 @@ func (s *Ethereum) PeersInfo() (peersinfo []*PeerInfo) {
} }
func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) { func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
s.chainManager.ResetWithGenesisBlock(gb) s.blockchain.ResetWithGenesisBlock(gb)
} }
func (s *Ethereum) StartMining(threads int) error { func (s *Ethereum) StartMining(threads int) error {
@ -518,7 +518,7 @@ func (s *Ethereum) Miner() *miner.Miner { return s.miner }
// func (s *Ethereum) Logger() logger.LogSystem { return s.logger } // func (s *Ethereum) Logger() logger.LogSystem { return s.logger }
func (s *Ethereum) Name() string { return s.net.Name } func (s *Ethereum) Name() string { return s.net.Name }
func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager } func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
func (s *Ethereum) ChainManager() *core.ChainManager { return s.chainManager } func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
func (s *Ethereum) BlockProcessor() *core.BlockProcessor { return s.blockProcessor } func (s *Ethereum) BlockProcessor() *core.BlockProcessor { return s.blockProcessor }
func (s *Ethereum) TxPool() *core.TxPool { return s.txPool } func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
func (s *Ethereum) Whisper() *whisper.Whisper { return s.whisper } func (s *Ethereum) Whisper() *whisper.Whisper { return s.whisper }
@ -581,7 +581,7 @@ func (self *Ethereum) AddPeer(nodeURL string) error {
func (s *Ethereum) Stop() { func (s *Ethereum) Stop() {
s.net.Stop() s.net.Stop()
s.chainManager.Stop() s.blockchain.Stop()
s.protocolManager.Stop() s.protocolManager.Stop()
s.txPool.Stop() s.txPool.Stop()
s.eventMux.Stop() s.eventMux.Stop()
@ -622,7 +622,7 @@ func (self *Ethereum) StartAutoDAG() {
select { select {
case <-timer: case <-timer:
glog.V(logger.Info).Infof("checking DAG (ethash dir: %s)", ethash.DefaultDir) glog.V(logger.Info).Infof("checking DAG (ethash dir: %s)", ethash.DefaultDir)
currentBlock := self.ChainManager().CurrentBlock().NumberU64() currentBlock := self.BlockChain().CurrentBlock().NumberU64()
thisEpoch := currentBlock / epochLength thisEpoch := currentBlock / epochLength
if nextEpoch <= thisEpoch { if nextEpoch <= thisEpoch {
if currentBlock%epochLength > autoDAGepochHeight { if currentBlock%epochLength > autoDAGepochHeight {

View File

@ -1,4 +1,4 @@
// Copyright 2014 The go-ethereum Authors // Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library. // This file is part of the go-ethereum library.
// //
// The go-ethereum library is free software: you can redistribute it and/or modify // The go-ethereum library is free software: you can redistribute it and/or modify
@ -23,6 +23,7 @@ import (
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/ethdb"
) )
type AccountChange struct { type AccountChange struct {
@ -31,7 +32,7 @@ type AccountChange struct {
// Filtering interface // Filtering interface
type Filter struct { type Filter struct {
db common.Database db ethdb.Database
earliest int64 earliest int64
latest int64 latest int64
skip int skip int
@ -46,7 +47,7 @@ type Filter struct {
// Create a new filter which uses a bloom filter on blocks to figure out whether a particular block // Create a new filter which uses a bloom filter on blocks to figure out whether a particular block
// is interesting or not. // is interesting or not.
func New(db common.Database) *Filter { func New(db ethdb.Database) *Filter {
return &Filter{db: db} return &Filter{db: db}
} }
@ -79,7 +80,7 @@ func (self *Filter) SetSkip(skip int) {
// Run filters logs with the current parameters set // Run filters logs with the current parameters set
func (self *Filter) Find() vm.Logs { func (self *Filter) Find() vm.Logs {
earliestBlock := core.GetCurrentBlock(self.db) earliestBlock := core.GetBlock(self.db, core.GetHeadBlockHash(self.db))
var earliestBlockNo uint64 = uint64(self.earliest) var earliestBlockNo uint64 = uint64(self.earliest)
if self.earliest == -1 { if self.earliest == -1 {
earliestBlockNo = earliestBlock.NumberU64() earliestBlockNo = earliestBlock.NumberU64()
@ -91,8 +92,12 @@ func (self *Filter) Find() vm.Logs {
var ( var (
logs vm.Logs logs vm.Logs
block = core.GetBlockByNumber(self.db, latestBlockNo) block *types.Block
) )
hash := core.GetCanonicalHash(self.db, latestBlockNo)
if hash != (common.Hash{}) {
block = core.GetBlock(self.db, hash)
}
done: done:
for i := 0; block != nil; i++ { for i := 0; block != nil; i++ {
@ -120,7 +125,7 @@ done:
logs = append(logs, self.FilterLogs(unfiltered)...) logs = append(logs, self.FilterLogs(unfiltered)...)
} }
block = core.GetBlockByHash(self.db, block.ParentHash()) block = core.GetBlock(self.db, block.ParentHash())
} }
skip := int(math.Min(float64(len(logs)), float64(self.skip))) skip := int(math.Min(float64(len(logs)), float64(self.skip)))

View File

@ -28,7 +28,7 @@ import (
// FilterSystem manages filters that filter specific events such as // FilterSystem manages filters that filter specific events such as
// block, transaction and log events. The Filtering system can be used to listen // block, transaction and log events. The Filtering system can be used to listen
// for specific LOG events fires by the EVM (Ethereum Virtual Machine). // for specific LOG events fired by the EVM (Ethereum Virtual Machine).
type FilterSystem struct { type FilterSystem struct {
eventMux *event.TypeMux eventMux *event.TypeMux

View File

@ -36,7 +36,7 @@ type blockPriceInfo struct {
type GasPriceOracle struct { type GasPriceOracle struct {
eth *Ethereum eth *Ethereum
chain *core.ChainManager chain *core.BlockChain
events event.Subscription events event.Subscription
blocks map[uint64]*blockPriceInfo blocks map[uint64]*blockPriceInfo
firstProcessed, lastProcessed uint64 firstProcessed, lastProcessed uint64
@ -48,7 +48,7 @@ func NewGasPriceOracle(eth *Ethereum) (self *GasPriceOracle) {
self = &GasPriceOracle{} self = &GasPriceOracle{}
self.blocks = make(map[uint64]*blockPriceInfo) self.blocks = make(map[uint64]*blockPriceInfo)
self.eth = eth self.eth = eth
self.chain = eth.chainManager self.chain = eth.blockchain
self.events = eth.EventMux().Subscribe( self.events = eth.EventMux().Subscribe(
core.ChainEvent{}, core.ChainEvent{},
core.ChainSplitEvent{}, core.ChainSplitEvent{},

View File

@ -60,9 +60,9 @@ func (ep extProt) GetHashes(hash common.Hash) error { return ep.getHashes(has
func (ep extProt) GetBlock(hashes []common.Hash) error { return ep.getBlocks(hashes) } func (ep extProt) GetBlock(hashes []common.Hash) error { return ep.getBlocks(hashes) }
type ProtocolManager struct { type ProtocolManager struct {
txpool txPool txpool txPool
chainman *core.ChainManager blockchain *core.BlockChain
chaindb ethdb.Database chaindb ethdb.Database
downloader *downloader.Downloader downloader *downloader.Downloader
fetcher *fetcher.Fetcher fetcher *fetcher.Fetcher
@ -87,17 +87,17 @@ type ProtocolManager struct {
// NewProtocolManager returns a new ethereum sub protocol manager. The Ethereum sub protocol manages peers capable // NewProtocolManager returns a new ethereum sub protocol manager. The Ethereum sub protocol manages peers capable
// with the ethereum network. // with the ethereum network.
func NewProtocolManager(networkId int, mux *event.TypeMux, txpool txPool, pow pow.PoW, chainman *core.ChainManager, chaindb ethdb.Database) *ProtocolManager { func NewProtocolManager(networkId int, mux *event.TypeMux, txpool txPool, pow pow.PoW, blockchain *core.BlockChain, chaindb ethdb.Database) *ProtocolManager {
// Create the protocol manager with the base fields // Create the protocol manager with the base fields
manager := &ProtocolManager{ manager := &ProtocolManager{
eventMux: mux, eventMux: mux,
txpool: txpool, txpool: txpool,
chainman: chainman, blockchain: blockchain,
chaindb: chaindb, chaindb: chaindb,
peers: newPeerSet(), peers: newPeerSet(),
newPeerCh: make(chan *peer, 1), newPeerCh: make(chan *peer, 1),
txsyncCh: make(chan *txsync), txsyncCh: make(chan *txsync),
quitSync: make(chan struct{}), quitSync: make(chan struct{}),
} }
// Initiate a sub-protocol for every implemented version we can handle // Initiate a sub-protocol for every implemented version we can handle
manager.SubProtocols = make([]p2p.Protocol, len(ProtocolVersions)) manager.SubProtocols = make([]p2p.Protocol, len(ProtocolVersions))
@ -116,15 +116,15 @@ func NewProtocolManager(networkId int, mux *event.TypeMux, txpool txPool, pow po
} }
} }
// Construct the different synchronisation mechanisms // Construct the different synchronisation mechanisms
manager.downloader = downloader.New(manager.eventMux, manager.chainman.HasBlock, manager.chainman.GetBlock, manager.chainman.CurrentBlock, manager.chainman.GetTd, manager.chainman.InsertChain, manager.removePeer) manager.downloader = downloader.New(manager.eventMux, manager.blockchain.HasBlock, manager.blockchain.GetBlock, manager.blockchain.CurrentBlock, manager.blockchain.GetTd, manager.blockchain.InsertChain, manager.removePeer)
validator := func(block *types.Block, parent *types.Block) error { validator := func(block *types.Block, parent *types.Block) error {
return core.ValidateHeader(pow, block.Header(), parent.Header(), true, false) return core.ValidateHeader(pow, block.Header(), parent.Header(), true, false)
} }
heighter := func() uint64 { heighter := func() uint64 {
return manager.chainman.CurrentBlock().NumberU64() return manager.blockchain.CurrentBlock().NumberU64()
} }
manager.fetcher = fetcher.New(manager.chainman.GetBlock, validator, manager.BroadcastBlock, heighter, manager.chainman.InsertChain, manager.removePeer) manager.fetcher = fetcher.New(manager.blockchain.GetBlock, validator, manager.BroadcastBlock, heighter, manager.blockchain.InsertChain, manager.removePeer)
return manager return manager
} }
@ -187,7 +187,7 @@ func (pm *ProtocolManager) handle(p *peer) error {
glog.V(logger.Debug).Infof("%v: peer connected [%s]", p, p.Name()) glog.V(logger.Debug).Infof("%v: peer connected [%s]", p, p.Name())
// Execute the Ethereum handshake // Execute the Ethereum handshake
td, head, genesis := pm.chainman.Status() td, head, genesis := pm.blockchain.Status()
if err := p.Handshake(td, head, genesis); err != nil { if err := p.Handshake(td, head, genesis); err != nil {
glog.V(logger.Debug).Infof("%v: handshake failed: %v", p, err) glog.V(logger.Debug).Infof("%v: handshake failed: %v", p, err)
return err return err
@ -252,7 +252,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
request.Amount = uint64(downloader.MaxHashFetch) request.Amount = uint64(downloader.MaxHashFetch)
} }
// Retrieve the hashes from the block chain and return them // Retrieve the hashes from the block chain and return them
hashes := pm.chainman.GetBlockHashesFromHash(request.Hash, request.Amount) hashes := pm.blockchain.GetBlockHashesFromHash(request.Hash, request.Amount)
if len(hashes) == 0 { if len(hashes) == 0 {
glog.V(logger.Debug).Infof("invalid block hash %x", request.Hash.Bytes()[:4]) glog.V(logger.Debug).Infof("invalid block hash %x", request.Hash.Bytes()[:4])
} }
@ -268,9 +268,9 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
request.Amount = uint64(downloader.MaxHashFetch) request.Amount = uint64(downloader.MaxHashFetch)
} }
// Calculate the last block that should be retrieved, and short circuit if unavailable // Calculate the last block that should be retrieved, and short circuit if unavailable
last := pm.chainman.GetBlockByNumber(request.Number + request.Amount - 1) last := pm.blockchain.GetBlockByNumber(request.Number + request.Amount - 1)
if last == nil { if last == nil {
last = pm.chainman.CurrentBlock() last = pm.blockchain.CurrentBlock()
request.Amount = last.NumberU64() - request.Number + 1 request.Amount = last.NumberU64() - request.Number + 1
} }
if last.NumberU64() < request.Number { if last.NumberU64() < request.Number {
@ -278,7 +278,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
} }
// Retrieve the hashes from the last block backwards, reverse and return // Retrieve the hashes from the last block backwards, reverse and return
hashes := []common.Hash{last.Hash()} hashes := []common.Hash{last.Hash()}
hashes = append(hashes, pm.chainman.GetBlockHashesFromHash(last.Hash(), request.Amount-1)...) hashes = append(hashes, pm.blockchain.GetBlockHashesFromHash(last.Hash(), request.Amount-1)...)
for i := 0; i < len(hashes)/2; i++ { for i := 0; i < len(hashes)/2; i++ {
hashes[i], hashes[len(hashes)-1-i] = hashes[len(hashes)-1-i], hashes[i] hashes[i], hashes[len(hashes)-1-i] = hashes[len(hashes)-1-i], hashes[i]
@ -318,7 +318,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
return errResp(ErrDecode, "msg %v: %v", msg, err) return errResp(ErrDecode, "msg %v: %v", msg, err)
} }
// Retrieve the requested block, stopping if enough was found // Retrieve the requested block, stopping if enough was found
if block := pm.chainman.GetBlock(hash); block != nil { if block := pm.blockchain.GetBlock(hash); block != nil {
blocks = append(blocks, block) blocks = append(blocks, block)
bytes += block.Size() bytes += block.Size()
} }
@ -358,9 +358,9 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
// Retrieve the next header satisfying the query // Retrieve the next header satisfying the query
var origin *types.Header var origin *types.Header
if query.Origin.Hash != (common.Hash{}) { if query.Origin.Hash != (common.Hash{}) {
origin = pm.chainman.GetHeader(query.Origin.Hash) origin = pm.blockchain.GetHeader(query.Origin.Hash)
} else { } else {
origin = pm.chainman.GetHeaderByNumber(query.Origin.Number) origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number)
} }
if origin == nil { if origin == nil {
break break
@ -373,7 +373,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
case query.Origin.Hash != (common.Hash{}) && query.Reverse: case query.Origin.Hash != (common.Hash{}) && query.Reverse:
// Hash based traversal towards the genesis block // Hash based traversal towards the genesis block
for i := 0; i < int(query.Skip)+1; i++ { for i := 0; i < int(query.Skip)+1; i++ {
if header := pm.chainman.GetHeader(query.Origin.Hash); header != nil { if header := pm.blockchain.GetHeader(query.Origin.Hash); header != nil {
query.Origin.Hash = header.ParentHash query.Origin.Hash = header.ParentHash
} else { } else {
unknown = true unknown = true
@ -382,8 +382,8 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
} }
case query.Origin.Hash != (common.Hash{}) && !query.Reverse: case query.Origin.Hash != (common.Hash{}) && !query.Reverse:
// Hash based traversal towards the leaf block // Hash based traversal towards the leaf block
if header := pm.chainman.GetHeaderByNumber(origin.Number.Uint64() + query.Skip + 1); header != nil { if header := pm.blockchain.GetHeaderByNumber(origin.Number.Uint64() + query.Skip + 1); header != nil {
if pm.chainman.GetBlockHashesFromHash(header.Hash(), query.Skip+1)[query.Skip] == query.Origin.Hash { if pm.blockchain.GetBlockHashesFromHash(header.Hash(), query.Skip+1)[query.Skip] == query.Origin.Hash {
query.Origin.Hash = header.Hash() query.Origin.Hash = header.Hash()
} else { } else {
unknown = true unknown = true
@ -466,7 +466,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
return errResp(ErrDecode, "msg %v: %v", msg, err) return errResp(ErrDecode, "msg %v: %v", msg, err)
} }
// Retrieve the requested block body, stopping if enough was found // Retrieve the requested block body, stopping if enough was found
if data := pm.chainman.GetBodyRLP(hash); len(data) != 0 { if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 {
bodies = append(bodies, data) bodies = append(bodies, data)
bytes += len(data) bytes += len(data)
} }
@ -562,7 +562,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
// Schedule all the unknown hashes for retrieval // Schedule all the unknown hashes for retrieval
unknown := make([]announce, 0, len(announces)) unknown := make([]announce, 0, len(announces))
for _, block := range announces { for _, block := range announces {
if !pm.chainman.HasBlock(block.Hash) { if !pm.blockchain.HasBlock(block.Hash) {
unknown = append(unknown, block) unknown = append(unknown, block)
} }
} }
@ -586,7 +586,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
request.Block.ReceivedAt = msg.ReceivedAt request.Block.ReceivedAt = msg.ReceivedAt
// Mark the block's arrival for whatever reason // Mark the block's arrival for whatever reason
_, chainHead, _ := pm.chainman.Status() _, chainHead, _ := pm.blockchain.Status()
jsonlogger.LogJson(&logger.EthChainReceivedNewBlock{ jsonlogger.LogJson(&logger.EthChainReceivedNewBlock{
BlockHash: request.Block.Hash().Hex(), BlockHash: request.Block.Hash().Hex(),
BlockNumber: request.Block.Number(), BlockNumber: request.Block.Number(),
@ -603,7 +603,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
// Update the peers total difficulty if needed, schedule a download if gapped // Update the peers total difficulty if needed, schedule a download if gapped
if request.TD.Cmp(p.Td()) > 0 { if request.TD.Cmp(p.Td()) > 0 {
p.SetTd(request.TD) p.SetTd(request.TD)
if request.TD.Cmp(new(big.Int).Add(pm.chainman.Td(), request.Block.Difficulty())) > 0 { if request.TD.Cmp(new(big.Int).Add(pm.blockchain.Td(), request.Block.Difficulty())) > 0 {
go pm.synchronise(p) go pm.synchronise(p)
} }
} }
@ -645,8 +645,8 @@ func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
if propagate { if propagate {
// Calculate the TD of the block (it's not imported yet, so block.Td is not valid) // Calculate the TD of the block (it's not imported yet, so block.Td is not valid)
var td *big.Int var td *big.Int
if parent := pm.chainman.GetBlock(block.ParentHash()); parent != nil { if parent := pm.blockchain.GetBlock(block.ParentHash()); parent != nil {
td = new(big.Int).Add(block.Difficulty(), pm.chainman.GetTd(block.ParentHash())) td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash()))
} else { } else {
glog.V(logger.Error).Infof("propagating dangling block #%d [%x]", block.NumberU64(), hash[:4]) glog.V(logger.Error).Infof("propagating dangling block #%d [%x]", block.NumberU64(), hash[:4])
return return
@ -659,7 +659,7 @@ func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
glog.V(logger.Detail).Infof("propagated block %x to %d peers in %v", hash[:4], len(transfer), time.Since(block.ReceivedAt)) glog.V(logger.Detail).Infof("propagated block %x to %d peers in %v", hash[:4], len(transfer), time.Since(block.ReceivedAt))
} }
// Otherwise if the block is indeed in out own chain, announce it // Otherwise if the block is indeed in out own chain, announce it
if pm.chainman.HasBlock(hash) { if pm.blockchain.HasBlock(hash) {
for _, peer := range peers { for _, peer := range peers {
if peer.version < eth62 { if peer.version < eth62 {
peer.SendNewBlockHashes61([]common.Hash{hash}) peer.SendNewBlockHashes61([]common.Hash{hash})

View File

@ -33,23 +33,23 @@ func testGetBlockHashes(t *testing.T, protocol int) {
number int number int
result int result int
}{ }{
{common.Hash{}, 1, 0}, // Make sure non existent hashes don't return results {common.Hash{}, 1, 0}, // Make sure non existent hashes don't return results
{pm.chainman.Genesis().Hash(), 1, 0}, // There are no hashes to retrieve up from the genesis {pm.blockchain.Genesis().Hash(), 1, 0}, // There are no hashes to retrieve up from the genesis
{pm.chainman.GetBlockByNumber(5).Hash(), 5, 5}, // All the hashes including the genesis requested {pm.blockchain.GetBlockByNumber(5).Hash(), 5, 5}, // All the hashes including the genesis requested
{pm.chainman.GetBlockByNumber(5).Hash(), 10, 5}, // More hashes than available till the genesis requested {pm.blockchain.GetBlockByNumber(5).Hash(), 10, 5}, // More hashes than available till the genesis requested
{pm.chainman.GetBlockByNumber(100).Hash(), 10, 10}, // All hashes available from the middle of the chain {pm.blockchain.GetBlockByNumber(100).Hash(), 10, 10}, // All hashes available from the middle of the chain
{pm.chainman.CurrentBlock().Hash(), 10, 10}, // All hashes available from the head of the chain {pm.blockchain.CurrentBlock().Hash(), 10, 10}, // All hashes available from the head of the chain
{pm.chainman.CurrentBlock().Hash(), limit, limit}, // Request the maximum allowed hash count {pm.blockchain.CurrentBlock().Hash(), limit, limit}, // Request the maximum allowed hash count
{pm.chainman.CurrentBlock().Hash(), limit + 1, limit}, // Request more than the maximum allowed hash count {pm.blockchain.CurrentBlock().Hash(), limit + 1, limit}, // Request more than the maximum allowed hash count
} }
// Run each of the tests and verify the results against the chain // Run each of the tests and verify the results against the chain
for i, tt := range tests { for i, tt := range tests {
// Assemble the hash response we would like to receive // Assemble the hash response we would like to receive
resp := make([]common.Hash, tt.result) resp := make([]common.Hash, tt.result)
if len(resp) > 0 { if len(resp) > 0 {
from := pm.chainman.GetBlock(tt.origin).NumberU64() - 1 from := pm.blockchain.GetBlock(tt.origin).NumberU64() - 1
for j := 0; j < len(resp); j++ { for j := 0; j < len(resp); j++ {
resp[j] = pm.chainman.GetBlockByNumber(uint64(int(from) - j)).Hash() resp[j] = pm.blockchain.GetBlockByNumber(uint64(int(from) - j)).Hash()
} }
} }
// Send the hash request and verify the response // Send the hash request and verify the response
@ -76,11 +76,11 @@ func testGetBlockHashesFromNumber(t *testing.T, protocol int) {
number int number int
result int result int
}{ }{
{pm.chainman.CurrentBlock().NumberU64() + 1, 1, 0}, // Out of bounds requests should return empty {pm.blockchain.CurrentBlock().NumberU64() + 1, 1, 0}, // Out of bounds requests should return empty
{pm.chainman.CurrentBlock().NumberU64(), 1, 1}, // Make sure the head hash can be retrieved {pm.blockchain.CurrentBlock().NumberU64(), 1, 1}, // Make sure the head hash can be retrieved
{pm.chainman.CurrentBlock().NumberU64() - 4, 5, 5}, // All hashes, including the head hash requested {pm.blockchain.CurrentBlock().NumberU64() - 4, 5, 5}, // All hashes, including the head hash requested
{pm.chainman.CurrentBlock().NumberU64() - 4, 10, 5}, // More hashes requested than available till the head {pm.blockchain.CurrentBlock().NumberU64() - 4, 10, 5}, // More hashes requested than available till the head
{pm.chainman.CurrentBlock().NumberU64() - 100, 10, 10}, // All hashes available from the middle of the chain {pm.blockchain.CurrentBlock().NumberU64() - 100, 10, 10}, // All hashes available from the middle of the chain
{0, 10, 10}, // All hashes available from the root of the chain {0, 10, 10}, // All hashes available from the root of the chain
{0, limit, limit}, // Request the maximum allowed hash count {0, limit, limit}, // Request the maximum allowed hash count
{0, limit + 1, limit}, // Request more than the maximum allowed hash count {0, limit + 1, limit}, // Request more than the maximum allowed hash count
@ -91,7 +91,7 @@ func testGetBlockHashesFromNumber(t *testing.T, protocol int) {
// Assemble the hash response we would like to receive // Assemble the hash response we would like to receive
resp := make([]common.Hash, tt.result) resp := make([]common.Hash, tt.result)
for j := 0; j < len(resp); j++ { for j := 0; j < len(resp); j++ {
resp[j] = pm.chainman.GetBlockByNumber(tt.origin + uint64(j)).Hash() resp[j] = pm.blockchain.GetBlockByNumber(tt.origin + uint64(j)).Hash()
} }
// Send the hash request and verify the response // Send the hash request and verify the response
p2p.Send(peer.app, 0x08, getBlockHashesFromNumberData{tt.origin, uint64(tt.number)}) p2p.Send(peer.app, 0x08, getBlockHashesFromNumberData{tt.origin, uint64(tt.number)})
@ -117,22 +117,22 @@ func testGetBlocks(t *testing.T, protocol int) {
available []bool // Availability of explicitly requested blocks available []bool // Availability of explicitly requested blocks
expected int // Total number of existing blocks to expect expected int // Total number of existing blocks to expect
}{ }{
{1, nil, nil, 1}, // A single random block should be retrievable {1, nil, nil, 1}, // A single random block should be retrievable
{10, nil, nil, 10}, // Multiple random blocks should be retrievable {10, nil, nil, 10}, // Multiple random blocks should be retrievable
{limit, nil, nil, limit}, // The maximum possible blocks should be retrievable {limit, nil, nil, limit}, // The maximum possible blocks should be retrievable
{limit + 1, nil, nil, limit}, // No more that the possible block count should be returned {limit + 1, nil, nil, limit}, // No more than the possible block count should be returned
{0, []common.Hash{pm.chainman.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable {0, []common.Hash{pm.blockchain.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable
{0, []common.Hash{pm.chainman.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable {0, []common.Hash{pm.blockchain.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable
{0, []common.Hash{common.Hash{}}, []bool{false}, 0}, // A non existent block should not be returned {0, []common.Hash{common.Hash{}}, []bool{false}, 0}, // A non existent block should not be returned
// Existing and non-existing blocks interleaved should not cause problems // Existing and non-existing blocks interleaved should not cause problems
{0, []common.Hash{ {0, []common.Hash{
common.Hash{}, common.Hash{},
pm.chainman.GetBlockByNumber(1).Hash(), pm.blockchain.GetBlockByNumber(1).Hash(),
common.Hash{}, common.Hash{},
pm.chainman.GetBlockByNumber(10).Hash(), pm.blockchain.GetBlockByNumber(10).Hash(),
common.Hash{}, common.Hash{},
pm.chainman.GetBlockByNumber(100).Hash(), pm.blockchain.GetBlockByNumber(100).Hash(),
common.Hash{}, common.Hash{},
}, []bool{false, true, false, true, false, true, false}, 3}, }, []bool{false, true, false, true, false, true, false}, 3},
} }
@ -144,11 +144,11 @@ func testGetBlocks(t *testing.T, protocol int) {
for j := 0; j < tt.random; j++ { for j := 0; j < tt.random; j++ {
for { for {
num := rand.Int63n(int64(pm.chainman.CurrentBlock().NumberU64())) num := rand.Int63n(int64(pm.blockchain.CurrentBlock().NumberU64()))
if !seen[num] { if !seen[num] {
seen[num] = true seen[num] = true
block := pm.chainman.GetBlockByNumber(uint64(num)) block := pm.blockchain.GetBlockByNumber(uint64(num))
hashes = append(hashes, block.Hash()) hashes = append(hashes, block.Hash())
if len(blocks) < tt.expected { if len(blocks) < tt.expected {
blocks = append(blocks, block) blocks = append(blocks, block)
@ -160,7 +160,7 @@ func testGetBlocks(t *testing.T, protocol int) {
for j, hash := range tt.explicit { for j, hash := range tt.explicit {
hashes = append(hashes, hash) hashes = append(hashes, hash)
if tt.available[j] && len(blocks) < tt.expected { if tt.available[j] && len(blocks) < tt.expected {
blocks = append(blocks, pm.chainman.GetBlock(hash)) blocks = append(blocks, pm.blockchain.GetBlock(hash))
} }
} }
// Send the hash request and verify the response // Send the hash request and verify the response
@ -194,83 +194,83 @@ func testGetBlockHeaders(t *testing.T, protocol int) {
}{ }{
// A single random block should be retrievable by hash and number too // A single random block should be retrievable by hash and number too
{ {
&getBlockHeadersData{Origin: hashOrNumber{Hash: pm.chainman.GetBlockByNumber(limit / 2).Hash()}, Amount: 1}, &getBlockHeadersData{Origin: hashOrNumber{Hash: pm.blockchain.GetBlockByNumber(limit / 2).Hash()}, Amount: 1},
[]common.Hash{pm.chainman.GetBlockByNumber(limit / 2).Hash()}, []common.Hash{pm.blockchain.GetBlockByNumber(limit / 2).Hash()},
}, { }, {
&getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 1}, &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 1},
[]common.Hash{pm.chainman.GetBlockByNumber(limit / 2).Hash()}, []common.Hash{pm.blockchain.GetBlockByNumber(limit / 2).Hash()},
}, },
// Multiple headers should be retrievable in both directions // Multiple headers should be retrievable in both directions
{ {
&getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3}, &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3},
[]common.Hash{ []common.Hash{
pm.chainman.GetBlockByNumber(limit / 2).Hash(), pm.blockchain.GetBlockByNumber(limit / 2).Hash(),
pm.chainman.GetBlockByNumber(limit/2 + 1).Hash(), pm.blockchain.GetBlockByNumber(limit/2 + 1).Hash(),
pm.chainman.GetBlockByNumber(limit/2 + 2).Hash(), pm.blockchain.GetBlockByNumber(limit/2 + 2).Hash(),
}, },
}, { }, {
&getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3, Reverse: true}, &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3, Reverse: true},
[]common.Hash{ []common.Hash{
pm.chainman.GetBlockByNumber(limit / 2).Hash(), pm.blockchain.GetBlockByNumber(limit / 2).Hash(),
pm.chainman.GetBlockByNumber(limit/2 - 1).Hash(), pm.blockchain.GetBlockByNumber(limit/2 - 1).Hash(),
pm.chainman.GetBlockByNumber(limit/2 - 2).Hash(), pm.blockchain.GetBlockByNumber(limit/2 - 2).Hash(),
}, },
}, },
// Multiple headers with skip lists should be retrievable // Multiple headers with skip lists should be retrievable
{ {
&getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3}, &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3},
[]common.Hash{ []common.Hash{
pm.chainman.GetBlockByNumber(limit / 2).Hash(), pm.blockchain.GetBlockByNumber(limit / 2).Hash(),
pm.chainman.GetBlockByNumber(limit/2 + 4).Hash(), pm.blockchain.GetBlockByNumber(limit/2 + 4).Hash(),
pm.chainman.GetBlockByNumber(limit/2 + 8).Hash(), pm.blockchain.GetBlockByNumber(limit/2 + 8).Hash(),
}, },
}, { }, {
&getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3, Reverse: true}, &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3, Reverse: true},
[]common.Hash{ []common.Hash{
pm.chainman.GetBlockByNumber(limit / 2).Hash(), pm.blockchain.GetBlockByNumber(limit / 2).Hash(),
pm.chainman.GetBlockByNumber(limit/2 - 4).Hash(), pm.blockchain.GetBlockByNumber(limit/2 - 4).Hash(),
pm.chainman.GetBlockByNumber(limit/2 - 8).Hash(), pm.blockchain.GetBlockByNumber(limit/2 - 8).Hash(),
}, },
}, },
// The chain endpoints should be retrievable // The chain endpoints should be retrievable
{ {
&getBlockHeadersData{Origin: hashOrNumber{Number: 0}, Amount: 1}, &getBlockHeadersData{Origin: hashOrNumber{Number: 0}, Amount: 1},
[]common.Hash{pm.chainman.GetBlockByNumber(0).Hash()}, []common.Hash{pm.blockchain.GetBlockByNumber(0).Hash()},
}, { }, {
&getBlockHeadersData{Origin: hashOrNumber{Number: pm.chainman.CurrentBlock().NumberU64()}, Amount: 1}, &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64()}, Amount: 1},
[]common.Hash{pm.chainman.CurrentBlock().Hash()}, []common.Hash{pm.blockchain.CurrentBlock().Hash()},
}, },
// Ensure protocol limits are honored // Ensure protocol limits are honored
{ {
&getBlockHeadersData{Origin: hashOrNumber{Number: pm.chainman.CurrentBlock().NumberU64() - 1}, Amount: limit + 10, Reverse: true}, &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() - 1}, Amount: limit + 10, Reverse: true},
pm.chainman.GetBlockHashesFromHash(pm.chainman.CurrentBlock().Hash(), limit), pm.blockchain.GetBlockHashesFromHash(pm.blockchain.CurrentBlock().Hash(), limit),
}, },
// Check that requesting more than available is handled gracefully // Check that requesting more than available is handled gracefully
{ {
&getBlockHeadersData{Origin: hashOrNumber{Number: pm.chainman.CurrentBlock().NumberU64() - 4}, Skip: 3, Amount: 3}, &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() - 4}, Skip: 3, Amount: 3},
[]common.Hash{ []common.Hash{
pm.chainman.GetBlockByNumber(pm.chainman.CurrentBlock().NumberU64() - 4).Hash(), pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64() - 4).Hash(),
pm.chainman.GetBlockByNumber(pm.chainman.CurrentBlock().NumberU64()).Hash(), pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64()).Hash(),
}, },
}, { }, {
&getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 3, Amount: 3, Reverse: true}, &getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 3, Amount: 3, Reverse: true},
[]common.Hash{ []common.Hash{
pm.chainman.GetBlockByNumber(4).Hash(), pm.blockchain.GetBlockByNumber(4).Hash(),
pm.chainman.GetBlockByNumber(0).Hash(), pm.blockchain.GetBlockByNumber(0).Hash(),
}, },
}, },
// Check that requesting more than available is handled gracefully, even if mid skip // Check that requesting more than available is handled gracefully, even if mid skip
{ {
&getBlockHeadersData{Origin: hashOrNumber{Number: pm.chainman.CurrentBlock().NumberU64() - 4}, Skip: 2, Amount: 3}, &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() - 4}, Skip: 2, Amount: 3},
[]common.Hash{ []common.Hash{
pm.chainman.GetBlockByNumber(pm.chainman.CurrentBlock().NumberU64() - 4).Hash(), pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64() - 4).Hash(),
pm.chainman.GetBlockByNumber(pm.chainman.CurrentBlock().NumberU64() - 1).Hash(), pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64() - 1).Hash(),
}, },
}, { }, {
&getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 2, Amount: 3, Reverse: true}, &getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 2, Amount: 3, Reverse: true},
[]common.Hash{ []common.Hash{
pm.chainman.GetBlockByNumber(4).Hash(), pm.blockchain.GetBlockByNumber(4).Hash(),
pm.chainman.GetBlockByNumber(1).Hash(), pm.blockchain.GetBlockByNumber(1).Hash(),
}, },
}, },
// Check that non existing headers aren't returned // Check that non existing headers aren't returned
@ -278,7 +278,7 @@ func testGetBlockHeaders(t *testing.T, protocol int) {
&getBlockHeadersData{Origin: hashOrNumber{Hash: unknown}, Amount: 1}, &getBlockHeadersData{Origin: hashOrNumber{Hash: unknown}, Amount: 1},
[]common.Hash{}, []common.Hash{},
}, { }, {
&getBlockHeadersData{Origin: hashOrNumber{Number: pm.chainman.CurrentBlock().NumberU64() + 1}, Amount: 1}, &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() + 1}, Amount: 1},
[]common.Hash{}, []common.Hash{},
}, },
} }
@ -287,7 +287,7 @@ func testGetBlockHeaders(t *testing.T, protocol int) {
// Collect the headers to expect in the response // Collect the headers to expect in the response
headers := []*types.Header{} headers := []*types.Header{}
for _, hash := range tt.expect { for _, hash := range tt.expect {
headers = append(headers, pm.chainman.GetBlock(hash).Header()) headers = append(headers, pm.blockchain.GetBlock(hash).Header())
} }
// Send the hash request and verify the response // Send the hash request and verify the response
p2p.Send(peer.app, 0x03, tt.query) p2p.Send(peer.app, 0x03, tt.query)
@ -315,22 +315,22 @@ func testGetBlockBodies(t *testing.T, protocol int) {
available []bool // Availability of explicitly requested blocks available []bool // Availability of explicitly requested blocks
expected int // Total number of existing blocks to expect expected int // Total number of existing blocks to expect
}{ }{
{1, nil, nil, 1}, // A single random block should be retrievable {1, nil, nil, 1}, // A single random block should be retrievable
{10, nil, nil, 10}, // Multiple random blocks should be retrievable {10, nil, nil, 10}, // Multiple random blocks should be retrievable
{limit, nil, nil, limit}, // The maximum possible blocks should be retrievable {limit, nil, nil, limit}, // The maximum possible blocks should be retrievable
{limit + 1, nil, nil, limit}, // No more that the possible block count should be returned {limit + 1, nil, nil, limit}, // No more than the possible block count should be returned
{0, []common.Hash{pm.chainman.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable {0, []common.Hash{pm.blockchain.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable
{0, []common.Hash{pm.chainman.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable {0, []common.Hash{pm.blockchain.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable
{0, []common.Hash{common.Hash{}}, []bool{false}, 0}, // A non existent block should not be returned {0, []common.Hash{common.Hash{}}, []bool{false}, 0}, // A non existent block should not be returned
// Existing and non-existing blocks interleaved should not cause problems // Existing and non-existing blocks interleaved should not cause problems
{0, []common.Hash{ {0, []common.Hash{
common.Hash{}, common.Hash{},
pm.chainman.GetBlockByNumber(1).Hash(), pm.blockchain.GetBlockByNumber(1).Hash(),
common.Hash{}, common.Hash{},
pm.chainman.GetBlockByNumber(10).Hash(), pm.blockchain.GetBlockByNumber(10).Hash(),
common.Hash{}, common.Hash{},
pm.chainman.GetBlockByNumber(100).Hash(), pm.blockchain.GetBlockByNumber(100).Hash(),
common.Hash{}, common.Hash{},
}, []bool{false, true, false, true, false, true, false}, 3}, }, []bool{false, true, false, true, false, true, false}, 3},
} }
@ -342,11 +342,11 @@ func testGetBlockBodies(t *testing.T, protocol int) {
for j := 0; j < tt.random; j++ { for j := 0; j < tt.random; j++ {
for { for {
num := rand.Int63n(int64(pm.chainman.CurrentBlock().NumberU64())) num := rand.Int63n(int64(pm.blockchain.CurrentBlock().NumberU64()))
if !seen[num] { if !seen[num] {
seen[num] = true seen[num] = true
block := pm.chainman.GetBlockByNumber(uint64(num)) block := pm.blockchain.GetBlockByNumber(uint64(num))
hashes = append(hashes, block.Hash()) hashes = append(hashes, block.Hash())
if len(bodies) < tt.expected { if len(bodies) < tt.expected {
bodies = append(bodies, &blockBody{Transactions: block.Transactions(), Uncles: block.Uncles()}) bodies = append(bodies, &blockBody{Transactions: block.Transactions(), Uncles: block.Uncles()})
@ -358,7 +358,7 @@ func testGetBlockBodies(t *testing.T, protocol int) {
for j, hash := range tt.explicit { for j, hash := range tt.explicit {
hashes = append(hashes, hash) hashes = append(hashes, hash)
if tt.available[j] && len(bodies) < tt.expected { if tt.available[j] && len(bodies) < tt.expected {
block := pm.chainman.GetBlock(hash) block := pm.blockchain.GetBlock(hash)
bodies = append(bodies, &blockBody{Transactions: block.Transactions(), Uncles: block.Uncles()}) bodies = append(bodies, &blockBody{Transactions: block.Transactions(), Uncles: block.Uncles()})
} }
} }
@ -442,11 +442,11 @@ func testGetNodeData(t *testing.T, protocol int) {
statedb.Put(hashes[i].Bytes(), data[i]) statedb.Put(hashes[i].Bytes(), data[i])
} }
accounts := []common.Address{testBankAddress, acc1Addr, acc2Addr} accounts := []common.Address{testBankAddress, acc1Addr, acc2Addr}
for i := uint64(0); i <= pm.chainman.CurrentBlock().NumberU64(); i++ { for i := uint64(0); i <= pm.blockchain.CurrentBlock().NumberU64(); i++ {
trie := state.New(pm.chainman.GetBlockByNumber(i).Root(), statedb) trie := state.New(pm.blockchain.GetBlockByNumber(i).Root(), statedb)
for j, acc := range accounts { for j, acc := range accounts {
bw := pm.chainman.State().GetBalance(acc) bw := pm.blockchain.State().GetBalance(acc)
bh := trie.GetBalance(acc) bh := trie.GetBalance(acc)
if (bw != nil && bh == nil) || (bw == nil && bh != nil) { if (bw != nil && bh == nil) || (bw == nil && bh != nil) {
@ -505,8 +505,8 @@ func testGetReceipt(t *testing.T, protocol int) {
// Collect the hashes to request, and the response to expect // Collect the hashes to request, and the response to expect
hashes := []common.Hash{} hashes := []common.Hash{}
for i := uint64(0); i <= pm.chainman.CurrentBlock().NumberU64(); i++ { for i := uint64(0); i <= pm.blockchain.CurrentBlock().NumberU64(); i++ {
for _, tx := range pm.chainman.GetBlockByNumber(i).Transactions() { for _, tx := range pm.blockchain.GetBlockByNumber(i).Transactions() {
hashes = append(hashes, tx.Hash()) hashes = append(hashes, tx.Hash())
} }
} }

View File

@ -30,18 +30,18 @@ var (
// channels for different events. // channels for different events.
func newTestProtocolManager(blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) *ProtocolManager { func newTestProtocolManager(blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) *ProtocolManager {
var ( var (
evmux = new(event.TypeMux) evmux = new(event.TypeMux)
pow = new(core.FakePow) pow = new(core.FakePow)
db, _ = ethdb.NewMemDatabase() db, _ = ethdb.NewMemDatabase()
genesis = core.WriteGenesisBlockForTesting(db, core.GenesisAccount{testBankAddress, testBankFunds}) genesis = core.WriteGenesisBlockForTesting(db, core.GenesisAccount{testBankAddress, testBankFunds})
chainman, _ = core.NewChainManager(db, pow, evmux) blockchain, _ = core.NewBlockChain(db, pow, evmux)
blockproc = core.NewBlockProcessor(db, pow, chainman, evmux) blockproc = core.NewBlockProcessor(db, pow, blockchain, evmux)
) )
chainman.SetProcessor(blockproc) blockchain.SetProcessor(blockproc)
if _, err := chainman.InsertChain(core.GenerateChain(genesis, db, blocks, generator)); err != nil { if _, err := blockchain.InsertChain(core.GenerateChain(genesis, db, blocks, generator)); err != nil {
panic(err) panic(err)
} }
pm := NewProtocolManager(NetworkId, evmux, &testTxPool{added: newtx}, pow, chainman, db) pm := NewProtocolManager(NetworkId, evmux, &testTxPool{added: newtx}, pow, blockchain, db)
pm.Start() pm.Start()
return pm return pm
} }
@ -116,7 +116,7 @@ func newTestPeer(name string, version int, pm *ProtocolManager, shake bool) (*te
} }
// Execute any implicitly requested handshakes and return // Execute any implicitly requested handshakes and return
if shake { if shake {
td, head, genesis := pm.chainman.Status() td, head, genesis := pm.blockchain.Status()
tp.handshake(nil, td, head, genesis) tp.handshake(nil, td, head, genesis)
} }
return tp, errc return tp, errc

View File

@ -45,7 +45,7 @@ func TestStatusMsgErrors64(t *testing.T) { testStatusMsgErrors(t, 64) }
func testStatusMsgErrors(t *testing.T, protocol int) { func testStatusMsgErrors(t *testing.T, protocol int) {
pm := newTestProtocolManager(0, nil, nil) pm := newTestProtocolManager(0, nil, nil)
td, currentBlock, genesis := pm.chainman.Status() td, currentBlock, genesis := pm.blockchain.Status()
defer pm.Stop() defer pm.Stop()
tests := []struct { tests := []struct {

View File

@ -160,7 +160,7 @@ func (pm *ProtocolManager) synchronise(peer *peer) {
return return
} }
// Make sure the peer's TD is higher than our own. If not drop. // Make sure the peer's TD is higher than our own. If not drop.
if peer.Td().Cmp(pm.chainman.Td()) <= 0 { if peer.Td().Cmp(pm.blockchain.Td()) <= 0 {
return return
} }
// Otherwise try to sync with the downloader // Otherwise try to sync with the downloader

View File

@ -100,7 +100,7 @@ type worker struct {
pow pow.PoW pow pow.PoW
eth core.Backend eth core.Backend
chain *core.ChainManager chain *core.BlockChain
proc *core.BlockProcessor proc *core.BlockProcessor
chainDb ethdb.Database chainDb ethdb.Database
@ -131,7 +131,7 @@ func newWorker(coinbase common.Address, eth core.Backend) *worker {
chainDb: eth.ChainDb(), chainDb: eth.ChainDb(),
recv: make(chan *Result, resultQueueSize), recv: make(chan *Result, resultQueueSize),
gasPrice: new(big.Int), gasPrice: new(big.Int),
chain: eth.ChainManager(), chain: eth.BlockChain(),
proc: eth.BlockProcessor(), proc: eth.BlockProcessor(),
possibleUncles: make(map[common.Hash]*types.Block), possibleUncles: make(map[common.Hash]*types.Block),
coinbase: coinbase, coinbase: coinbase,

View File

@ -151,7 +151,7 @@ func (self *adminApi) DataDir(req *shared.Request) (interface{}, error) {
return self.ethereum.DataDir, nil return self.ethereum.DataDir, nil
} }
func hasAllBlocks(chain *core.ChainManager, bs []*types.Block) bool { func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
for _, b := range bs { for _, b := range bs {
if !chain.HasBlock(b.Hash()) { if !chain.HasBlock(b.Hash()) {
return false return false
@ -193,10 +193,10 @@ func (self *adminApi) ImportChain(req *shared.Request) (interface{}, error) {
break break
} }
// Import the batch. // Import the batch.
if hasAllBlocks(self.ethereum.ChainManager(), blocks[:i]) { if hasAllBlocks(self.ethereum.BlockChain(), blocks[:i]) {
continue continue
} }
if _, err := self.ethereum.ChainManager().InsertChain(blocks[:i]); err != nil { if _, err := self.ethereum.BlockChain().InsertChain(blocks[:i]); err != nil {
return false, fmt.Errorf("invalid block %d: %v", n, err) return false, fmt.Errorf("invalid block %d: %v", n, err)
} }
} }
@ -214,7 +214,7 @@ func (self *adminApi) ExportChain(req *shared.Request) (interface{}, error) {
return false, err return false, err
} }
defer fh.Close() defer fh.Close()
if err := self.ethereum.ChainManager().Export(fh); err != nil { if err := self.ethereum.BlockChain().Export(fh); err != nil {
return false, err return false, err
} }

View File

@ -152,7 +152,7 @@ func (self *debugApi) SetHead(req *shared.Request) (interface{}, error) {
return nil, fmt.Errorf("block #%d not found", args.BlockNumber) return nil, fmt.Errorf("block #%d not found", args.BlockNumber)
} }
self.ethereum.ChainManager().SetHead(block) self.ethereum.BlockChain().SetHead(block)
return nil, nil return nil, nil
} }

View File

@ -168,7 +168,7 @@ func (self *ethApi) IsMining(req *shared.Request) (interface{}, error) {
} }
func (self *ethApi) IsSyncing(req *shared.Request) (interface{}, error) { func (self *ethApi) IsSyncing(req *shared.Request) (interface{}, error) {
current := self.ethereum.ChainManager().CurrentBlock().NumberU64() current := self.ethereum.BlockChain().CurrentBlock().NumberU64()
origin, height := self.ethereum.Downloader().Boundaries() origin, height := self.ethereum.Downloader().Boundaries()
if current < height { if current < height {

View File

@ -181,7 +181,7 @@ func runBlockTest(test *BlockTest) error {
return fmt.Errorf("InsertPreState: %v", err) return fmt.Errorf("InsertPreState: %v", err)
} }
cm := ethereum.ChainManager() cm := ethereum.BlockChain()
validBlocks, err := test.TryBlocksInsert(cm) validBlocks, err := test.TryBlocksInsert(cm)
if err != nil { if err != nil {
return err return err
@ -276,7 +276,7 @@ func (t *BlockTest) InsertPreState(ethereum *eth.Ethereum) (*state.StateDB, erro
expected we are expected to ignore it and continue processing and then validate the expected we are expected to ignore it and continue processing and then validate the
post state. post state.
*/ */
func (t *BlockTest) TryBlocksInsert(chainManager *core.ChainManager) ([]btBlock, error) { func (t *BlockTest) TryBlocksInsert(blockchain *core.BlockChain) ([]btBlock, error) {
validBlocks := make([]btBlock, 0) validBlocks := make([]btBlock, 0)
// insert the test blocks, which will execute all transactions // insert the test blocks, which will execute all transactions
for _, b := range t.Json.Blocks { for _, b := range t.Json.Blocks {
@ -289,7 +289,7 @@ func (t *BlockTest) TryBlocksInsert(chainManager *core.ChainManager) ([]btBlock,
} }
} }
// RLP decoding worked, try to insert into chain: // RLP decoding worked, try to insert into chain:
_, err = chainManager.InsertChain(types.Blocks{cb}) _, err = blockchain.InsertChain(types.Blocks{cb})
if err != nil { if err != nil {
if b.BlockHeader == nil { if b.BlockHeader == nil {
continue // OK - block is supposed to be invalid, continue with next block continue // OK - block is supposed to be invalid, continue with next block
@ -426,7 +426,7 @@ func (t *BlockTest) ValidatePostState(statedb *state.StateDB) error {
return nil return nil
} }
func (test *BlockTest) ValidateImportedHeaders(cm *core.ChainManager, validBlocks []btBlock) error { func (test *BlockTest) ValidateImportedHeaders(cm *core.BlockChain, validBlocks []btBlock) error {
// to get constant lookup when verifying block headers by hash (some tests have many blocks) // to get constant lookup when verifying block headers by hash (some tests have many blocks)
bmap := make(map[string]btBlock, len(test.Json.Blocks)) bmap := make(map[string]btBlock, len(test.Json.Blocks))
for _, b := range validBlocks { for _, b := range validBlocks {

View File

@ -126,7 +126,7 @@ func New(ethereum *eth.Ethereum, frontend Frontend) *XEth {
if frontend == nil { if frontend == nil {
xeth.frontend = dummyFrontend{} xeth.frontend = dummyFrontend{}
} }
xeth.state = NewState(xeth, xeth.backend.ChainManager().State()) xeth.state = NewState(xeth, xeth.backend.BlockChain().State())
go xeth.start() go xeth.start()
@ -214,7 +214,7 @@ func (self *XEth) AtStateNum(num int64) *XEth {
if block := self.getBlockByHeight(num); block != nil { if block := self.getBlockByHeight(num); block != nil {
st = state.New(block.Root(), self.backend.ChainDb()) st = state.New(block.Root(), self.backend.ChainDb())
} else { } else {
st = state.New(self.backend.ChainManager().GetBlockByNumber(0).Root(), self.backend.ChainDb()) st = state.New(self.backend.BlockChain().GetBlockByNumber(0).Root(), self.backend.ChainDb())
} }
} }
@ -290,19 +290,19 @@ func (self *XEth) getBlockByHeight(height int64) *types.Block {
num = uint64(height) num = uint64(height)
} }
return self.backend.ChainManager().GetBlockByNumber(num) return self.backend.BlockChain().GetBlockByNumber(num)
} }
func (self *XEth) BlockByHash(strHash string) *Block { func (self *XEth) BlockByHash(strHash string) *Block {
hash := common.HexToHash(strHash) hash := common.HexToHash(strHash)
block := self.backend.ChainManager().GetBlock(hash) block := self.backend.BlockChain().GetBlock(hash)
return NewBlock(block) return NewBlock(block)
} }
func (self *XEth) EthBlockByHash(strHash string) *types.Block { func (self *XEth) EthBlockByHash(strHash string) *types.Block {
hash := common.HexToHash(strHash) hash := common.HexToHash(strHash)
block := self.backend.ChainManager().GetBlock(hash) block := self.backend.BlockChain().GetBlock(hash)
return block return block
} }
@ -356,11 +356,11 @@ func (self *XEth) EthBlockByNumber(num int64) *types.Block {
} }
func (self *XEth) Td(hash common.Hash) *big.Int { func (self *XEth) Td(hash common.Hash) *big.Int {
return self.backend.ChainManager().GetTd(hash) return self.backend.BlockChain().GetTd(hash)
} }
func (self *XEth) CurrentBlock() *types.Block { func (self *XEth) CurrentBlock() *types.Block {
return self.backend.ChainManager().CurrentBlock() return self.backend.BlockChain().CurrentBlock()
} }
func (self *XEth) GetBlockReceipts(bhash common.Hash) types.Receipts { func (self *XEth) GetBlockReceipts(bhash common.Hash) types.Receipts {
@ -372,7 +372,7 @@ func (self *XEth) GetTxReceipt(txhash common.Hash) *types.Receipt {
} }
func (self *XEth) GasLimit() *big.Int { func (self *XEth) GasLimit() *big.Int {
return self.backend.ChainManager().GasLimit() return self.backend.BlockChain().GasLimit()
} }
func (self *XEth) Block(v interface{}) *Block { func (self *XEth) Block(v interface{}) *Block {
@ -855,7 +855,7 @@ func (self *XEth) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr st
} }
header := self.CurrentBlock().Header() header := self.CurrentBlock().Header()
vmenv := core.NewEnv(statedb, self.backend.ChainManager(), msg, header) vmenv := core.NewEnv(statedb, self.backend.BlockChain(), msg, header)
res, gas, err := core.ApplyMessage(vmenv, msg, from) res, gas, err := core.ApplyMessage(vmenv, msg, from)
return common.ToHex(res), gas.String(), err return common.ToHex(res), gas.String(), err