Skip to content

Commit

Permalink
consensus/dummy: reduce diff with subnet-evm (ava-labs#476)
Browse files Browse the repository at this point in the history
  • Loading branch information
darioush authored and oxbee committed Nov 6, 2024
1 parent 037132e commit fe2fc4f
Show file tree
Hide file tree
Showing 14 changed files with 85 additions and 65 deletions.
2 changes: 1 addition & 1 deletion accounts/abi/bind/backends/simulated.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.Genesis
Alloc: alloc,
}
cacheConfig := &core.CacheConfig{}
blockchain, _ := core.NewBlockChain(database, cacheConfig, &genesis, dummy.NewFaker(), vm.Config{}, common.Hash{}, false)
blockchain, _ := core.NewBlockChain(database, cacheConfig, &genesis, dummy.NewCoinbaseFaker(), vm.Config{}, common.Hash{}, false)

backend := &SimulatedBackend{
database: database,
Expand Down
67 changes: 42 additions & 25 deletions consensus/dummy/consensus.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ import (
"math/big"
"time"

"github.com/ava-labs/avalanchego/utils/timer/mockable"
"github.com/ava-labs/coreth/consensus"
"github.com/ava-labs/coreth/core/state"
"github.com/ava-labs/coreth/core/types"
"github.com/ava-labs/coreth/params"
"github.com/ava-labs/coreth/rpc"
"github.com/ava-labs/coreth/trie"
"github.com/ethereum/go-ethereum/common"
)
Expand All @@ -31,16 +31,14 @@ var (
errExtDataGasUsedTooLarge = errors.New("extDataGasUsed is not uint64")
)

type Mode uint

const (
ModeSkipHeader Mode = 1 // Skip over header verification
ModeSkipBlockFee Mode = 2 // Skip block fee verification
)
type Mode struct {
ModeSkipHeader bool
ModeSkipBlockFee bool
ModeSkipCoinbase bool
}

type (
OnFinalizeAndAssembleCallbackType = func(header *types.Header, state *state.StateDB, txs []*types.Transaction) (extraData []byte, blockFeeContribution *big.Int, extDataGasUsed *big.Int, err error)
OnAPIsCallbackType = func(consensus.ChainHeaderReader) []rpc.API
OnExtraStateChangeType = func(block *types.Block, statedb *state.StateDB) (blockFeeContribution *big.Int, extDataGasUsed *big.Int, err error)

ConsensusCallbacks struct {
Expand All @@ -49,39 +47,58 @@ type (
}

DummyEngine struct {
cb *ConsensusCallbacks
cb ConsensusCallbacks
clock *mockable.Clock
consensusMode Mode
}
)

func NewDummyEngine(cb *ConsensusCallbacks) *DummyEngine {
func NewETHFaker() *DummyEngine {
return &DummyEngine{
cb: cb,
clock: &mockable.Clock{},
consensusMode: Mode{ModeSkipBlockFee: true},
}
}

func NewETHFaker() *DummyEngine {
func NewFaker() *DummyEngine {
return &DummyEngine{
cb: new(ConsensusCallbacks),
consensusMode: ModeSkipBlockFee,
clock: &mockable.Clock{},
}
}

func NewComplexETHFaker(cb *ConsensusCallbacks) *DummyEngine {
func NewFakerWithClock(cb ConsensusCallbacks, clock *mockable.Clock) *DummyEngine {
return &DummyEngine{
cb: cb,
clock: clock,
}
}

func NewFakerWithCallbacks(cb ConsensusCallbacks) *DummyEngine {
return &DummyEngine{
cb: cb,
clock: &mockable.Clock{},
}
}

func NewFakerWithMode(cb ConsensusCallbacks, mode Mode) *DummyEngine {
return &DummyEngine{
cb: cb,
consensusMode: ModeSkipBlockFee,
clock: &mockable.Clock{},
consensusMode: mode,
}
}

func NewFaker() *DummyEngine {
return NewDummyEngine(new(ConsensusCallbacks))
func NewCoinbaseFaker() *DummyEngine {
return &DummyEngine{
clock: &mockable.Clock{},
consensusMode: Mode{ModeSkipCoinbase: true},
}
}

func NewFullFaker() *DummyEngine {
return &DummyEngine{
cb: new(ConsensusCallbacks),
consensusMode: ModeSkipHeader,
clock: &mockable.Clock{},
consensusMode: Mode{ModeSkipHeader: true},
}
}

Expand Down Expand Up @@ -212,7 +229,7 @@ func (self *DummyEngine) verifyHeader(chain consensus.ChainHeaderReader, header
}

// Verify the header's timestamp
if header.Time > uint64(time.Now().Add(allowedFutureBlockTime).Unix()) {
if header.Time > uint64(self.clock.Time().Add(allowedFutureBlockTime).Unix()) {
return consensus.ErrFutureBlock
}
// Verify the header's timestamp is not earlier than parent's
Expand Down Expand Up @@ -241,7 +258,7 @@ func (self *DummyEngine) Author(header *types.Header) (common.Address, error) {

func (self *DummyEngine) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header) error {
// If we're running a full engine faking, accept any input as valid
if self.consensusMode == ModeSkipHeader {
if self.consensusMode.ModeSkipHeader {
return nil
}
// Short circuit if the header is known, or it's parent not
Expand Down Expand Up @@ -276,7 +293,7 @@ func (self *DummyEngine) verifyBlockFee(
receipts []*types.Receipt,
extraStateChangeContribution *big.Int,
) error {
if self.consensusMode == ModeSkipBlockFee {
if self.consensusMode.ModeSkipBlockFee {
return nil
}
if baseFee == nil || baseFee.Sign() <= 0 {
Expand Down Expand Up @@ -442,8 +459,8 @@ func (self *DummyEngine) FinalizeAndAssemble(chain consensus.ChainHeaderReader,

// Header seems complete, assemble into a block and return
return types.NewBlockWithExtData(
header, txs, uncles, receipts, trie.NewStackTrie(nil), extraData,
chain.Config().IsApricotPhase1(header.Time),
header, txs, uncles, receipts, trie.NewStackTrie(nil),
extraData, chain.Config().IsApricotPhase1(header.Time),
), nil
}

Expand Down
4 changes: 2 additions & 2 deletions core/bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,11 +162,11 @@ func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) {
Config: params.TestChainConfig,
Alloc: GenesisAlloc{benchRootAddr: {Balance: benchRootFunds}},
}
_, chain, _, _ := GenerateChainWithGenesis(gspec, dummy.NewFaker(), b.N, 10, gen)
_, chain, _, _ := GenerateChainWithGenesis(gspec, dummy.NewCoinbaseFaker(), b.N, 10, gen)

// Time the insertion of the new chain.
// State and blocks are stored in the same DB.
chainman, _ := NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewFaker(), vm.Config{}, common.Hash{}, false)
chainman, _ := NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewCoinbaseFaker(), vm.Config{}, common.Hash{}, false)
defer chainman.Stop()
b.ReportAllocs()
b.ResetTimer()
Expand Down
2 changes: 1 addition & 1 deletion core/blockchain_log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func TestAcceptedLogsSubscription(t *testing.T) {
)
var (
require = require.New(t)
engine = dummy.NewFaker()
engine = dummy.NewCoinbaseFaker()
key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
addr1 = crypto.PubkeyToAddress(key1.PublicKey)
funds = new(big.Int).Mul(big.NewInt(100), big.NewInt(params.Ether))
Expand Down
14 changes: 7 additions & 7 deletions core/blockchain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func createBlockChain(
db,
cacheConfig,
gspec,
dummy.NewDummyEngine(&TestCallbacks),
dummy.NewFakerWithCallbacks(TestCallbacks),
vm.Config{},
lastAcceptedHash,
false,
Expand Down Expand Up @@ -648,14 +648,14 @@ func TestTransactionIndices(t *testing.T) {
}
signer = types.LatestSigner(gspec.Config)
)
genDb, blocks, _, err := GenerateChainWithGenesis(gspec, dummy.NewDummyEngine(&TestCallbacks), 128, 10, func(i int, block *BlockGen) {
genDb, blocks, _, err := GenerateChainWithGenesis(gspec, dummy.NewFakerWithCallbacks(TestCallbacks), 128, 10, func(i int, block *BlockGen) {
tx, err := types.SignTx(types.NewTransaction(block.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil), signer, key1)
require.NoError(err)
block.AddTx(tx)
})
require.NoError(err)

blocks2, _, err := GenerateChain(gspec.Config, blocks[len(blocks)-1], dummy.NewDummyEngine(&TestCallbacks), genDb, 10, 10, func(i int, block *BlockGen) {
blocks2, _, err := GenerateChain(gspec.Config, blocks[len(blocks)-1], dummy.NewFakerWithCallbacks(TestCallbacks), genDb, 10, 10, func(i int, block *BlockGen) {
tx, err := types.SignTx(types.NewTransaction(block.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil), signer, key1)
require.NoError(err)
block.AddTx(tx)
Expand Down Expand Up @@ -789,14 +789,14 @@ func TestTransactionSkipIndexing(t *testing.T) {
}
signer = types.LatestSigner(gspec.Config)
)
genDb, blocks, _, err := GenerateChainWithGenesis(gspec, dummy.NewDummyEngine(&TestCallbacks), 5, 10, func(i int, block *BlockGen) {
genDb, blocks, _, err := GenerateChainWithGenesis(gspec, dummy.NewFakerWithCallbacks(TestCallbacks), 5, 10, func(i int, block *BlockGen) {
tx, err := types.SignTx(types.NewTransaction(block.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil), signer, key1)
require.NoError(err)
block.AddTx(tx)
})
require.NoError(err)

blocks2, _, err := GenerateChain(gspec.Config, blocks[len(blocks)-1], dummy.NewDummyEngine(&TestCallbacks), genDb, 5, 10, func(i int, block *BlockGen) {
blocks2, _, err := GenerateChain(gspec.Config, blocks[len(blocks)-1], dummy.NewFakerWithCallbacks(TestCallbacks), genDb, 5, 10, func(i int, block *BlockGen) {
tx, err := types.SignTx(types.NewTransaction(block.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil), signer, key1)
require.NoError(err)
block.AddTx(tx)
Expand Down Expand Up @@ -936,7 +936,7 @@ func TestCanonicalHashMarker(t *testing.T) {
Alloc: GenesisAlloc{},
BaseFee: big.NewInt(params.ApricotPhase3InitialBaseFee),
}
engine = dummy.NewFaker()
engine = dummy.NewCoinbaseFaker()
)
_, forkA, _, err := GenerateChainWithGenesis(gspec, engine, c.forkA, 10, func(i int, gen *BlockGen) {})
if err != nil {
Expand Down Expand Up @@ -1242,7 +1242,7 @@ func TestEIP3651(t *testing.T) {
var (
aa = common.HexToAddress("0x000000000000000000000000000000000000aaaa")
bb = common.HexToAddress("0x000000000000000000000000000000000000bbbb")
engine = dummy.NewFaker()
engine = dummy.NewCoinbaseFaker()

// A sender who makes transactions, has some funds
key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
Expand Down
4 changes: 2 additions & 2 deletions core/chain_makers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func ExampleGenerateChain() {
// each block and adds different features to gen based on the
// block index.
signer := types.HomesteadSigner{}
_, chain, _, err := GenerateChainWithGenesis(gspec, dummy.NewFaker(), 3, 10, func(i int, gen *BlockGen) {
_, chain, _, err := GenerateChainWithGenesis(gspec, dummy.NewCoinbaseFaker(), 3, 10, func(i int, gen *BlockGen) {
switch i {
case 0:
// In block 1, addr1 sends addr2 some ether.
Expand All @@ -81,7 +81,7 @@ func ExampleGenerateChain() {
}

// Import the chain. This runs all block validation rules.
blockchain, _ := NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewFaker(), vm.Config{}, common.Hash{}, false)
blockchain, _ := NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewCoinbaseFaker(), vm.Config{}, common.Hash{}, false)
defer blockchain.Stop()

if i, err := blockchain.InsertChain(chain); err != nil {
Expand Down
6 changes: 3 additions & 3 deletions core/headerchain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,18 +80,18 @@ func TestHeaderInsertion(t *testing.T) {
}
)
genesis := gspec.ToBlock()
chain, err := NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewFaker(), vm.Config{}, common.Hash{}, false)
chain, err := NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewCoinbaseFaker(), vm.Config{}, common.Hash{}, false)
if err != nil {
t.Fatal(err)
}
defer chain.Stop()

// chain A: G->A1->A2...A128
chainA, _, _ := GenerateChain(params.TestChainConfig, types.NewBlockWithHeader(genesis.Header()), dummy.NewFaker(), db, 128, 10, func(i int, b *BlockGen) {
chainA, _, _ := GenerateChain(params.TestChainConfig, types.NewBlockWithHeader(genesis.Header()), dummy.NewCoinbaseFaker(), db, 128, 10, func(i int, b *BlockGen) {
b.SetCoinbase(common.Address{0: byte(10), 19: byte(i)})
})
// chain B: G->A1->B2...B128
chainB, _, _ := GenerateChain(params.TestChainConfig, types.NewBlockWithHeader(chainA[0].Header()), dummy.NewFaker(), db, 128, 10, func(i int, b *BlockGen) {
chainB, _, _ := GenerateChain(params.TestChainConfig, types.NewBlockWithHeader(chainA[0].Header()), dummy.NewCoinbaseFaker(), db, 128, 10, func(i int, b *BlockGen) {
b.SetCoinbase(common.Address{0: byte(10), 19: byte(i)})
})

Expand Down
16 changes: 8 additions & 8 deletions core/state_processor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func TestStateProcessorErrors(t *testing.T) {
},
GasLimit: params.CortinaGasLimit,
}
blockchain, _ = NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewFaker(), vm.Config{}, common.Hash{}, false)
blockchain, _ = NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewCoinbaseFaker(), vm.Config{}, common.Hash{}, false)
)
defer blockchain.Stop()
bigNumber := new(big.Int).SetBytes(common.FromHex("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"))
Expand Down Expand Up @@ -203,7 +203,7 @@ func TestStateProcessorErrors(t *testing.T) {
want: "could not apply tx 0 [0xd82a0c2519acfeac9a948258c47e784acd20651d9d80f9a1c67b4137651c3a24]: insufficient funds for gas * price + value: address 0x71562b71999873DB5b286dF957af199Ec94617F7 have 4000000000000000000 want 2431633873983640103894990685182446064918669677978451844828609264166175722438635000",
},
} {
block := GenerateBadBlock(gspec.ToBlock(), dummy.NewFaker(), tt.txs, gspec.Config)
block := GenerateBadBlock(gspec.ToBlock(), dummy.NewCoinbaseFaker(), tt.txs, gspec.Config)
_, err := blockchain.InsertChain(types.Blocks{block})
if err == nil {
t.Fatal("block imported without errors")
Expand Down Expand Up @@ -241,7 +241,7 @@ func TestStateProcessorErrors(t *testing.T) {
},
GasLimit: params.ApricotPhase1GasLimit,
}
blockchain, _ = NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewFaker(), vm.Config{}, common.Hash{}, false)
blockchain, _ = NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewCoinbaseFaker(), vm.Config{}, common.Hash{}, false)
)
defer blockchain.Stop()
for i, tt := range []struct {
Expand All @@ -255,7 +255,7 @@ func TestStateProcessorErrors(t *testing.T) {
want: "could not apply tx 0 [0x88626ac0d53cb65308f2416103c62bb1f18b805573d4f96a3640bbbfff13c14f]: transaction type not supported",
},
} {
block := GenerateBadBlock(gspec.ToBlock(), dummy.NewFaker(), tt.txs, gspec.Config)
block := GenerateBadBlock(gspec.ToBlock(), dummy.NewCoinbaseFaker(), tt.txs, gspec.Config)
_, err := blockchain.InsertChain(types.Blocks{block})
if err == nil {
t.Fatal("block imported without errors")
Expand All @@ -281,7 +281,7 @@ func TestStateProcessorErrors(t *testing.T) {
},
GasLimit: params.CortinaGasLimit,
}
blockchain, _ = NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewFaker(), vm.Config{}, common.Hash{}, false)
blockchain, _ = NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewCoinbaseFaker(), vm.Config{}, common.Hash{}, false)
)
defer blockchain.Stop()
for i, tt := range []struct {
Expand All @@ -295,7 +295,7 @@ func TestStateProcessorErrors(t *testing.T) {
want: "could not apply tx 0 [0x88626ac0d53cb65308f2416103c62bb1f18b805573d4f96a3640bbbfff13c14f]: sender not an eoa: address 0x71562b71999873DB5b286dF957af199Ec94617F7, codehash: 0x9280914443471259d4570a8661015ae4a5b80186dbc619658fb494bebc3da3d1",
},
} {
block := GenerateBadBlock(gspec.ToBlock(), dummy.NewFaker(), tt.txs, gspec.Config)
block := GenerateBadBlock(gspec.ToBlock(), dummy.NewCoinbaseFaker(), tt.txs, gspec.Config)
_, err := blockchain.InsertChain(types.Blocks{block})
if err == nil {
t.Fatal("block imported without errors")
Expand Down Expand Up @@ -344,7 +344,7 @@ func TestStateProcessorErrors(t *testing.T) {
},
GasLimit: params.CortinaGasLimit,
}
blockchain, _ = NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewFaker(), vm.Config{}, common.Hash{}, false)
blockchain, _ = NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewCoinbaseFaker(), vm.Config{}, common.Hash{}, false)
tooBigInitCode = [params.MaxInitCodeSize + 1]byte{}
smallInitCode = [320]byte{}
)
Expand All @@ -366,7 +366,7 @@ func TestStateProcessorErrors(t *testing.T) {
want: "could not apply tx 0 [0x849278f616d51ab56bba399551317213ce7a10e4d9cbc3d14bb663e50cb7ab99]: intrinsic gas too low: have 54299, want 54300",
},
} {
block := GenerateBadBlock(gspec.ToBlock(), dummy.NewFaker(), tt.txs, gspec.Config)
block := GenerateBadBlock(gspec.ToBlock(), dummy.NewCoinbaseFaker(), tt.txs, gspec.Config)
_, err := blockchain.InsertChain(types.Blocks{block})
if err == nil {
t.Fatal("block imported without errors")
Expand Down
2 changes: 1 addition & 1 deletion core/test_blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -1341,7 +1341,7 @@ func TestInsertChainInvalidBlockFee(t *testing.T, create func(db ethdb.Database,

// This call generates a chain of 3 blocks.
signer := types.LatestSigner(params.TestChainConfig)
eng := dummy.NewComplexETHFaker(&TestCallbacks)
eng := dummy.NewFakerWithMode(TestCallbacks, dummy.Mode{ModeSkipBlockFee: true, ModeSkipCoinbase: true})
_, chain, _, err := GenerateChainWithGenesis(gspec, eng, 3, 0, func(i int, gen *BlockGen) {
tx := types.NewTx(&types.DynamicFeeTx{
ChainID: params.TestChainConfig.ChainID,
Expand Down
4 changes: 2 additions & 2 deletions eth/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func roundUpCacheSize(input int, allocSize int) int {
func New(
stack *node.Node,
config *Config,
cb *dummy.ConsensusCallbacks,
cb dummy.ConsensusCallbacks,
chainDb ethdb.Database,
settings Settings,
lastAcceptedHash common.Hash,
Expand Down Expand Up @@ -154,7 +154,7 @@ func New(
chainDb: chainDb,
eventMux: new(event.TypeMux),
accountManager: stack.AccountManager(),
engine: dummy.NewDummyEngine(cb),
engine: dummy.NewFakerWithClock(cb, clock),
closeBloomHandler: make(chan struct{}),
networkID: config.NetworkId,
etherbase: config.Miner.Etherbase,
Expand Down
2 changes: 1 addition & 1 deletion eth/gasprice/gasprice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func newTestBackend(t *testing.T, config *params.ChainConfig, numBlocks int, ext
Alloc: core.GenesisAlloc{addr: core.GenesisAccount{Balance: bal}},
}

engine := dummy.NewDummyEngine(&dummy.ConsensusCallbacks{
engine := dummy.NewFakerWithCallbacks(dummy.ConsensusCallbacks{
OnFinalizeAndAssemble: func(header *types.Header, state *state.StateDB, txs []*types.Transaction) ([]byte, *big.Int, *big.Int, error) {
return nil, common.Big0, extDataGasUsage, nil
},
Expand Down
2 changes: 1 addition & 1 deletion internal/ethapi/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ type testBackend struct {

func newTestBackend(t *testing.T, n int, gspec *core.Genesis, generator func(i int, b *core.BlockGen)) *testBackend {
var (
engine = dummy.NewETHFaker()
engine = dummy.NewCoinbaseFaker()
backend = &testBackend{
db: rawdb.NewMemoryDatabase(),
}
Expand Down
Loading

0 comments on commit fe2fc4f

Please sign in to comment.