Skip to content

Commit

Permalink
modify the blockchain code (#489)
Browse files Browse the repository at this point in the history
  • Loading branch information
erickyan86 authored Sep 17, 2019
1 parent c1aa4ef commit b599fa0
Show file tree
Hide file tree
Showing 7 changed files with 33 additions and 101 deletions.
69 changes: 2 additions & 67 deletions blockchain/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion blockchain/blockchain_insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
}

Expand Down
12 changes: 6 additions & 6 deletions blockchain/blockgenerator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
Expand All @@ -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 {
Expand All @@ -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())
}
Expand All @@ -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
}
9 changes: 3 additions & 6 deletions blockchain/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 10 additions & 10 deletions blockchain/forkcontroller.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -152,15 +152,15 @@ 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
}
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
Expand All @@ -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 {
Expand Down
16 changes: 8 additions & 8 deletions blockchain/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import (
"github.com/fractalplatform/fractal/types"
)

type Station struct {
type station struct {
peerCh chan *router.Event
blockchain *BlockChain
networkID uint64
Expand All @@ -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,
Expand All @@ -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()
Expand Down Expand Up @@ -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{})
Expand Down Expand Up @@ -125,7 +125,7 @@ func (bs *Station) handshake(e *router.Event) {
}
}

func (bs *Station) loop() {
func (bs *station) loop() {
for {
select {
case <-bs.quit:
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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 {
Expand Down
6 changes: 3 additions & 3 deletions blockchain/test_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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,
Expand Down

0 comments on commit b599fa0

Please sign in to comment.