From b599fa02349f7936cfce8bd1ecd048aa07626741 Mon Sep 17 00:00:00 2001 From: erick yan <46879318+erickyan86@users.noreply.github.com> Date: Tue, 17 Sep 2019 16:07:09 +0800 Subject: [PATCH] modify the blockchain code (#489) --- blockchain/blockchain.go | 69 +-------------------------------- blockchain/blockchain_insert.go | 2 +- blockchain/blockgenerator.go | 12 +++--- blockchain/error.go | 9 ++--- blockchain/forkcontroller.go | 20 +++++----- blockchain/handler.go | 16 ++++---- blockchain/test_utils.go | 6 +-- 7 files changed, 33 insertions(+), 101 deletions(-) diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go index caddb4b5..703b2963 100644 --- a/blockchain/blockchain.go +++ b/blockchain/blockchain.go @@ -83,10 +83,10 @@ type BlockChain struct { procInterrupt int32 // procInterrupt must be atomically called, interrupt signaler for block processing wg sync.WaitGroup // chain processing wait group for shutting down senderCacher TxSenderCacher // senderCacher is a concurrent tranaction sender recoverer sender cacher. - fcontroller *ForkController // fcontroller + fcontroller *forkController // fcontroller processor processor.Processor // block processor interface validator processor.Validator // block and state validator interface - station *Station // p2p station + station *station // p2p station headerCache *lru.Cache // Cache for the most recent block headers tdCache *lru.Cache // Cache for the most recent block total difficulties @@ -1098,71 +1098,6 @@ func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header { } -// HasHeader checks if a block header is present in the database or not. -func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool { - if bc.numberCache.Contains(hash) || bc.headerCache.Contains(hash) { - return true - } - return rawdb.HasHeader(bc.db, hash, number) - -} - -// GetBlockHashesFromHash retrieves a number of block hashes starting at a given hash, fetching towards the genesis block. -func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { - header := bc.GetHeaderByHash(hash) - if header == nil { - return nil - } - chain := make([]common.Hash, 0, max) - for i := uint64(0); i < max; i++ { - next := header.ParentHash - if header = bc.GetHeader(next, header.Number.Uint64()-1); header == nil { - break - } - chain = append(chain, next) - if header.Number.Sign() == 0 { - break - } - } - return chain -} - -// GetAncestor retrieves the Nth ancestor of a given block. -func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) { - bc.chainmu.Lock() - defer bc.chainmu.Unlock() - - if ancestor > number { - return common.Hash{}, 0 - } - if ancestor == 1 { - // in this case it is cheaper to just read the header - if header := bc.GetHeader(hash, number); header != nil { - return header.ParentHash, number - 1 - } - return common.Hash{}, 0 - } - for ancestor != 0 { - if rawdb.ReadCanonicalHash(bc.db, number) == hash { - number -= ancestor - return rawdb.ReadCanonicalHash(bc.db, number), number - } - if *maxNonCanonical == 0 { - return common.Hash{}, 0 - } - *maxNonCanonical-- - ancestor-- - header := bc.GetHeader(hash, number) - if header == nil { - return common.Hash{}, 0 - } - hash = header.ParentHash - number-- - } - return hash, number - -} - // GetHeaderByNumber retrieves a block header from the database by number. func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header { hash := rawdb.ReadCanonicalHash(bc.db, number) diff --git a/blockchain/blockchain_insert.go b/blockchain/blockchain_insert.go index c9762f9b..e59737ce 100644 --- a/blockchain/blockchain_insert.go +++ b/blockchain/blockchain_insert.go @@ -49,7 +49,7 @@ func (st *insertStats) report(chain []*types.Block, index int) { // Assemble the log context and send it to the logger context := []interface{}{ - "blocks", st.processed, "txs", st.txsCnt, "gas", float64(st.usedGas), + "blocks", st.processed, "txs", st.txsCnt, "gas", st.usedGas, "elapsed", common.PrettyDuration(elapsed), "number", end.Number(), "hash", end.Hash(), } diff --git a/blockchain/blockgenerator.go b/blockchain/blockgenerator.go index 6e27112e..e7265542 100644 --- a/blockchain/blockgenerator.go +++ b/blockchain/blockgenerator.go @@ -28,8 +28,8 @@ import ( "github.com/fractalplatform/fractal/types" ) -// BlockGenerator creates blocks for testing. -type BlockGenerator struct { +// blockGenerator creates blocks for testing. +type blockGenerator struct { i int parent *types.Block header *types.Header @@ -46,7 +46,7 @@ type BlockGenerator struct { } // SetCoinbase sets the coinbase of the generated block. -func (bg *BlockGenerator) SetCoinbase(name common.Name) { +func (bg *blockGenerator) SetCoinbase(name common.Name) { if bg.gasPool != nil { if len(bg.txs) > 0 { panic("coinbase must be set before adding transactions") @@ -58,7 +58,7 @@ func (bg *BlockGenerator) SetCoinbase(name common.Name) { } // TxNonce retrun nonce -func (bg *BlockGenerator) TxNonce(name common.Name) uint64 { +func (bg *blockGenerator) TxNonce(name common.Name) uint64 { am, _ := accountmanager.NewAccountManager(bg.stateDB) a, err := am.GetAccountByName(name) if err != nil { @@ -71,7 +71,7 @@ func (bg *BlockGenerator) TxNonce(name common.Name) uint64 { } // AddTxWithChain adds a transaction to the generated block. -func (bg *BlockGenerator) AddTxWithChain(tx *types.Transaction) { +func (bg *blockGenerator) AddTxWithChain(tx *types.Transaction) { if bg.gasPool == nil { bg.SetCoinbase(bg.genesisBlock.Coinbase()) } @@ -88,6 +88,6 @@ func (bg *BlockGenerator) AddTxWithChain(tx *types.Transaction) { } // CurrentHeader return current header -func (bg *BlockGenerator) CurrentHeader() *types.Header { +func (bg *blockGenerator) CurrentHeader() *types.Header { return bg.parent.Head } diff --git a/blockchain/error.go b/blockchain/error.go index 01e50d47..c376c9f7 100644 --- a/blockchain/error.go +++ b/blockchain/error.go @@ -24,16 +24,13 @@ import ( ) var ( - ErrSideBlock = errors.New("write side block and state") - + // ErrNoGenesis genesis block not found in chain db. ErrNoGenesis = errors.New("Genesis not found in chain") - errReorgSystemBlock = errors.New("not reorg system block") - - errGenesisNoConfig = errors.New("genesis has no chain configuration") - // ErrBlacklistedHash is returned if a block to import is on the blacklist. ErrBlacklistedHash = errors.New("blacklisted hash") + + errGenesisNoConfig = errors.New("genesis has no chain configuration") ) // GenesisMismatchError is raised when trying to overwrite an existing diff --git a/blockchain/forkcontroller.go b/blockchain/forkcontroller.go index a111b385..6274a100 100644 --- a/blockchain/forkcontroller.go +++ b/blockchain/forkcontroller.go @@ -44,15 +44,15 @@ type ForkInfo struct { NextForkIDBlockNum uint64 } -// ForkController control the hard forking. -type ForkController struct { +// forkController control the hard forking. +type forkController struct { cfg *ForkConfig chainCfg *params.ChainConfig } // NewForkController return a new fork controller. -func NewForkController(cfg *ForkConfig, chaincfg *params.ChainConfig) *ForkController { - return &ForkController{cfg: cfg, chainCfg: chaincfg} +func NewForkController(cfg *ForkConfig, chaincfg *params.ChainConfig) *forkController { + return &forkController{cfg: cfg, chainCfg: chaincfg} } func initForkController(chainName string, statedb *state.StateDB, curforkID uint64) error { @@ -76,7 +76,7 @@ func initForkController(chainName string, statedb *state.StateDB, curforkID uint return nil } -func (fc *ForkController) getForkInfo(statedb *state.StateDB) (ForkInfo, error) { +func (fc *forkController) getForkInfo(statedb *state.StateDB) (ForkInfo, error) { info := ForkInfo{} infoBytes, err := statedb.Get(fc.chainCfg.ChainName, forkInfo) @@ -94,7 +94,7 @@ func (fc *ForkController) getForkInfo(statedb *state.StateDB) (ForkInfo, error) return info, nil } -func (fc *ForkController) putForkInfo(info ForkInfo, statedb *state.StateDB) error { +func (fc *forkController) putForkInfo(info ForkInfo, statedb *state.StateDB) error { infoBytes, err := rlp.EncodeToBytes(info) if err != nil { return err @@ -104,7 +104,7 @@ func (fc *ForkController) putForkInfo(info ForkInfo, statedb *state.StateDB) err return nil } -func (fc *ForkController) update(block *types.Block, statedb *state.StateDB, getHeader func(number uint64) *types.Header) error { +func (fc *forkController) update(block *types.Block, statedb *state.StateDB, getHeader func(number uint64) *types.Header) error { info, err := fc.getForkInfo(statedb) if err != nil { return err @@ -152,7 +152,7 @@ func (fc *ForkController) update(block *types.Block, statedb *state.StateDB, get return fc.putForkInfo(info, statedb) } -func (fc *ForkController) currentForkID(statedb *state.StateDB) (uint64, uint64, error) { +func (fc *forkController) currentForkID(statedb *state.StateDB) (uint64, uint64, error) { info, err := fc.getForkInfo(statedb) if err != nil { return 0, 0, err @@ -160,7 +160,7 @@ func (fc *ForkController) currentForkID(statedb *state.StateDB) (uint64, uint64, return info.CurForkID, params.NextForkID, nil } -func (fc *ForkController) checkForkID(header *types.Header, state *state.StateDB) error { +func (fc *forkController) checkForkID(header *types.Header, state *state.StateDB) error { // check current fork id and next fork id if curForkID, _, err := fc.currentForkID(state); err != nil { return err @@ -171,7 +171,7 @@ func (fc *ForkController) checkForkID(header *types.Header, state *state.StateDB return nil } -func (fc *ForkController) fillForkID(header *types.Header, state *state.StateDB) error { +func (fc *forkController) fillForkID(header *types.Header, state *state.StateDB) error { // check current fork id and next fork id curForkID, nextForkID, err := fc.currentForkID(state) if err != nil { diff --git a/blockchain/handler.go b/blockchain/handler.go index 87550dd3..8d5fad0a 100644 --- a/blockchain/handler.go +++ b/blockchain/handler.go @@ -28,7 +28,7 @@ import ( "github.com/fractalplatform/fractal/types" ) -type Station struct { +type station struct { peerCh chan *router.Event blockchain *BlockChain networkID uint64 @@ -42,8 +42,8 @@ func errResp(code errCode, format string, v ...interface{}) error { return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...)) } -func newStation(bc *BlockChain, networkID uint64) *Station { - bs := &Station{ +func newStation(bc *BlockChain, networkID uint64) *station { + bs := &station{ peerCh: make(chan *router.Event), blockchain: bc, networkID: networkID, @@ -67,7 +67,7 @@ func newStation(bc *BlockChain, networkID uint64) *Station { return bs } -func (bs *Station) chainStatus() *statusData { +func (bs *station) chainStatus() *statusData { genesis := bs.blockchain.Genesis() head := bs.blockchain.CurrentHeader() hash := head.Hash() @@ -96,7 +96,7 @@ func checkChainStatus(local *statusData, remote *statusData) error { return nil } -func (bs *Station) handshake(e *router.Event) { +func (bs *station) handshake(e *router.Event) { station := router.NewLocalStation("shake"+e.From.Name(), nil) ch := make(chan *router.Event) sub := router.Subscribe(station, ch, router.P2PStatusMsg, &statusData{}) @@ -125,7 +125,7 @@ func (bs *Station) handshake(e *router.Event) { } } -func (bs *Station) loop() { +func (bs *station) loop() { for { select { case <-bs.quit: @@ -163,7 +163,7 @@ func (bs *Station) loop() { // handleMsg is invoked whenever an inbound message is received from a remote // peer. The remote connection is torn down upon returning any error. -func (bs *Station) handleMsg(e *router.Event) error { +func (bs *station) handleMsg(e *router.Event) error { start := time.Now() defer func() { router.AddCPU(e.From, time.Since(start)) @@ -254,7 +254,7 @@ func (bs *Station) handleMsg(e *router.Event) error { return nil } -func (bs *Station) Stop() { +func (bs *station) Stop() { log.Info("BlockchainHandler stopping...") close(bs.quit) for _, sub := range bs.subs { diff --git a/blockchain/test_utils.go b/blockchain/test_utils.go index 76817b1b..dc5c9a66 100644 --- a/blockchain/test_utils.go +++ b/blockchain/test_utils.go @@ -112,7 +112,7 @@ func makeNewChain(t *testing.T, genesis *Genesis, chain *BlockChain, n, seed int newblocks, _ := generateChain(genesis.Config, chain.CurrentBlock(), engine, chain, tmpDB, - n, seed, func(i int, b *BlockGenerator) { + n, seed, func(i int, b *blockGenerator) { name := common.StrToName(genesis.Config.SysName) b.SetCoinbase(name) @@ -138,7 +138,7 @@ func deepCopyDB(db fdb.Database) (fdb.Database, error) { } func generateChain(config *params.ChainConfig, parent *types.Block, engine *dpos.Dpos, - chain *BlockChain, db fdb.Database, n, seed int, gen func(int, *BlockGenerator)) ([]*types.Block, [][]*types.Receipt) { + chain *BlockChain, db fdb.Database, n, seed int, gen func(int, *blockGenerator)) ([]*types.Block, [][]*types.Receipt) { if config == nil { config = params.DefaultChainconfig @@ -147,7 +147,7 @@ func generateChain(config *params.ChainConfig, parent *types.Block, engine *dpos chain.db = db blocks, receipts := make(types.Blocks, n), make([][]*types.Receipt, n) genblock := func(i int, parent *types.Block, stateDB *state.StateDB) (*types.Block, []*types.Receipt) { - b := &BlockGenerator{ + b := &blockGenerator{ i: i, parent: parent, stateDB: stateDB,