Blockchain interface. (#4214)

* Blockchain interface.

* Fix comments, remove unused.

Co-authored-by: Konstantin <k.potapov@softpro.com>
pull/4219/head
Konstantin 2 years ago committed by GitHub
parent 93bd74904d
commit 4eabc120b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      api/service/crosslink_sending/service.go
  2. 2
      api/service/explorer/interface.go
  3. 4
      api/service/explorer/service.go
  4. 4
      api/service/explorer/storage.go
  5. 20
      api/service/legacysync/syncing.go
  6. 2
      api/service/synchronize/service.go
  7. 2
      cmd/harmony/main.go
  8. 2
      consensus/consensus.go
  9. 4
      core/block_validator.go
  10. 3440
      core/blockchain.go
  11. 3028
      core/blockchain_impl.go
  12. 0
      core/blockchain_impl_test.go
  13. 2
      core/chain_makers.go
  14. 2
      core/evm_test.go
  15. 7
      core/offchain.go
  16. 4
      core/state_processor.go
  17. 2
      core/tx_pool_test.go
  18. 2
      hmy/downloader/downloader.go
  19. 2
      hmy/downloader/downloaders.go
  20. 8
      hmy/hmy.go
  21. 10
      internal/shardchain/shardchains.go
  22. 4
      node/node.go
  23. 2
      node/node_handler.go
  24. 6
      node/node_syncing.go
  25. 4
      node/worker/worker.go
  26. 2
      staking/verify/verify.go
  27. 10
      test/chain/main.go

@ -12,13 +12,13 @@ type broadcast interface {
type Service struct {
node broadcast
bc *core.BlockChain
bc core.BlockChain
ch chan core.ChainEvent
closeCh chan struct{}
beacon bool
}
func New(node broadcast, bc *core.BlockChain) *Service {
func New(node broadcast, bc core.BlockChain) *Service {
return &Service{
node: node,
bc: bc,

@ -146,7 +146,7 @@ type iterator interface {
}
// blockChainTxIndexer is the interface to check the loop up entry for transaction.
// Implemented by *core.BlockChain
// Implemented by core.BlockChain
type blockChainTxIndexer interface {
ReadTxLookupEntry(txID common.Hash) (common.Hash, uint64, uint64)
}

@ -48,12 +48,12 @@ type Service struct {
storage *storage
server *http.Server
messageChan chan *msg_pb.Message
blockchain *core.BlockChain
blockchain core.BlockChain
backend hmy.NodeAPI
}
// New returns explorer service.
func New(selfPeer *p2p.Peer, bc *core.BlockChain, backend hmy.NodeAPI) *Service {
func New(selfPeer *p2p.Peer, bc core.BlockChain, backend hmy.NodeAPI) *Service {
dbPath := defaultDBPath(selfPeer.IP, selfPeer.Port)
storage, err := newStorage(bc, dbPath)
if err != nil {

@ -32,7 +32,7 @@ var ErrExplorerNotReady = errors.New("explorer db not ready")
type (
storage struct {
db database
bc *core.BlockChain
bc core.BlockChain
// TODO: optimize this with priority queue
tm *taskManager
@ -55,7 +55,7 @@ type (
}
)
func newStorage(bc *core.BlockChain, dbPath string) (*storage, error) {
func newStorage(bc core.BlockChain, dbPath string) (*storage, error) {
utils.Logger().Info().Msg("explorer storage folder: " + dbPath)
db, err := newLvlDB(dbPath)
if err != nil {

@ -160,7 +160,7 @@ func (sc *SyncConfig) RemovePeer(peer *SyncPeerConfig) {
}
// CreateStateSync returns the implementation of StateSyncInterface interface.
func CreateStateSync(bc *core.BlockChain, ip string, port string, peerHash [20]byte, isExplorer bool, role nodeconfig.Role) *StateSync {
func CreateStateSync(bc core.BlockChain, ip string, port string, peerHash [20]byte, isExplorer bool, role nodeconfig.Role) *StateSync {
stateSync := &StateSync{}
stateSync.blockChain = bc
stateSync.selfip = ip
@ -177,7 +177,7 @@ func CreateStateSync(bc *core.BlockChain, ip string, port string, peerHash [20]b
// StateSync is the struct that implements StateSyncInterface.
type StateSync struct {
blockChain *core.BlockChain
blockChain core.BlockChain
selfip string
selfport string
selfPeerHash [20]byte // hash of ip and address combination
@ -535,7 +535,7 @@ func (ss *StateSync) getConsensusHashes(startHash []byte, size uint32) error {
return nil
}
func (ss *StateSync) generateStateSyncTaskQueue(bc *core.BlockChain) {
func (ss *StateSync) generateStateSyncTaskQueue(bc core.BlockChain) {
ss.stateSyncTaskQueue = queue.New(0)
ss.syncConfig.ForEachPeer(func(configPeer *SyncPeerConfig) (brk bool) {
for id, blockHash := range configPeer.blockHashes {
@ -554,7 +554,7 @@ func (ss *StateSync) generateStateSyncTaskQueue(bc *core.BlockChain) {
}
// downloadBlocks downloads blocks from state sync task queue.
func (ss *StateSync) downloadBlocks(bc *core.BlockChain) {
func (ss *StateSync) downloadBlocks(bc core.BlockChain) {
// Initialize blockchain
var wg sync.WaitGroup
count := 0
@ -839,7 +839,7 @@ func (ss *StateSync) getBlockFromLastMileBlocksByParentHash(parentHash common.Ha
}
// UpdateBlockAndStatus ...
func (ss *StateSync) UpdateBlockAndStatus(block *types.Block, bc *core.BlockChain, verifyAllSig bool) error {
func (ss *StateSync) UpdateBlockAndStatus(block *types.Block, bc core.BlockChain, verifyAllSig bool) error {
if block.NumberU64() != bc.CurrentBlock().NumberU64()+1 {
utils.Logger().Debug().Uint64("curBlockNum", bc.CurrentBlock().NumberU64()).Uint64("receivedBlockNum", block.NumberU64()).Msg("[SYNC] Inappropriate block number, ignore!")
return nil
@ -910,7 +910,7 @@ func (ss *StateSync) UpdateBlockAndStatus(block *types.Block, bc *core.BlockChai
}
// generateNewState will construct most recent state from downloaded blocks
func (ss *StateSync) generateNewState(bc *core.BlockChain, worker *worker.Worker) error {
func (ss *StateSync) generateNewState(bc core.BlockChain, worker *worker.Worker) error {
// update blocks created before node start sync
parentHash := bc.CurrentBlock().Hash()
@ -973,7 +973,7 @@ func (ss *StateSync) generateNewState(bc *core.BlockChain, worker *worker.Worker
}
// ProcessStateSync processes state sync from the blocks received but not yet processed so far
func (ss *StateSync) ProcessStateSync(startHash []byte, size uint32, bc *core.BlockChain, worker *worker.Worker) error {
func (ss *StateSync) ProcessStateSync(startHash []byte, size uint32, bc core.BlockChain, worker *worker.Worker) error {
// Gets consensus hashes.
if err := ss.getConsensusHashes(startHash, size); err != nil {
return errors.Wrap(err, "getConsensusHashes")
@ -1072,7 +1072,7 @@ func (ss *StateSync) getMaxPeerHeight(isBeacon bool) uint64 {
}
// IsSameBlockchainHeight checks whether the node is out of sync from other peers
func (ss *StateSync) IsSameBlockchainHeight(bc *core.BlockChain) (uint64, bool) {
func (ss *StateSync) IsSameBlockchainHeight(bc core.BlockChain) (uint64, bool) {
otherHeight := ss.getMaxPeerHeight(false)
currentHeight := bc.CurrentBlock().NumberU64()
return otherHeight, currentHeight == otherHeight
@ -1084,7 +1084,7 @@ func (ss *StateSync) GetMaxPeerHeight() uint64 {
}
// SyncLoop will keep syncing with peers until catches up
func (ss *StateSync) SyncLoop(bc *core.BlockChain, worker *worker.Worker, isBeacon bool, consensus *consensus.Consensus) {
func (ss *StateSync) SyncLoop(bc core.BlockChain, worker *worker.Worker, isBeacon bool, consensus *consensus.Consensus) {
if !isBeacon {
ss.RegisterNodeInfo()
}
@ -1128,7 +1128,7 @@ func (ss *StateSync) SyncLoop(bc *core.BlockChain, worker *worker.Worker, isBeac
ss.purgeAllBlocksFromCache()
}
func (ss *StateSync) addConsensusLastMile(bc *core.BlockChain, consensus *consensus.Consensus) error {
func (ss *StateSync) addConsensusLastMile(bc core.BlockChain, consensus *consensus.Consensus) error {
curNumber := bc.CurrentBlock().NumberU64()
blockIter, err := consensus.GetLastMileBlockIter(curNumber + 1)
if err != nil {

@ -12,7 +12,7 @@ type Service struct {
}
// NewService creates the a new downloader service
func NewService(host p2p.Host, bcs []*core.BlockChain, config downloader.Config) *Service {
func NewService(host p2p.Host, bcs []core.BlockChain, config downloader.Config) *Service {
return &Service{
Downloaders: downloader.NewDownloaders(host, bcs, config),
}

@ -796,7 +796,7 @@ func setupPrometheusService(node *node.Node, hc harmonyconfig.HarmonyConfig, sid
}
func setupSyncService(node *node.Node, host p2p.Host, hc harmonyconfig.HarmonyConfig) {
blockchains := []*core.BlockChain{node.Blockchain()}
blockchains := []core.BlockChain{node.Blockchain()}
if !node.IsRunningBeaconChain() {
blockchains = append(blockchains, node.Beaconchain())
}

@ -62,7 +62,7 @@ type Consensus struct {
multiSigMutex sync.RWMutex
// The blockchain this consensus is working on
Blockchain *core.BlockChain
Blockchain core.BlockChain
// Minimal number of peers in the shard
// If the number of validators is less than minPeers, the consensus won't start
MinPeers int

@ -41,12 +41,12 @@ import (
// BlockValidator implements validator.
type BlockValidator struct {
config *params.ChainConfig // Chain configuration options
bc *BlockChain // Canonical block chain
bc BlockChain // Canonical blockchain
engine consensus_engine.Engine // Consensus engine used for validating
}
// NewBlockValidator returns a new block validator which is safe for re-use
func NewBlockValidator(config *params.ChainConfig, blockchain *BlockChain, engine consensus_engine.Engine) *BlockValidator {
func NewBlockValidator(config *params.ChainConfig, blockchain BlockChain, engine consensus_engine.Engine) *BlockValidator {
validator := &BlockValidator{
config: config,
engine: engine,

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -94,7 +94,7 @@ func (b *BlockGen) AddTx(tx *types.Transaction) {
// further limitations on the content of transactions that can be
// added. If contract code relies on the BLOCKHASH instruction,
// the block in chain will be returned.
func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction) {
func (b *BlockGen) AddTxWithChain(bc BlockChain, tx *types.Transaction) {
if b.gasPool == nil {
b.SetCoinbase(common.Address{})
}

@ -27,7 +27,7 @@ import (
staking "github.com/harmony-one/harmony/staking/types"
)
func getTestEnvironment(testBankKey ecdsa.PrivateKey) (*BlockChain, *state.DB, *block.Header, ethdb.Database) {
func getTestEnvironment(testBankKey ecdsa.PrivateKey) (*BlockChainImpl, *state.DB, *block.Header, ethdb.Database) {
// initialize
var (
testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)

@ -22,8 +22,7 @@ import (
"github.com/pkg/errors"
)
// CommitOffChainData write off chain data of a block onto db writer.
func (bc *BlockChain) CommitOffChainData(
func (bc *BlockChainImpl) CommitOffChainData(
batch rawdb.DatabaseWriter,
block *types.Block,
receipts []*types.Receipt,
@ -277,7 +276,7 @@ func (bc *BlockChain) CommitOffChainData(
return CanonStatTy, nil
}
func (bc *BlockChain) writeValidatorStats(
func (bc *BlockChainImpl) writeValidatorStats(
tempValidatorStats map[common.Address]*staking.ValidatorStats,
batch rawdb.DatabaseWriter,
) {
@ -311,7 +310,7 @@ func (bc *BlockChain) writeValidatorStats(
}
}
func (bc *BlockChain) getNextBlockEpoch(header *block.Header) (*big.Int, error) {
func (bc *BlockChainImpl) getNextBlockEpoch(header *block.Header) (*big.Int, error) {
nextBlockEpoch := header.Epoch()
if header.IsLastBlockInEpoch() {
nextBlockEpoch = new(big.Int).Add(header.Epoch(), common.Big1)

@ -49,7 +49,7 @@ const (
// StateProcessor implements Processor.
type StateProcessor struct {
config *params.ChainConfig // Chain configuration options
bc *BlockChain // Canonical block chain
bc BlockChain // Canonical block chain
engine consensus_engine.Engine // Consensus engine used for block rewards
resultCache *lru.Cache // Cache for result after a certain block is processed
}
@ -67,7 +67,7 @@ type ProcessorResult struct {
// NewStateProcessor initialises a new StateProcessor.
func NewStateProcessor(
config *params.ChainConfig, bc *BlockChain, engine consensus_engine.Engine,
config *params.ChainConfig, bc BlockChain, engine consensus_engine.Engine,
) *StateProcessor {
resultCache, _ := lru.New(resultCacheLimit)
return &StateProcessor{

@ -141,7 +141,7 @@ func pricedTransaction(shardID uint32, nonce uint64, gaslimit uint64, gasprice *
return signedTx
}
func createBlockChain() *BlockChain {
func createBlockChain() *BlockChainImpl {
key, _ := crypto.GenerateKey()
gspec := Genesis{
Config: params.TestChainConfig,

@ -44,7 +44,7 @@ type (
)
// NewDownloader creates a new downloader
func NewDownloader(host p2p.Host, bc *core.BlockChain, config Config) *Downloader {
func NewDownloader(host p2p.Host, bc core.BlockChain, config Config) *Downloader {
config.fixValues()
sp := sync.NewProtocol(sync.Config{

@ -15,7 +15,7 @@ type Downloaders struct {
}
// NewDownloaders creates Downloaders for sync of multiple blockchains
func NewDownloaders(host p2p.Host, bcs []*core.BlockChain, config Config) *Downloaders {
func NewDownloaders(host p2p.Host, bcs []core.BlockChain, config Config) *Downloaders {
ds := make(map[uint32]*Downloader)
for _, bc := range bcs {

@ -47,8 +47,8 @@ type Harmony struct {
// Channel for shutting down the service
ShutdownChan chan bool // Channel for shutting down the Harmony
BloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
BlockChain *core.BlockChain
BeaconChain *core.BlockChain
BlockChain core.BlockChain
BeaconChain core.BlockChain
TxPool *core.TxPool
CxPool *core.CxPool // CxPool is used to store the blockHashes of blocks containing cx receipts to be sent
// DB interfaces
@ -84,8 +84,8 @@ type Harmony struct {
type NodeAPI interface {
AddPendingStakingTransaction(*staking.StakingTransaction) error
AddPendingTransaction(newTx *types.Transaction) error
Blockchain() *core.BlockChain
Beaconchain() *core.BlockChain
Blockchain() core.BlockChain
Beaconchain() core.BlockChain
GetTransactionsHistory(address, txType, order string) ([]common.Hash, error)
GetStakingTransactionsHistory(address, txType, order string) ([]common.Hash, error)
GetTransactionsCount(address, txType string) (uint64, error)

@ -21,7 +21,7 @@ import (
type Collection interface {
// ShardChain returns the blockchain for the given shard,
// opening one as necessary.
ShardChain(shardID uint32) (*core.BlockChain, error)
ShardChain(shardID uint32) (core.BlockChain, error)
// CloseShardChain closes the given shard chain.
CloseShardChain(shardID uint32) error
@ -37,7 +37,7 @@ type CollectionImpl struct {
dbInit DBInitializer
engine engine.Engine
mtx sync.Mutex
pool map[uint32]*core.BlockChain
pool map[uint32]core.BlockChain
disableCache map[uint32]bool
chainConfig *params.ChainConfig
}
@ -56,7 +56,7 @@ func NewCollection(
dbFactory: dbFactory,
dbInit: dbInit,
engine: engine,
pool: make(map[uint32]*core.BlockChain),
pool: make(map[uint32]core.BlockChain),
disableCache: make(map[uint32]bool),
chainConfig: chainConfig,
}
@ -64,7 +64,7 @@ func NewCollection(
// ShardChain returns the blockchain for the given shard,
// opening one as necessary.
func (sc *CollectionImpl) ShardChain(shardID uint32) (*core.BlockChain, error) {
func (sc *CollectionImpl) ShardChain(shardID uint32) (core.BlockChain, error) {
sc.mtx.Lock()
defer sc.mtx.Unlock()
if bc, ok := sc.pool[shardID]; ok {
@ -148,7 +148,7 @@ func (sc *CollectionImpl) CloseShardChain(shardID uint32) error {
// Close closes all shard chains.
func (sc *CollectionImpl) Close() error {
newPool := make(map[uint32]*core.BlockChain)
newPool := make(map[uint32]core.BlockChain)
sc.mtx.Lock()
oldPool := sc.pool
sc.pool = newPool

@ -137,7 +137,7 @@ type Node struct {
}
// Blockchain returns the blockchain for the node's current shard.
func (node *Node) Blockchain() *core.BlockChain {
func (node *Node) Blockchain() core.BlockChain {
shardID := node.NodeConfig.ShardID
bc, err := node.shardChains.ShardChain(shardID)
if err != nil {
@ -150,7 +150,7 @@ func (node *Node) Blockchain() *core.BlockChain {
}
// Beaconchain returns the beaconchain from node.
func (node *Node) Beaconchain() *core.BlockChain {
func (node *Node) Beaconchain() core.BlockChain {
bc, err := node.shardChains.ShardChain(shard.BeaconChainShardID)
if err != nil {
utils.Logger().Error().Err(err).Msg("cannot get beaconchain")

@ -280,7 +280,7 @@ func (node *Node) BroadcastCrosslinkHeartbeatSignalFromBeaconToShards() { // lea
}
// getCrosslinkHeadersForShards get headers required for crosslink creation.
func getCrosslinkHeadersForShards(beacon *core.BlockChain, shardChain *core.BlockChain, curBlock *types.Block, shardID uint32, latestSentCrosslink *uint64) ([]*block.Header, error) {
func getCrosslinkHeadersForShards(beacon core.BlockChain, shardChain core.BlockChain, curBlock *types.Block, shardID uint32, latestSentCrosslink *uint64) ([]*block.Header, error) {
var headers []*block.Header
lastLink, err := beacon.ReadShardLastCrossLink(shardID)
var latestBlockNum uint64

@ -92,7 +92,7 @@ func (node *Node) IsSameHeight() (uint64, bool) {
return node.stateSync.IsSameBlockchainHeight(node.Blockchain())
}
func (node *Node) createStateSync(bc *core.BlockChain) *legacysync.StateSync {
func (node *Node) createStateSync(bc core.BlockChain) *legacysync.StateSync {
// Temp hack: The actual port used in dns sync is node.downloaderServer.Port.
// But registration is done through an old way of port arithmetics (syncPort + 3000).
// Thus for compatibility, we are doing the arithmetics here, and not to change the
@ -270,7 +270,7 @@ func (node *Node) doBeaconSyncing() {
}
// DoSyncing keep the node in sync with other peers, willJoinConsensus means the node will try to join consensus after catch up
func (node *Node) DoSyncing(bc *core.BlockChain, worker *worker.Worker, willJoinConsensus bool) {
func (node *Node) DoSyncing(bc core.BlockChain, worker *worker.Worker, willJoinConsensus bool) {
if node.NodeConfig.IsOffline {
return
}
@ -289,7 +289,7 @@ func (node *Node) DoSyncing(bc *core.BlockChain, worker *worker.Worker, willJoin
}
// doSync keep the node in sync with other peers, willJoinConsensus means the node will try to join consensus after catch up
func (node *Node) doSync(bc *core.BlockChain, worker *worker.Worker, willJoinConsensus bool) {
func (node *Node) doSync(bc core.BlockChain, worker *worker.Worker, willJoinConsensus bool) {
if node.stateSync.GetActivePeerNumber() < legacysync.NumPeersLowBound {
shardID := bc.ShardID()
peers, err := node.SyncingPeerProvider.SyncingPeers(shardID)

@ -56,7 +56,7 @@ type environment struct {
type Worker struct {
config *params.ChainConfig
factory blockfactory.Factory
chain *core.BlockChain
chain core.BlockChain
current *environment // An environment for current running cycle.
engine consensus_engine.Engine
gasFloor uint64
@ -566,7 +566,7 @@ func (w *Worker) FinalizeNewBlock(
// New create a new worker object.
func New(
config *params.ChainConfig, chain *core.BlockChain, engine consensus_engine.Engine,
config *params.ChainConfig, chain core.BlockChain, engine consensus_engine.Engine,
) *Worker {
worker := &Worker{
config: config,

@ -20,7 +20,7 @@ var (
// AggregateSigForCommittee ..
func AggregateSigForCommittee(
chain *core.BlockChain,
chain core.BlockChain,
committee *shard.Committee,
decider quorum.Decider,
aggSignature *bls.Sign,

@ -53,7 +53,7 @@ var (
allRandomUserAddress []common.Address
allRandomUserKey []*ecdsa.PrivateKey
faucetContractAddress common.Address
chain *core.BlockChain
chain core.BlockChain
err error
state *core_state.DB
)
@ -84,10 +84,10 @@ func init() {
type testWorkerBackend struct {
db ethdb.Database
txPool *core.TxPool
chain *core.BlockChain
chain *core.BlockChainImpl
}
func fundFaucetContract(chain *core.BlockChain) {
func fundFaucetContract(chain core.BlockChain) {
fmt.Println()
fmt.Println("--------- Funding addresses for Faucet Contract Call ---------")
fmt.Println()
@ -148,7 +148,7 @@ func fundFaucetContract(chain *core.BlockChain) {
fmt.Println("--------- Funding addresses for Faucet Contract Call DONE ---------")
}
func callFaucetContractToFundAnAddress(chain *core.BlockChain) {
func callFaucetContractToFundAnAddress(chain core.BlockChain) {
// Send Faucet Contract Transaction ///
fmt.Println("--------- Now Setting up Faucet Contract Call ---------")
fmt.Println()
@ -197,7 +197,7 @@ func callFaucetContractToFundAnAddress(chain *core.BlockChain) {
fmt.Println("--------- Faucet Contract Call DONE ---------")
}
func playFaucetContract(chain *core.BlockChain) {
func playFaucetContract(chain core.BlockChain) {
fundFaucetContract(chain)
callFaucetContractToFundAnAddress(chain)
}

Loading…
Cancel
Save