From 9d2e5a0c39be5b783c189e6d8883a5e192c5991a Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 15 Oct 2024 20:22:00 -0700 Subject: [PATCH 01/69] fix chainID in TestWaitDeployedCornerCases (#670) --- accounts/abi/bind/util_test.go | 12 ++++++++---- scripts/known_flakes.txt | 1 + 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/accounts/abi/bind/util_test.go b/accounts/abi/bind/util_test.go index d5754c603a..3eddeec0b1 100644 --- a/accounts/abi/bind/util_test.go +++ b/accounts/abi/bind/util_test.go @@ -125,10 +125,12 @@ func TestWaitDeployedCornerCases(t *testing.T) { // Create a transaction to an account. code := "6060604052600a8060106000396000f360606040526008565b00" tx := types.NewTransaction(0, common.HexToAddress("0x01"), big.NewInt(0), 3000000, gasPrice, common.FromHex(code)) - tx, _ = types.SignTx(tx, types.LatestSigner(params.TestChainConfig), testKey) + tx, _ = types.SignTx(tx, types.LatestSignerForChainID(big.NewInt(1337)), testKey) ctx, cancel := context.WithCancel(context.Background()) defer cancel() - backend.Client().SendTransaction(ctx, tx) + if err := backend.Client().SendTransaction(ctx, tx); err != nil { + t.Fatalf("Failed to send transaction: %s", err) + } backend.Commit(true) notContractCreation := errors.New("tx is not contract creation") if _, err := bind.WaitDeployed(ctx, backend.Client(), tx); err.Error() != notContractCreation.Error() { @@ -137,7 +139,7 @@ func TestWaitDeployedCornerCases(t *testing.T) { // Create a transaction that is not mined. tx = types.NewContractCreation(1, big.NewInt(0), 3000000, gasPrice, common.FromHex(code)) - tx, _ = types.SignTx(tx, types.LatestSigner(params.TestChainConfig), testKey) + tx, _ = types.SignTx(tx, types.LatestSignerForChainID(big.NewInt(1337)), testKey) go func() { contextCanceled := errors.New("context canceled") @@ -146,6 +148,8 @@ func TestWaitDeployedCornerCases(t *testing.T) { } }() - backend.Client().SendTransaction(ctx, tx) + if err := backend.Client().SendTransaction(ctx, tx); err != nil { + t.Fatalf("Failed to send transaction: %s", err) + } cancel() } diff --git a/scripts/known_flakes.txt b/scripts/known_flakes.txt index 05c41794ba..b28b4e710c 100644 --- a/scripts/known_flakes.txt +++ b/scripts/known_flakes.txt @@ -7,5 +7,6 @@ TestResumeSyncAccountsTrieInterrupted TestResyncNewRootAfterDeletes TestTransactionSkipIndexing TestVMShutdownWhileSyncing +TestWaitDeployedCornerCases TestWalletNotifications TestWebsocketLargeRead \ No newline at end of file From 4c5617b03f7857cec6cfd788cd75a16ddeba85bc Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Mon, 28 Oct 2024 07:59:24 -0700 Subject: [PATCH 02/69] ci: fix windows flake test detection (#677) --- scripts/build_test.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build_test.sh b/scripts/build_test.sh index 460ebcd564..c3fb241349 100755 --- a/scripts/build_test.sh +++ b/scripts/build_test.sh @@ -41,7 +41,7 @@ do unexpected_failures=$( # First grep pattern corresponds to test failures, second pattern corresponds to test panics due to timeouts (grep "^--- FAIL" test.out | awk '{print $3}' || grep -E '^\s+Test.+ \(' test.out | awk '{print $1}') | - sort -u | comm -23 - ./scripts/known_flakes.txt + sort -u | comm -23 - <(sed 's/\r$//' ./scripts/known_flakes.txt) ) if [ -n "${unexpected_failures}" ]; then echo "Unexpected test failures: ${unexpected_failures}" From 3abb04ce2f62b0539bde5eb88e0b55b1f5e7e745 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Wed, 13 Nov 2024 14:42:19 -0800 Subject: [PATCH 03/69] sync subnet-evm to 981830ed + avalanchego v1.12.0-initial-poc.9 (#686) --- .github/pull_request_template.md | 4 + README.md | 2 +- core/blockchain.go | 18 +- core/chain_makers.go | 2 +- core/genesis.go | 2 +- core/state/state_test.go | 8 +- core/state/statedb.go | 20 +- core/state/statedb_fuzz_test.go | 2 +- core/state/statedb_test.go | 36 +-- core/state/sync_test.go | 2 +- core/test_blockchain.go | 2 +- core/txpool/blobpool/blobpool_test.go | 12 +- eth/api_debug_test.go | 6 +- eth/state_accessor.go | 7 +- go.mod | 28 +-- go.sum | 61 +++-- plugin/evm/block.go | 29 +-- plugin/evm/gossip_test.go | 2 +- plugin/evm/import_tx.go | 2 +- plugin/evm/shared_memory_writer.go | 37 --- plugin/evm/syncervm_test.go | 2 +- plugin/evm/tx.go | 11 + plugin/evm/tx_gossip_test.go | 38 +-- plugin/evm/vm.go | 176 ++++++++------ plugin/evm/vm_warp_test.go | 115 +++++++-- precompile/precompileconfig/config.go | 13 +- scripts/versions.sh | 2 +- tests/state_test_util.go | 2 +- triedb/database.go | 11 - triedb/hashdb/database.go | 39 ++- utils/snow.go | 55 ++++- warp/backend.go | 114 ++++----- warp/backend_test.go | 77 ++---- warp/handlers/signature_request.go | 22 +- warp/handlers/signature_request_p2p.go | 151 ------------ warp/handlers/signature_request_p2p_test.go | 232 ------------------ warp/handlers/signature_request_test.go | 15 +- warp/handlers/stats.go | 26 +- warp/service.go | 8 +- warp/verifier_backend.go | 64 +++++ warp/verifier_backend_test.go | 255 ++++++++++++++++++++ warp/verifier_stats.go | 29 +++ 42 files changed, 854 insertions(+), 885 deletions(-) delete mode 100644 plugin/evm/shared_memory_writer.go delete mode 100644 warp/handlers/signature_request_p2p.go delete mode 100644 warp/handlers/signature_request_p2p_test.go create mode 100644 warp/verifier_backend.go create mode 100644 warp/verifier_backend_test.go create mode 100644 warp/verifier_stats.go diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 8200c0597f..7751a8146f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -3,3 +3,7 @@ ## How this works ## How this was tested + +## Need to be documented? + +## Need to update RELEASES.md? diff --git a/README.md b/README.md index 69a11a6c43..40cd3a8407 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [Avalanche](https://docs.avax.network/intro) is a network composed of multiple blockchains. Each blockchain is an instance of a Virtual Machine (VM), much like an object in an object-oriented language is an instance of a class. That is, the VM defines the behavior of the blockchain. -Coreth (from core Ethereum) is the [Virtual Machine (VM)](https://docs.avax.network/learn/avalanche/virtual-machines) that defines the Contract Chain (C-Chain). +Coreth (from core Ethereum) is the [Virtual Machine (VM)](https://docs.avax.network/learn/virtual-machines) that defines the Contract Chain (C-Chain). This chain implements the Ethereum Virtual Machine and supports Solidity smart contracts as well as most other Ethereum client functionality. ## Building diff --git a/core/blockchain.go b/core/blockchain.go index 2dcd2738a6..db3a49bdb0 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -177,10 +177,11 @@ type CacheConfig struct { // triedbConfig derives the configures for trie database. func (c *CacheConfig) triedbConfig() *triedb.Config { config := &triedb.Config{Preimages: c.Preimages} - if c.StateScheme == rawdb.HashScheme { + if c.StateScheme == rawdb.HashScheme || c.StateScheme == "" { config.HashDB = &hashdb.Config{ - CleanCacheSize: c.TrieCleanLimit * 1024 * 1024, - StatsPrefix: trieCleanCacheStatsNamespace, + CleanCacheSize: c.TrieCleanLimit * 1024 * 1024, + StatsPrefix: trieCleanCacheStatsNamespace, + ReferenceRootAtomicallyOnUpdate: true, } } if c.StateScheme == rawdb.PathScheme { @@ -1161,9 +1162,9 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types. // diff layer for the block. var err error if bc.snaps == nil { - _, err = state.Commit(block.NumberU64(), bc.chainConfig.IsEIP158(block.Number()), true) + _, err = state.Commit(block.NumberU64(), bc.chainConfig.IsEIP158(block.Number())) } else { - _, err = state.CommitWithSnap(block.NumberU64(), bc.chainConfig.IsEIP158(block.Number()), bc.snaps, block.Hash(), block.ParentHash(), true) + _, err = state.CommitWithSnap(block.NumberU64(), bc.chainConfig.IsEIP158(block.Number()), bc.snaps, block.Hash(), block.ParentHash()) } if err != nil { return err @@ -1695,9 +1696,9 @@ func (bc *BlockChain) reprocessBlock(parent *types.Block, current *types.Block) // If snapshots are enabled, call CommitWithSnaps to explicitly create a snapshot // diff layer for the block. if bc.snaps == nil { - return statedb.Commit(current.NumberU64(), bc.chainConfig.IsEIP158(current.Number()), false) + return statedb.Commit(current.NumberU64(), bc.chainConfig.IsEIP158(current.Number())) } - return statedb.CommitWithSnap(current.NumberU64(), bc.chainConfig.IsEIP158(current.Number()), bc.snaps, current.Hash(), current.ParentHash(), false) + return statedb.CommitWithSnap(current.NumberU64(), bc.chainConfig.IsEIP158(current.Number()), bc.snaps, current.Hash(), current.ParentHash()) } // initSnapshot instantiates a Snapshot instance and adds it to [bc] @@ -1838,8 +1839,7 @@ func (bc *BlockChain) reprocessState(current *types.Block, reexec uint64) error // Flatten snapshot if initialized, holding a reference to the state root until the next block // is processed. if err := bc.flattenSnapshot(func() error { - triedb.Reference(root, common.Hash{}) - if previousRoot != (common.Hash{}) { + if previousRoot != (common.Hash{}) && previousRoot != root { triedb.Dereference(previousRoot) } previousRoot = root diff --git a/core/chain_makers.go b/core/chain_makers.go index f8831ade81..d5ffd53074 100644 --- a/core/chain_makers.go +++ b/core/chain_makers.go @@ -298,7 +298,7 @@ func GenerateChain(config *params.ChainConfig, parent *types.Block, engine conse } // Write state changes to db - root, err := statedb.Commit(b.header.Number.Uint64(), config.IsEIP158(b.header.Number), false) + root, err := statedb.Commit(b.header.Number.Uint64(), config.IsEIP158(b.header.Number)) if err != nil { panic(fmt.Sprintf("state write error: %v", err)) } diff --git a/core/genesis.go b/core/genesis.go index 494a16f81c..07d3ba072d 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -299,7 +299,7 @@ func (g *Genesis) toBlock(db ethdb.Database, triedb *triedb.Database) *types.Blo } } - statedb.Commit(0, false, false) + statedb.Commit(0, false) // Commit newly generated states into disk if it's not empty. if root != types.EmptyRootHash { if err := triedb.Commit(root, true); err != nil { diff --git a/core/state/state_test.go b/core/state/state_test.go index 0d6f7d6445..3d6dadf209 100644 --- a/core/state/state_test.go +++ b/core/state/state_test.go @@ -68,7 +68,7 @@ func TestDump(t *testing.T) { // write some of them to the trie s.state.updateStateObject(obj1) s.state.updateStateObject(obj2) - root, _ := s.state.Commit(0, false, false) + root, _ := s.state.Commit(0, false) // check that DumpToCollector contains the state objects that are in trie s.state, _ = New(root, tdb, nil) @@ -130,7 +130,7 @@ func TestIterativeDump(t *testing.T) { // write some of them to the trie s.state.updateStateObject(obj1) s.state.updateStateObject(obj2) - root, _ := s.state.Commit(0, false, false) + root, _ := s.state.Commit(0, false) s.state, _ = New(root, tdb, nil) b := &bytes.Buffer{} @@ -156,7 +156,7 @@ func TestNull(t *testing.T) { var value common.Hash s.state.SetState(address, common.Hash{}, value) - s.state.Commit(0, false, false) + s.state.Commit(0, false) if value := s.state.GetState(address, common.Hash{}); value != (common.Hash{}) { t.Errorf("expected empty current value, got %x", value) @@ -228,7 +228,7 @@ func TestSnapshot2(t *testing.T) { so0.deleted = false state.setStateObject(so0) - root, _ := state.Commit(0, false, false) + root, _ := state.Commit(0, false) state, _ = New(root, state.db, nil) // and one with deleted == true diff --git a/core/state/statedb.go b/core/state/statedb.go index 9eda070321..3096589b6e 100644 --- a/core/state/statedb.go +++ b/core/state/statedb.go @@ -1263,14 +1263,14 @@ func (s *StateDB) handleDestruction(nodes *trienode.MergedNodeSet) (map[common.A } // Commit writes the state to the underlying in-memory trie database. -func (s *StateDB) Commit(block uint64, deleteEmptyObjects bool, referenceRoot bool) (common.Hash, error) { - return s.commit(block, deleteEmptyObjects, nil, common.Hash{}, common.Hash{}, referenceRoot) +func (s *StateDB) Commit(block uint64, deleteEmptyObjects bool) (common.Hash, error) { + return s.commit(block, deleteEmptyObjects, nil, common.Hash{}, common.Hash{}) } // CommitWithSnap writes the state to the underlying in-memory trie database and // generates a snapshot layer for the newly committed state. -func (s *StateDB) CommitWithSnap(block uint64, deleteEmptyObjects bool, snaps *snapshot.Tree, blockHash, parentHash common.Hash, referenceRoot bool) (common.Hash, error) { - return s.commit(block, deleteEmptyObjects, snaps, blockHash, parentHash, referenceRoot) +func (s *StateDB) CommitWithSnap(block uint64, deleteEmptyObjects bool, snaps *snapshot.Tree, blockHash, parentHash common.Hash) (common.Hash, error) { + return s.commit(block, deleteEmptyObjects, snaps, blockHash, parentHash) } // Once the state is committed, tries cached in stateDB (including account @@ -1280,7 +1280,7 @@ func (s *StateDB) CommitWithSnap(block uint64, deleteEmptyObjects bool, snaps *s // // The associated block number of the state transition is also provided // for more chain context. -func (s *StateDB) commit(block uint64, deleteEmptyObjects bool, snaps *snapshot.Tree, blockHash, parentHash common.Hash, referenceRoot bool) (common.Hash, error) { +func (s *StateDB) commit(block uint64, deleteEmptyObjects bool, snaps *snapshot.Tree, blockHash, parentHash common.Hash) (common.Hash, error) { // Short circuit in case any database failure occurred earlier. if s.dbErr != nil { return common.Hash{}, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr) @@ -1389,14 +1389,8 @@ func (s *StateDB) commit(block uint64, deleteEmptyObjects bool, snaps *snapshot. if root != origin { start := time.Now() set := triestate.New(s.accountsOrigin, s.storagesOrigin, incomplete) - if referenceRoot { - if err := s.db.TrieDB().UpdateAndReferenceRoot(root, origin, block, nodes, set); err != nil { - return common.Hash{}, err - } - } else { - if err := s.db.TrieDB().Update(root, origin, block, nodes, set); err != nil { - return common.Hash{}, err - } + if err := s.db.TrieDB().Update(root, origin, block, nodes, set); err != nil { + return common.Hash{}, err } s.originalRoot = root if metrics.EnabledExpensive { diff --git a/core/state/statedb_fuzz_test.go b/core/state/statedb_fuzz_test.go index f694cb2a0f..9cbbffa870 100644 --- a/core/state/statedb_fuzz_test.go +++ b/core/state/statedb_fuzz_test.go @@ -233,7 +233,7 @@ func (test *stateTest) run() bool { } else { state.IntermediateRoot(true) // call intermediateRoot at the transaction boundary } - nroot, err := state.Commit(0, true, false) // call commit at the block boundary + nroot, err := state.Commit(0, true) // call commit at the block boundary if err != nil { panic(err) } diff --git a/core/state/statedb_test.go b/core/state/statedb_test.go index 7ae230fbed..88799e3c3e 100644 --- a/core/state/statedb_test.go +++ b/core/state/statedb_test.go @@ -127,7 +127,7 @@ func TestIntermediateLeaks(t *testing.T) { } // Commit and cross check the databases. - transRoot, err := transState.Commit(0, false, false) + transRoot, err := transState.Commit(0, false) if err != nil { t.Fatalf("failed to commit transition state: %v", err) } @@ -135,7 +135,7 @@ func TestIntermediateLeaks(t *testing.T) { t.Errorf("can not commit trie %v to persistent database", transRoot.Hex()) } - finalRoot, err := finalState.Commit(0, false, false) + finalRoot, err := finalState.Commit(0, false) if err != nil { t.Fatalf("failed to commit final state: %v", err) } @@ -543,7 +543,7 @@ func (test *snapshotTest) checkEqual(state, checkstate *StateDB) error { func TestTouchDelete(t *testing.T) { s := newStateEnv() s.state.getOrNewStateObject(common.Address{}) - root, _ := s.state.Commit(0, false, false) + root, _ := s.state.Commit(0, false) s.state, _ = NewWithSnapshot(root, s.state.db, s.state.snap) snapshot := s.state.Snapshot() @@ -631,7 +631,7 @@ func TestCopyCommitCopy(t *testing.T) { t.Fatalf("second copy committed storage slot mismatch: have %x, want %x", val, sval) } // Commit state, ensure states can be loaded from disk - root, _ := state.Commit(0, false, false) + root, _ := state.Commit(0, false) state, _ = New(root, tdb, nil) if balance := state.GetBalance(addr); balance.Cmp(uint256.NewInt(42)) != 0 { t.Fatalf("state post-commit balance mismatch: have %v, want %v", balance, 42) @@ -745,7 +745,7 @@ func TestCommitCopy(t *testing.T) { t.Fatalf("initial committed storage slot mismatch: have %x, want %x", val, common.Hash{}) } // Copy the committed state database, the copied one is not functional. - state.Commit(0, true, false) + state.Commit(0, true) copied := state.Copy() if balance := copied.GetBalance(addr); balance.Cmp(uint256.NewInt(0)) != 0 { t.Fatalf("unexpected balance: have %v", balance) @@ -779,7 +779,7 @@ func TestDeleteCreateRevert(t *testing.T) { addr := common.BytesToAddress([]byte("so")) state.SetBalance(addr, uint256.NewInt(1)) - root, _ := state.Commit(0, false, false) + root, _ := state.Commit(0, false) state, _ = NewWithSnapshot(root, state.db, state.snap) // Simulate self-destructing in one transaction, then create-reverting in another @@ -791,7 +791,7 @@ func TestDeleteCreateRevert(t *testing.T) { state.RevertToSnapshot(id) // Commit the entire state and make sure we don't crash and have the correct state - root, _ = state.Commit(0, true, false) + root, _ = state.Commit(0, true) state, _ = NewWithSnapshot(root, state.db, state.snap) if state.getStateObject(addr) != nil { @@ -834,7 +834,7 @@ func testMissingTrieNodes(t *testing.T, scheme string) { a2 := common.BytesToAddress([]byte("another")) state.SetBalance(a2, uint256.NewInt(100)) state.SetCode(a2, []byte{1, 2, 4}) - root, _ = state.Commit(0, false, false) + root, _ = state.Commit(0, false) t.Logf("root: %x", root) // force-flush tdb.Commit(root, false) @@ -858,7 +858,7 @@ func testMissingTrieNodes(t *testing.T, scheme string) { } // Modify the state state.SetBalance(addr, uint256.NewInt(2)) - root, err := state.Commit(0, false, false) + root, err := state.Commit(0, false) if err == nil { t.Fatalf("expected error, got root :%x", root) } @@ -1044,7 +1044,7 @@ func TestMultiCoinOperations(t *testing.T) { assetID := common.Hash{2} s.state.getOrNewStateObject(addr) - root, _ := s.state.Commit(0, false, false) + root, _ := s.state.Commit(0, false) s.state, _ = NewWithSnapshot(root, s.state.db, s.state.snap) s.state.AddBalance(addr, new(uint256.Int)) @@ -1101,14 +1101,14 @@ func TestMultiCoinSnapshot(t *testing.T) { assertBalances(10, 0, 0) // Commit and get the new root - root, _ = stateDB.Commit(0, false, false) + root, _ = stateDB.Commit(0, false) assertBalances(10, 0, 0) // Create a new state from the latest root, add a multicoin balance, and // commit it to the tree. stateDB, _ = New(root, sdb, snapTree) stateDB.AddBalanceMultiCoin(addr, assetID1, big.NewInt(10)) - root, _ = stateDB.Commit(0, false, false) + root, _ = stateDB.Commit(0, false) assertBalances(10, 10, 0) // Add more layers than the cap and ensure the balances and layers are correct @@ -1116,7 +1116,7 @@ func TestMultiCoinSnapshot(t *testing.T) { stateDB, _ = New(root, sdb, snapTree) stateDB.AddBalanceMultiCoin(addr, assetID1, big.NewInt(1)) stateDB.AddBalanceMultiCoin(addr, assetID2, big.NewInt(2)) - root, _ = stateDB.Commit(0, false, false) + root, _ = stateDB.Commit(0, false) } assertBalances(10, 266, 512) @@ -1125,7 +1125,7 @@ func TestMultiCoinSnapshot(t *testing.T) { stateDB, _ = New(root, sdb, snapTree) stateDB.AddBalance(addr, uint256.NewInt(1)) stateDB.AddBalanceMultiCoin(addr, assetID1, big.NewInt(1)) - root, _ = stateDB.Commit(0, false, false) + root, _ = stateDB.Commit(0, false) stateDB, _ = New(root, sdb, snapTree) assertBalances(11, 267, 512) } @@ -1147,7 +1147,7 @@ func TestGenerateMultiCoinAccounts(t *testing.T) { t.Fatal(err) } stateDB.SetBalanceMultiCoin(addr, assetID, assetBalance) - root, err := stateDB.Commit(0, false, false) + root, err := stateDB.Commit(0, false) if err != nil { t.Fatal(err) } @@ -1207,7 +1207,7 @@ func TestFlushOrderDataLoss(t *testing.T) { state.SetState(common.Address{a}, common.Hash{a, s}, common.Hash{a, s}) } } - root, err := state.Commit(0, false, false) + root, err := state.Commit(0, false) if err != nil { t.Fatalf("failed to commit state trie: %v", err) } @@ -1286,7 +1286,7 @@ func TestResetObject(t *testing.T) { state.CreateAccount(addr) state.SetBalance(addr, uint256.NewInt(2)) state.SetState(addr, slotB, common.BytesToHash([]byte{0x2})) - root, _ := state.CommitWithSnap(0, true, snaps, common.Hash{}, common.Hash{}, false) + root, _ := state.CommitWithSnap(0, true, snaps, common.Hash{}, common.Hash{}) // Ensure the original account is wiped properly snap := snaps.Snapshot(root) @@ -1317,7 +1317,7 @@ func TestDeleteStorage(t *testing.T) { value := common.Hash(uint256.NewInt(uint64(10 * i)).Bytes32()) state.SetState(addr, slot, value) } - root, _ := state.CommitWithSnap(0, true, snaps, common.Hash{}, common.Hash{}, false) + root, _ := state.CommitWithSnap(0, true, snaps, common.Hash{}, common.Hash{}) // Init phase done, create two states, one with snap and one without fastState, _ := New(root, db, snaps) slowState, _ := New(root, db, nil) diff --git a/core/state/sync_test.go b/core/state/sync_test.go index 5b1c9e3866..17444dfe89 100644 --- a/core/state/sync_test.go +++ b/core/state/sync_test.go @@ -76,7 +76,7 @@ func makeTestState(scheme string) (ethdb.Database, Database, *triedb.Database, c } accounts = append(accounts, acc) } - root, _ := state.Commit(0, false, false) + root, _ := state.Commit(0, false) // Return the generated state return db, sdb, nodeDb, root, accounts diff --git a/core/test_blockchain.go b/core/test_blockchain.go index 41d5657b92..9c22ff0338 100644 --- a/core/test_blockchain.go +++ b/core/test_blockchain.go @@ -1502,7 +1502,7 @@ func checkTxIndicesHelper(t *testing.T, expectedTail *uint64, indexedFrom uint64 require.EventuallyWithTf(t, func(c *assert.CollectT) { stored = *rawdb.ReadTxIndexTail(db) - require.Equalf(t, tailValue, stored, "expected tail to be %d, found %d", tailValue, stored) + assert.Equalf(c, tailValue, stored, "expected tail to be %d, found %d", tailValue, stored) }, 30*time.Second, 500*time.Millisecond, "expected tail to be %d eventually", tailValue) } diff --git a/core/txpool/blobpool/blobpool_test.go b/core/txpool/blobpool/blobpool_test.go index 5290153bba..0e993ca9dc 100644 --- a/core/txpool/blobpool/blobpool_test.go +++ b/core/txpool/blobpool/blobpool_test.go @@ -584,7 +584,7 @@ func TestOpenDrops(t *testing.T) { statedb.AddBalance(crypto.PubkeyToAddress(overcapper.PublicKey), uint256.NewInt(10000000)) statedb.AddBalance(crypto.PubkeyToAddress(duplicater.PublicKey), uint256.NewInt(1000000)) statedb.AddBalance(crypto.PubkeyToAddress(repeater.PublicKey), uint256.NewInt(1000000)) - statedb.Commit(0, true, false) + statedb.Commit(0, true) chain := &testBlockChain{ config: testChainConfig, @@ -703,7 +703,7 @@ func TestOpenIndex(t *testing.T) { // Create a blob pool out of the pre-seeded data statedb, _ := state.New(types.EmptyRootHash, state.NewDatabase(rawdb.NewDatabase(memorydb.New())), nil) statedb.AddBalance(addr, uint256.NewInt(1_000_000_000)) - statedb.Commit(0, true, false) + statedb.Commit(0, true) chain := &testBlockChain{ config: testChainConfig, @@ -806,7 +806,7 @@ func TestOpenHeap(t *testing.T) { statedb.AddBalance(addr1, uint256.NewInt(1_000_000_000)) statedb.AddBalance(addr2, uint256.NewInt(1_000_000_000)) statedb.AddBalance(addr3, uint256.NewInt(1_000_000_000)) - statedb.Commit(0, true, false) + statedb.Commit(0, true) chain := &testBlockChain{ config: testChainConfig, @@ -887,7 +887,7 @@ func TestOpenCap(t *testing.T) { statedb.AddBalance(addr1, uint256.NewInt(1_000_000_000)) statedb.AddBalance(addr2, uint256.NewInt(1_000_000_000)) statedb.AddBalance(addr3, uint256.NewInt(1_000_000_000)) - statedb.Commit(0, true, false) + statedb.Commit(0, true) chain := &testBlockChain{ config: testChainConfig, @@ -1305,7 +1305,7 @@ func TestAdd(t *testing.T) { store.Put(blob) } } - statedb.Commit(0, true, false) + statedb.Commit(0, true) store.Close() // Create a blob pool out of the pre-seeded dats @@ -1378,7 +1378,7 @@ func benchmarkPoolPending(b *testing.B, datacap uint64) { statedb.AddBalance(addr, uint256.NewInt(1_000_000_000)) pool.add(tx) } - statedb.Commit(0, true, false) + statedb.Commit(0, true) defer pool.Close() // Benchmark assembling the pending diff --git a/eth/api_debug_test.go b/eth/api_debug_test.go index 5ff163664e..a0fa2eaa5a 100644 --- a/eth/api_debug_test.go +++ b/eth/api_debug_test.go @@ -93,7 +93,7 @@ func TestAccountRange(t *testing.T) { m[addr] = true } } - root, _ := sdb.Commit(0, true, false) + root, _ := sdb.Commit(0, true) sdb, _ = state.New(root, statedb, nil) trie, err := statedb.OpenTrie(root) @@ -151,7 +151,7 @@ func TestEmptyAccountRange(t *testing.T) { st, _ = state.New(types.EmptyRootHash, statedb, nil) ) // Commit(although nothing to flush) and re-init the statedb - st.Commit(0, true, false) + st.Commit(0, true) st, _ = state.New(types.EmptyRootHash, statedb, nil) results := st.RawDump(&state.DumpConfig{ @@ -197,7 +197,7 @@ func TestStorageRangeAt(t *testing.T) { for _, entry := range storage { sdb.SetState(addr, *entry.Key, entry.Value) } - root, _ := sdb.Commit(0, false, false) + root, _ := sdb.Commit(0, false) sdb, _ = state.New(root, db, nil) // Check a few combinations of limit and start/end. diff --git a/eth/state_accessor.go b/eth/state_accessor.go index 15b14b559a..d5f87ce2ef 100644 --- a/eth/state_accessor.go +++ b/eth/state_accessor.go @@ -163,7 +163,7 @@ func (eth *Ethereum) hashState(ctx context.Context, block *types.Block, reexec u return nil, nil, fmt.Errorf("processing block %d failed: %v", current.NumberU64(), err) } // Finalize the state so any modifications are written to the trie - root, err := statedb.Commit(current.NumberU64(), eth.blockchain.Config().IsEIP158(current.Number()), true) + root, err := statedb.Commit(current.NumberU64(), eth.blockchain.Config().IsEIP158(current.Number())) if err != nil { return nil, nil, fmt.Errorf("stateAtBlock commit failed, number %d root %v: %w", current.NumberU64(), current.Root().Hex(), err) @@ -172,8 +172,9 @@ func (eth *Ethereum) hashState(ctx context.Context, block *types.Block, reexec u if err != nil { return nil, nil, fmt.Errorf("state reset after block %d failed: %v", current.NumberU64(), err) } - // Note: In subnet-evm, the state reference is held by passing true to [statedb.Commit]. - // Drop the parent state to prevent accumulating too many nodes in memory. + // Hold the state reference and also drop the parent state + // to prevent accumulating too many nodes in memory. + tdb.Reference(root, common.Hash{}) if parent != (common.Hash{}) { tdb.Dereference(parent) } diff --git a/go.mod b/go.mod index 75608b44bb..8bb078c376 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.22.8 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.11.12-rc.3 + github.com/ava-labs/avalanchego v1.12.0-initial-poc.9 github.com/cespare/cp v0.1.0 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 @@ -33,16 +33,16 @@ require ( github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.12.0 github.com/status-im/keycard-go v0.2.0 - github.com/stretchr/testify v1.8.4 + github.com/stretchr/testify v1.9.0 github.com/tyler-smith/go-bip39 v1.1.0 github.com/urfave/cli/v2 v2.25.7 go.uber.org/goleak v1.3.0 go.uber.org/mock v0.4.0 - golang.org/x/crypto v0.22.0 + golang.org/x/crypto v0.26.0 golang.org/x/exp v0.0.0-20231127185646-65229373498e - golang.org/x/sync v0.7.0 - golang.org/x/sys v0.19.0 - golang.org/x/text v0.14.0 + golang.org/x/sync v0.8.0 + golang.org/x/sys v0.24.0 + golang.org/x/text v0.17.0 golang.org/x/time v0.3.0 google.golang.org/protobuf v1.34.2 gopkg.in/natefinch/lumberjack.v2 v2.0.0 @@ -55,7 +55,7 @@ require ( github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect github.com/btcsuite/btcd/btcutil v1.1.3 // indirect github.com/cenkalti/backoff/v4 v4.2.1 // indirect - github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cockroachdb/errors v1.9.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect github.com/cockroachdb/pebble v0.0.0-20230928194634-aa077af62593 // indirect @@ -99,12 +99,12 @@ require ( github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.10.1 // indirect github.com/rivo/uniseg v0.2.0 // indirect - github.com/rogpeppe/go-internal v1.10.0 // indirect + github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/spf13/afero v1.8.2 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/subosito/gotenv v1.3.0 // indirect - github.com/supranational/blst v0.3.11 // indirect + github.com/supranational/blst v0.3.13 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220614013038-64ee5596c38a // indirect github.com/tklauser/go-sysconf v0.3.12 // indirect github.com/tklauser/numcpus v0.6.1 // indirect @@ -120,12 +120,12 @@ require ( go.opentelemetry.io/proto/otlp v1.0.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.26.0 // indirect - golang.org/x/net v0.24.0 // indirect - golang.org/x/term v0.19.0 // indirect + golang.org/x/net v0.28.0 // indirect + golang.org/x/term v0.23.0 // indirect gonum.org/v1/gonum v0.11.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20240123012728-ef4313101c80 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20240123012728-ef4313101c80 // indirect - google.golang.org/grpc v1.62.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20240604185151-ef581f913117 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240827150818-7e3bb234dfed // indirect + google.golang.org/grpc v1.66.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index e0b4fed0f8..644f445ac7 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,8 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/avalanchego v1.11.12-rc.3 h1:cfJ9HCCunCZn922uIfnsw1UKt/c4pOl2/6w/Y7Fwn9Q= -github.com/ava-labs/avalanchego v1.11.12-rc.3/go.mod h1:qSHmog3wMVjo/ruIAQo0ppXAilyni07NIu5K88RyhWE= +github.com/ava-labs/avalanchego v1.12.0-initial-poc.9 h1:dQhb+KlPoud+AkRV3A0suKCTodlUSzflGcZElESeVKo= +github.com/ava-labs/avalanchego v1.12.0-initial-poc.9/go.mod h1:86tO6F1FT8emclUwdQ2WCwAtAerqjm5A4IbV6XxNUyM= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= @@ -90,8 +90,9 @@ github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyY github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/cp v0.1.0 h1:SE+dxFebS7Iik5LK0tsi1k9ZCxEaFX4AjQmoyA+1dJk= github.com/cespare/cp v0.1.0/go.mod h1:SOGHArjBr4JWaSDEVpWpo/hNg6RoKrls6Oh40hiwW+s= -github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/logex v1.2.0/go.mod h1:9+9sk7u7pGNWYMkh0hdiL++6OeibzJccyQU4p4MedaY= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= @@ -219,8 +220,8 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69 github.com/gogo/status v1.1.0/go.mod h1:BFv9nrluPLmrS0EmGVvLaPNmRosr9KapBYd5/hpY1WM= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.2.0 h1:uCdmnmatrKCgMBlM4rMuJZWOkPDqdbZPnrMXDY4gI68= -github.com/golang/glog v1.2.0/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= +github.com/golang/glog v1.2.1 h1:OptwRhECazUx5ix5TTWC3EZhsZEHWcYWY4FQHTIubm4= +github.com/golang/glog v1.2.1/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -467,8 +468,8 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= -github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -510,12 +511,12 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/subosito/gotenv v1.3.0 h1:mjC+YW8QpAdXibNi+vNWgzmgBH4+5l5dCXv8cNysBLI= github.com/subosito/gotenv v1.3.0/go.mod h1:YzJjq/33h7nrwdY+iHMhEOEEbW0ovIz0tB6t6PwAXzs= -github.com/supranational/blst v0.3.11 h1:LyU6FolezeWAhvQk0k6O/d49jqgO52MSDDfYgbeoEm4= -github.com/supranational/blst v0.3.11/go.mod h1:jZJtfjgudtNl4en1tzwPIV3KjUnQUvG3/j+w+fVonLw= +github.com/supranational/blst v0.3.13 h1:AYeSxdOMacwu7FBmpfloBz5pbFXDmJL33RuwnKtmTjk= +github.com/supranational/blst v0.3.13/go.mod h1:jZJtfjgudtNl4en1tzwPIV3KjUnQUvG3/j+w+fVonLw= github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= github.com/syndtr/goleveldb v1.0.1-0.20220614013038-64ee5596c38a h1:1ur3QoCqvE5fl+nylMaIr9PVV1w343YRDtsy+Rwu7XI= github.com/syndtr/goleveldb v1.0.1-0.20220614013038-64ee5596c38a/go.mod h1:RRCYJbIwD5jmqPI9XoAFR0OcDxqUctll6zUj/+B4S48= @@ -600,8 +601,8 @@ golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= -golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= +golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw= +golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -684,8 +685,8 @@ golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= -golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= +golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE= +golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -707,8 +708,8 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= -golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -775,12 +776,12 @@ golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= -golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= +golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.19.0 h1:+ThwsDv+tYfnJFhF4L8jITxu1tdTWRTZpdsWgEgjL6Q= -golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk= +golang.org/x/term v0.23.0 h1:F6D4vR+EHoL9/sWAWgAR1H2DcHr4PareCbAaCo1RpuU= +golang.org/x/term v0.23.0/go.mod h1:DgV24QBUrK6jhZXl+20l6UWznPlwAHm1Q1mGHtydmSk= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -791,8 +792,8 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= -golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= +golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -925,12 +926,10 @@ google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= -google.golang.org/genproto v0.0.0-20240123012728-ef4313101c80 h1:KAeGQVN3M9nD0/bQXnr/ClcEMJ968gUXJQ9pwfSynuQ= -google.golang.org/genproto v0.0.0-20240123012728-ef4313101c80/go.mod h1:cc8bqMqtv9gMOr0zHg2Vzff5ULhhL2IXP4sbcn32Dro= -google.golang.org/genproto/googleapis/api v0.0.0-20240123012728-ef4313101c80 h1:Lj5rbfG876hIAYFjqiJnPHfhXbv+nzTWfm04Fg/XSVU= -google.golang.org/genproto/googleapis/api v0.0.0-20240123012728-ef4313101c80/go.mod h1:4jWUdICTdgc3Ibxmr8nAJiiLHwQBY0UI0XZcEMaFKaA= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240123012728-ef4313101c80 h1:AjyfHzEPEFp/NpvfN5g+KDla3EMojjhRVZc1i7cj+oM= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240123012728-ef4313101c80/go.mod h1:PAREbraiVEVGVdTZsVWjSbbTtSyGbAgIIvni8a8CD5s= +google.golang.org/genproto/googleapis/api v0.0.0-20240604185151-ef581f913117 h1:+rdxYoE3E5htTEWIe15GlN6IfvbURM//Jt0mmkmm6ZU= +google.golang.org/genproto/googleapis/api v0.0.0-20240604185151-ef581f913117/go.mod h1:OimBR/bc1wPO9iV4NC2bpyjy3VnAwZh5EBPQdtaE5oo= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240827150818-7e3bb234dfed h1:J6izYgfBXAI3xTKLgxzTmUltdYaLsuBxFCgDHWJ/eXg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240827150818-7e3bb234dfed/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= @@ -949,8 +948,8 @@ google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/grpc v1.62.0 h1:HQKZ/fa1bXkX1oFOvSjmZEUL8wLSaZTjCcLAlmZRtdk= -google.golang.org/grpc v1.62.0/go.mod h1:IWTG0VlJLCh1SkC58F7np9ka9mx/WNkjl4PGJaiq+QE= +google.golang.org/grpc v1.66.0 h1:DibZuoBznOxbDQxRINckZcUvnCEvrW9pcWIE2yF9r1c= +google.golang.org/grpc v1.66.0/go.mod h1:s3/l6xSSCURdVfAnL+TqCNMyTDAGN6+lZeVxnZR128Y= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= diff --git a/plugin/evm/block.go b/plugin/evm/block.go index 4b6ac6824a..a8d9084464 100644 --- a/plugin/evm/block.go +++ b/plugin/evm/block.go @@ -148,12 +148,9 @@ func (b *Block) Accept(context.Context) error { // Call Accept for relevant precompile logs. Note we do this prior to // calling Accept on the blockChain so any side effects (eg warp signatures) - // take place before the accepted log is emitted to subscribers. Use of the - // sharedMemoryWriter ensures shared memory requests generated by - // precompiles are committed atomically with the vm's lastAcceptedKey. + // take place before the accepted log is emitted to subscribers. rules := b.vm.chainConfig.Rules(b.ethBlock.Number(), b.ethBlock.Timestamp()) - sharedMemoryWriter := NewSharedMemoryWriter() - if err := b.handlePrecompileAccept(rules, sharedMemoryWriter); err != nil { + if err := b.handlePrecompileAccept(rules); err != nil { return err } if err := vm.blockChain.Accept(b.ethBlock); err != nil { @@ -177,23 +174,20 @@ func (b *Block) Accept(context.Context) error { return err } // Get pending operations on the vm's versionDB so we can apply them atomically - // with the shared memory requests. + // with the shared memory changes. vdbBatch, err := b.vm.db.CommitBatch() if err != nil { return fmt.Errorf("could not create commit batch processing block[%s]: %w", b.ID(), err) } - // Apply any shared memory requests that accumulated from processing the logs - // of the accepted block (generated by precompiles) atomically with other pending - // changes to the vm's versionDB. - return atomicState.Accept(vdbBatch, sharedMemoryWriter.requests) + // Apply any shared memory changes atomically with other pending changes to + // the vm's versionDB. + return atomicState.Accept(vdbBatch, nil) } // handlePrecompileAccept calls Accept on any logs generated with an active precompile address that implements // contract.Accepter -// This function assumes that the Accept function will ONLY operate on state maintained in the VM's versiondb. -// This ensures that any DB operations are performed atomically with marking the block as accepted. -func (b *Block) handlePrecompileAccept(rules params.Rules, sharedMemoryWriter *sharedMemoryWriter) error { +func (b *Block) handlePrecompileAccept(rules params.Rules) error { // Short circuit early if there are no precompile accepters to execute if len(rules.AccepterPrecompiles) == 0 { return nil @@ -207,9 +201,8 @@ func (b *Block) handlePrecompileAccept(rules params.Rules, sharedMemoryWriter *s return fmt.Errorf("failed to fetch receipts for accepted block with non-empty root hash (%s) (Block: %s, Height: %d)", b.ethBlock.ReceiptHash(), b.ethBlock.Hash(), b.ethBlock.NumberU64()) } acceptCtx := &precompileconfig.AcceptContext{ - SnowCtx: b.vm.ctx, - SharedMemory: sharedMemoryWriter, - Warp: b.vm.warpBackend, + SnowCtx: b.vm.ctx, + Warp: b.vm.warpBackend, } for _, receipt := range receipts { for logIdx, log := range receipt.Logs { @@ -334,7 +327,7 @@ func (b *Block) verify(predicateContext *precompileconfig.PredicateContext, writ // If the chain is still bootstrapping, we can assume that all blocks we are verifying have // been accepted by the network (so the predicate was validated by the network when the // block was originally verified). - if b.vm.bootstrapped { + if b.vm.bootstrapped.Get() { if err := b.verifyPredicates(predicateContext); err != nil { return fmt.Errorf("failed to verify predicates: %w", err) } @@ -405,7 +398,7 @@ func (b *Block) verifyUTXOsPresent() error { return nil } - if !b.vm.bootstrapped { + if !b.vm.bootstrapped.Get() { return nil } diff --git a/plugin/evm/gossip_test.go b/plugin/evm/gossip_test.go index 2db67a6f4b..8ed7aee3cf 100644 --- a/plugin/evm/gossip_test.go +++ b/plugin/evm/gossip_test.go @@ -189,7 +189,7 @@ func TestGossipSubscribe(t *testing.T) { defer gossipTxPool.lock.RUnlock() for i, tx := range ethTxs { - require.Truef(gossipTxPool.bloom.Has(&GossipEthTx{Tx: tx}), "expected tx[%d] to be in bloom filter", i) + assert.Truef(c, gossipTxPool.bloom.Has(&GossipEthTx{Tx: tx}), "expected tx[%d] to be in bloom filter", i) } }, 30*time.Second, diff --git a/plugin/evm/import_tx.go b/plugin/evm/import_tx.go index b67b834673..b447a717ee 100644 --- a/plugin/evm/import_tx.go +++ b/plugin/evm/import_tx.go @@ -221,7 +221,7 @@ func (utx *UnsignedImportTx) SemanticVerify( return fmt.Errorf("import tx contained mismatched number of inputs/credentials (%d vs. %d)", len(utx.ImportedInputs), len(stx.Creds)) } - if !vm.bootstrapped { + if !vm.bootstrapped.Get() { // Allow for force committing during bootstrapping return nil } diff --git a/plugin/evm/shared_memory_writer.go b/plugin/evm/shared_memory_writer.go deleted file mode 100644 index 7e6de6f862..0000000000 --- a/plugin/evm/shared_memory_writer.go +++ /dev/null @@ -1,37 +0,0 @@ -// (c) 2023, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package evm - -import ( - "github.com/ava-labs/avalanchego/chains/atomic" - "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/coreth/precompile/precompileconfig" -) - -var _ precompileconfig.SharedMemoryWriter = &sharedMemoryWriter{} - -type sharedMemoryWriter struct { - requests map[ids.ID]*atomic.Requests -} - -func NewSharedMemoryWriter() *sharedMemoryWriter { - return &sharedMemoryWriter{ - requests: make(map[ids.ID]*atomic.Requests), - } -} - -func (s *sharedMemoryWriter) AddSharedMemoryRequests(chainID ids.ID, requests *atomic.Requests) { - mergeAtomicOpsToMap(s.requests, chainID, requests) -} - -// mergeAtomicOps merges atomic ops for [chainID] represented by [requests] -// to the [output] map provided. -func mergeAtomicOpsToMap(output map[ids.ID]*atomic.Requests, chainID ids.ID, requests *atomic.Requests) { - if request, exists := output[chainID]; exists { - request.PutRequests = append(request.PutRequests, requests.PutRequests...) - request.RemoveRequests = append(request.RemoveRequests, requests.RemoveRequests...) - } else { - output[chainID] = requests - } -} diff --git a/plugin/evm/syncervm_test.go b/plugin/evm/syncervm_test.go index 3ecfcb517c..bba4663153 100644 --- a/plugin/evm/syncervm_test.go +++ b/plugin/evm/syncervm_test.go @@ -554,7 +554,7 @@ func testSyncerVM(t *testing.T, vmSetup *syncVMSetup, test syncTest) { // check we can transition to [NormalOp] state and continue to process blocks. require.NoError(syncerVM.SetState(context.Background(), snow.NormalOp)) - require.True(syncerVM.bootstrapped) + require.True(syncerVM.bootstrapped.Get()) // check atomic memory was synced properly syncerSharedMemories := newSharedMemories(syncerAtomicMemory, syncerVM.ctx.ChainID, syncerVM.ctx.XChainID) diff --git a/plugin/evm/tx.go b/plugin/evm/tx.go index 00f7de4bce..9361f71976 100644 --- a/plugin/evm/tx.go +++ b/plugin/evm/tx.go @@ -288,3 +288,14 @@ func mergeAtomicOps(txs []*Tx) (map[ids.ID]*atomic.Requests, error) { } return output, nil } + +// mergeAtomicOps merges atomic ops for [chainID] represented by [requests] +// to the [output] map provided. +func mergeAtomicOpsToMap(output map[ids.ID]*atomic.Requests, chainID ids.ID, requests *atomic.Requests) { + if request, exists := output[chainID]; exists { + request.PutRequests = append(request.PutRequests, requests.PutRequests...) + request.RemoveRequests = append(request.RemoveRequests, requests.RemoveRequests...) + } else { + output[chainID] = requests + } +} diff --git a/plugin/evm/tx_gossip_test.go b/plugin/evm/tx_gossip_test.go index 6024747180..af544e9415 100644 --- a/plugin/evm/tx_gossip_test.go +++ b/plugin/evm/tx_gossip_test.go @@ -21,7 +21,6 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/validators" - "github.com/ava-labs/avalanchego/snow/validators/validatorstest" agoUtils "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/logging" @@ -43,7 +42,7 @@ func TestEthTxGossip(t *testing.T) { require := require.New(t) ctx := context.Background() snowCtx := utils.TestSnowContext() - validatorState := &validatorstest.State{} + validatorState := utils.NewTestValidatorState() snowCtx.ValidatorState = validatorState pk, err := secp256k1.NewPrivateKey() @@ -169,15 +168,10 @@ func TestAtomicTxGossip(t *testing.T) { ctx := context.Background() snowCtx := utils.TestSnowContext() snowCtx.AVAXAssetID = ids.GenerateTestID() - snowCtx.XChainID = ids.GenerateTestID() - validatorState := &validatorstest.State{ - GetSubnetIDF: func(context.Context, ids.ID) (ids.ID, error) { - return ids.Empty, nil - }, - } + validatorState := utils.NewTestValidatorState() snowCtx.ValidatorState = validatorState memory := atomic.NewMemory(memdb.New()) - snowCtx.SharedMemory = memory.NewSharedMemory(ids.Empty) + snowCtx.SharedMemory = memory.NewSharedMemory(snowCtx.ChainID) pk, err := secp256k1.NewPrivateKey() require.NoError(err) @@ -308,14 +302,6 @@ func TestEthTxPushGossipOutbound(t *testing.T) { require := require.New(t) ctx := context.Background() snowCtx := utils.TestSnowContext() - snowCtx.ValidatorState = &validatorstest.State{ - GetCurrentHeightF: func(context.Context) (uint64, error) { - return 0, nil - }, - GetValidatorSetF: func(context.Context, uint64, ids.ID) (map[ids.NodeID]*validators.GetValidatorOutput, error) { - return nil, nil - }, - } sender := &enginetest.SenderStub{ SentAppGossip: make(chan []byte, 1), } @@ -440,15 +426,10 @@ func TestAtomicTxPushGossipOutbound(t *testing.T) { ctx := context.Background() snowCtx := utils.TestSnowContext() snowCtx.AVAXAssetID = ids.GenerateTestID() - snowCtx.XChainID = ids.GenerateTestID() - validatorState := &validatorstest.State{ - GetSubnetIDF: func(context.Context, ids.ID) (ids.ID, error) { - return ids.Empty, nil - }, - } + validatorState := utils.NewTestValidatorState() snowCtx.ValidatorState = validatorState memory := atomic.NewMemory(memdb.New()) - snowCtx.SharedMemory = memory.NewSharedMemory(ids.Empty) + snowCtx.SharedMemory = memory.NewSharedMemory(snowCtx.ChainID) pk, err := secp256k1.NewPrivateKey() require.NoError(err) @@ -518,15 +499,10 @@ func TestAtomicTxPushGossipInbound(t *testing.T) { ctx := context.Background() snowCtx := utils.TestSnowContext() snowCtx.AVAXAssetID = ids.GenerateTestID() - snowCtx.XChainID = ids.GenerateTestID() - validatorState := &validatorstest.State{ - GetSubnetIDF: func(context.Context, ids.ID) (ids.ID, error) { - return ids.Empty, nil - }, - } + validatorState := utils.NewTestValidatorState() snowCtx.ValidatorState = validatorState memory := atomic.NewMemory(memdb.New()) - snowCtx.SharedMemory = memory.NewSharedMemory(ids.Empty) + snowCtx.SharedMemory = memory.NewSharedMemory(snowCtx.ChainID) pk, err := secp256k1.NewPrivateKey() require.NoError(err) diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index e113252e05..50606b0af7 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -17,7 +17,9 @@ import ( "sync" "time" + "github.com/ava-labs/avalanchego/cache/metercacher" "github.com/ava-labs/avalanchego/network/p2p" + "github.com/ava-labs/avalanchego/network/p2p/acp118" "github.com/ava-labs/avalanchego/network/p2p/gossip" "github.com/ava-labs/avalanchego/upgrade" avalanchegoConstants "github.com/ava-labs/avalanchego/utils/constants" @@ -49,7 +51,6 @@ import ( statesyncclient "github.com/ava-labs/coreth/sync/client" "github.com/ava-labs/coreth/sync/client/stats" "github.com/ava-labs/coreth/warp" - "github.com/ava-labs/coreth/warp/handlers" // Force-load tracer engine to trigger registration // @@ -316,7 +317,7 @@ type VM struct { // Metrics sdkMetrics *prometheus.Registry - bootstrapped bool + bootstrapped avalancheUtils.Atomic[bool] IsPlugin bool logger CorethLogger @@ -336,6 +337,10 @@ type VM struct { atomicTxGossipHandler p2p.Handler atomicTxPushGossiper *gossip.PushGossiper[*GossipAtomicTx] atomicTxPullGossiper gossip.Gossiper + + chainAlias string + // RPC handlers (should be stopped before closing chaindb) + rpcHandlers []interface{ Stop() } } // CodecRegistry implements the secp256k1fx interface @@ -392,13 +397,14 @@ func (vm *VM) Initialize( // fallback to ChainID string instead of erroring alias = vm.ctx.ChainID.String() } + vm.chainAlias = alias var writer io.Writer = vm.ctx.Log if vm.IsPlugin { writer = originalStderr } - corethLogger, err := InitLogger(alias, vm.config.LogLevel, vm.config.LogJSONFormat, writer) + corethLogger, err := InitLogger(vm.chainAlias, vm.config.LogLevel, vm.config.LogJSONFormat, writer) if err != nil { return fmt.Errorf("failed to initialize logger due to: %w ", err) } @@ -419,16 +425,15 @@ func (vm *VM) Initialize( vm.toEngine = toEngine vm.shutdownChan = make(chan struct{}, 1) - // Use NewNested rather than New so that the structure of the database - // remains the same regardless of the provided baseDB type. - vm.chaindb = rawdb.NewDatabase(Database{prefixdb.NewNested(ethDBPrefix, db)}) - vm.db = versiondb.New(db) - vm.acceptedBlockDB = prefixdb.New(acceptedPrefix, vm.db) - vm.metadataDB = prefixdb.New(metadataPrefix, vm.db) - // Note warpDB is not part of versiondb because it is not necessary - // that warp signatures are committed to the database atomically with - // the last accepted block. - vm.warpDB = prefixdb.New(warpPrefix, db) + + if err := vm.initializeMetrics(); err != nil { + return fmt.Errorf("failed to initialize metrics: %w", err) + } + + // Initialize the database + if err := vm.initializeDBs(db); err != nil { + return fmt.Errorf("failed to initialize databases: %w", err) + } if vm.config.InspectDatabase { start := time.Now() @@ -571,10 +576,6 @@ func (vm *VM) Initialize( vm.codec = Codec - if err := vm.initializeMetrics(); err != nil { - return err - } - // TODO: read size from settings vm.mempool, err = NewMempool(chainCtx, vm.sdkMetrics, defaultMempoolSize, vm.verifyTxAtTip) if err != nil { @@ -600,26 +601,31 @@ func (vm *VM) Initialize( for i, hexMsg := range vm.config.WarpOffChainMessages { offchainWarpMessages[i] = []byte(hexMsg) } + warpSignatureCache := &cache.LRU[ids.ID, []byte]{Size: warpSignatureCacheSize} + meteredCache, err := metercacher.New("warp_signature_cache", vm.sdkMetrics, warpSignatureCache) + if err != nil { + return fmt.Errorf("failed to create warp signature cache: %w", err) + } + + // clear warpdb on initialization if config enabled + if vm.config.PruneWarpDB { + if err := database.Clear(vm.warpDB, ethdb.IdealBatchSize); err != nil { + return fmt.Errorf("failed to prune warpDB: %w", err) + } + } + vm.warpBackend, err = warp.NewBackend( vm.ctx.NetworkID, vm.ctx.ChainID, vm.ctx.WarpSigner, vm, vm.warpDB, - warpSignatureCacheSize, + meteredCache, offchainWarpMessages, ) if err != nil { return err } - - // clear warpdb on initialization if config enabled - if vm.config.PruneWarpDB { - if err := vm.warpBackend.Clear(); err != nil { - return fmt.Errorf("failed to prune warpDB: %w", err) - } - } - if err := vm.initializeChain(lastAcceptedHash); err != nil { return err } @@ -660,7 +666,17 @@ func (vm *VM) Initialize( return err } - vm.initializeHandlers() + // Add p2p warp message warpHandler + warpHandler := acp118.NewCachedHandler(meteredCache, vm.warpBackend, vm.ctx.WarpSigner) + vm.Network.AddHandler(p2p.SignatureRequestHandlerID, warpHandler) + + vm.setAppRequestHandlers() + + vm.StateSyncServer = NewStateSyncServer(&stateSyncServerConfig{ + Chain: vm.blockChain, + AtomicTrie: vm.atomicTrie, + SyncableInterval: vm.config.StateSyncCommitInterval, + }) return vm.initializeStateSyncClient(lastAcceptedHeight) } @@ -799,21 +815,6 @@ func (vm *VM) initializeStateSyncClient(lastAcceptedHeight uint64) error { return nil } -// initializeHandlers should be called after [vm.chain] is initialized. -func (vm *VM) initializeHandlers() { - vm.StateSyncServer = NewStateSyncServer(&stateSyncServerConfig{ - Chain: vm.blockChain, - AtomicTrie: vm.atomicTrie, - SyncableInterval: vm.config.StateSyncCommitInterval, - }) - - // Add p2p warp message warpHandler - warpHandler := handlers.NewSignatureRequestHandlerP2P(vm.warpBackend, vm.networkCodec) - vm.Network.AddHandler(p2p.SignatureRequestHandlerID, warpHandler) - - vm.setAppRequestHandlers() -} - func (vm *VM) initChainState(lastAcceptedBlock *types.Block) error { block, err := vm.newBlock(lastAcceptedBlock) if err != nil { @@ -1076,33 +1077,48 @@ func (vm *VM) onExtraStateChange(block *types.Block, state *state.StateDB) (*big func (vm *VM) SetState(_ context.Context, state snow.State) error { switch state { case snow.StateSyncing: - vm.bootstrapped = false + vm.bootstrapped.Set(false) return nil case snow.Bootstrapping: - vm.bootstrapped = false - if err := vm.StateSyncClient.Error(); err != nil { - return err - } - // After starting bootstrapping, do not attempt to resume a previous state sync. - if err := vm.StateSyncClient.ClearOngoingSummary(); err != nil { - return err - } - // Ensure snapshots are initialized before bootstrapping (i.e., if state sync is skipped). - // Note calling this function has no effect if snapshots are already initialized. - vm.blockChain.InitializeSnapshots() - return vm.fx.Bootstrapping() + return vm.onBootstrapStarted() case snow.NormalOp: - // Initialize goroutines related to block building once we enter normal operation as there is no need to handle mempool gossip before this point. - if err := vm.initBlockBuilding(); err != nil { - return fmt.Errorf("failed to initialize block building: %w", err) - } - vm.bootstrapped = true - return vm.fx.Bootstrapped() + return vm.onNormalOperationsStarted() default: return snow.ErrUnknownState } } +// onBootstrapStarted marks this VM as bootstrapping +func (vm *VM) onBootstrapStarted() error { + vm.bootstrapped.Set(false) + if err := vm.StateSyncClient.Error(); err != nil { + return err + } + // After starting bootstrapping, do not attempt to resume a previous state sync. + if err := vm.StateSyncClient.ClearOngoingSummary(); err != nil { + return err + } + // Ensure snapshots are initialized before bootstrapping (i.e., if state sync is skipped). + // Note calling this function has no effect if snapshots are already initialized. + vm.blockChain.InitializeSnapshots() + + return vm.fx.Bootstrapping() +} + +// onNormalOperationsStarted marks this VM as bootstrapped +func (vm *VM) onNormalOperationsStarted() error { + if vm.bootstrapped.Get() { + return nil + } + vm.bootstrapped.Set(true) + if err := vm.fx.Bootstrapped(); err != nil { + return err + } + // Initialize goroutines related to block building + // once we enter normal operation as there is no need to handle mempool gossip before this point. + return vm.initBlockBuilding() +} + // initBlockBuilding starts goroutines to manage block building func (vm *VM) initBlockBuilding() error { ctx, cancel := context.WithCancel(context.TODO()) @@ -1116,7 +1132,7 @@ func (vm *VM) initBlockBuilding() error { } ethTxPool, err := NewGossipEthTxPool(vm.txPool, vm.sdkMetrics) if err != nil { - return err + return fmt.Errorf("failed to initialize gossip eth tx pool: %w", err) } vm.shutdownWg.Add(1) go func() { @@ -1199,7 +1215,7 @@ func (vm *VM) initBlockBuilding() error { } if err := vm.Network.AddHandler(p2p.TxGossipHandlerID, vm.ethTxGossipHandler); err != nil { - return err + return fmt.Errorf("failed to add eth tx gossip handler: %w", err) } if vm.atomicTxGossipHandler == nil { @@ -1216,7 +1232,7 @@ func (vm *VM) initBlockBuilding() error { } if err := vm.Network.AddHandler(p2p.AtomicTxGossipHandlerID, vm.atomicTxGossipHandler); err != nil { - return err + return fmt.Errorf("failed to add atomic tx gossip handler: %w", err) } if vm.ethTxPullGossiper == nil { @@ -1279,8 +1295,8 @@ func (vm *VM) initBlockBuilding() error { // setAppRequestHandlers sets the request handlers for the VM to serve state sync // requests. func (vm *VM) setAppRequestHandlers() { - // Create separate EVM TrieDB (read only) for serving leafs requests. - // We create a separate TrieDB here, so that it has a separate cache from the one + // Create standalone EVM TrieDB (read only) for serving leafs requests. + // We create a standalone TrieDB here, so that it has a standalone cache from the one // used by the node when processing blocks. evmTrieDB := triedb.NewDatabase( vm.chaindb, @@ -1314,6 +1330,10 @@ func (vm *VM) Shutdown(context.Context) error { log.Error("error stopping state syncer", "err", err) } close(vm.shutdownChan) + // Stop RPC handlers before eth.Stop which will close the database + for _, handler := range vm.rpcHandlers { + handler.Stop() + } vm.eth.Stop() vm.shutdownWg.Wait() return nil @@ -1500,10 +1520,6 @@ func (vm *VM) CreateHandlers(context.Context) (map[string]http.Handler, error) { return nil, err } - primaryAlias, err := vm.ctx.BCLookup.PrimaryAlias(vm.ctx.ChainID) - if err != nil { - return nil, fmt.Errorf("failed to get primary alias for chain due to %w", err) - } apis := make(map[string]http.Handler) avaxAPI, err := newHandler("avax", &AvaxAPI{vm}) if err != nil { @@ -1513,7 +1529,7 @@ func (vm *VM) CreateHandlers(context.Context) (map[string]http.Handler, error) { apis[avaxEndpoint] = avaxAPI if vm.config.AdminAPIEnabled { - adminAPI, err := newHandler("admin", NewAdminService(vm, os.ExpandEnv(fmt.Sprintf("%s_coreth_performance_%s", vm.config.AdminAPIDir, primaryAlias)))) + adminAPI, err := newHandler("admin", NewAdminService(vm, os.ExpandEnv(fmt.Sprintf("%s_coreth_performance_%s", vm.config.AdminAPIDir, vm.chainAlias)))) if err != nil { return nil, fmt.Errorf("failed to register service for admin API due to %w", err) } @@ -1544,9 +1560,26 @@ func (vm *VM) CreateHandlers(context.Context) (map[string]http.Handler, error) { vm.config.WSCPUMaxStored.Duration, ) + vm.rpcHandlers = append(vm.rpcHandlers, handler) return apis, nil } +// initializeDBs initializes the databases used by the VM. +// coreth always uses the avalanchego provided database. +func (vm *VM) initializeDBs(db database.Database) error { + // Use NewNested rather than New so that the structure of the database + // remains the same regardless of the provided baseDB type. + vm.chaindb = rawdb.NewDatabase(Database{prefixdb.NewNested(ethDBPrefix, db)}) + vm.db = versiondb.New(db) + vm.acceptedBlockDB = prefixdb.New(acceptedPrefix, vm.db) + vm.metadataDB = prefixdb.New(metadataPrefix, vm.db) + // Note warpDB is not part of versiondb because it is not necessary + // that warp signatures are committed to the database atomically with + // the last accepted block. + vm.warpDB = prefixdb.New(warpPrefix, db) + return nil +} + // CreateStaticHandlers makes new http handlers that can handle API calls func (vm *VM) CreateStaticHandlers(context.Context) (map[string]http.Handler, error) { handler := rpc.NewServer(0) @@ -1557,6 +1590,7 @@ func (vm *VM) CreateStaticHandlers(context.Context) (map[string]http.Handler, er return nil, err } + vm.rpcHandlers = append(vm.rpcHandlers, handler) return map[string]http.Handler{ "/rpc": handler, }, nil diff --git a/plugin/evm/vm_warp_test.go b/plugin/evm/vm_warp_test.go index ec333e4132..7893588ac2 100644 --- a/plugin/evm/vm_warp_test.go +++ b/plugin/evm/vm_warp_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" commonEng "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/snow/validators/validatorstest" @@ -31,9 +32,10 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/precompile/contract" - "github.com/ava-labs/coreth/precompile/contracts/warp" + warpcontract "github.com/ava-labs/coreth/precompile/contracts/warp" "github.com/ava-labs/coreth/predicate" "github.com/ava-labs/coreth/utils" + "github.com/ava-labs/coreth/warp" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" @@ -74,7 +76,7 @@ func TestSendWarpMessage(t *testing.T) { payloadData := avagoUtils.RandomBytes(100) - warpSendMessageInput, err := warp.PackSendWarpMessage(payloadData) + warpSendMessageInput, err := warpcontract.PackSendWarpMessage(payloadData) require.NoError(err) addressedPayload, err := payload.NewAddressedCall( testEthAddrs[0].Bytes(), @@ -89,7 +91,7 @@ func TestSendWarpMessage(t *testing.T) { require.NoError(err) // Submit a transaction to trigger sending a warp message - tx0 := types.NewTransaction(uint64(0), warp.ContractAddress, big.NewInt(1), 100_000, big.NewInt(params.LaunchMinGasPrice), warpSendMessageInput) + tx0 := types.NewTransaction(uint64(0), warpcontract.ContractAddress, big.NewInt(1), 100_000, big.NewInt(params.LaunchMinGasPrice), warpSendMessageInput) signedTx0, err := types.SignTx(tx0, types.LatestSignerForChainID(vm.chainConfig.ChainID), testKeys[0].ToECDSA()) require.NoError(err) @@ -110,20 +112,19 @@ func TestSendWarpMessage(t *testing.T) { require.Len(receipts[0].Logs, 1) expectedTopics := []common.Hash{ - warp.WarpABI.Events["SendWarpMessage"].ID, + warpcontract.WarpABI.Events["SendWarpMessage"].ID, common.BytesToHash(testEthAddrs[0].Bytes()), common.Hash(expectedUnsignedMessage.ID()), } require.Equal(expectedTopics, receipts[0].Logs[0].Topics) logData := receipts[0].Logs[0].Data - unsignedMessage, err := warp.UnpackSendWarpEventDataToMessage(logData) + unsignedMessage, err := warpcontract.UnpackSendWarpEventDataToMessage(logData) require.NoError(err) - unsignedMessageID := unsignedMessage.ID() // Verify the signature cannot be fetched before the block is accepted - _, err = vm.warpBackend.GetMessageSignature(unsignedMessageID) + _, err = vm.warpBackend.GetMessageSignature(context.TODO(), unsignedMessage) require.Error(err) - _, err = vm.warpBackend.GetBlockSignature(blk.ID()) + _, err = vm.warpBackend.GetBlockSignature(context.TODO(), blk.ID()) require.Error(err) require.NoError(vm.SetPreference(context.Background(), blk.ID())) @@ -131,7 +132,7 @@ func TestSendWarpMessage(t *testing.T) { vm.blockChain.DrainAcceptorQueue() // Verify the message signature after accepting the block. - rawSignatureBytes, err := vm.warpBackend.GetMessageSignature(unsignedMessageID) + rawSignatureBytes, err := vm.warpBackend.GetMessageSignature(context.TODO(), unsignedMessage) require.NoError(err) blsSignature, err := bls.SignatureFromBytes(rawSignatureBytes[:]) require.NoError(err) @@ -148,7 +149,7 @@ func TestSendWarpMessage(t *testing.T) { require.True(bls.Verify(vm.ctx.PublicKey, blsSignature, unsignedMessage.Bytes())) // Verify the blockID will now be signed by the backend and produces a valid signature. - rawSignatureBytes, err = vm.warpBackend.GetBlockSignature(blk.ID()) + rawSignatureBytes, err = vm.warpBackend.GetBlockSignature(context.TODO(), blk.ID()) require.NoError(err) blsSignature, err = bls.SignatureFromBytes(rawSignatureBytes[:]) require.NoError(err) @@ -341,7 +342,7 @@ func testWarpVMTransaction(t *testing.T, unsignedMessage *avalancheWarp.Unsigned common.Big0, txPayload, types.AccessList{}, - warp.ContractAddress, + warpcontract.ContractAddress, signedMessage.Bytes(), ), types.LatestSignerForChainID(vm.chainConfig.ChainID), @@ -410,15 +411,15 @@ func TestReceiveWarpMessage(t *testing.T) { // enable warp at the default genesis time enableTime := upgrade.InitiallyActiveTime - enableConfig := warp.NewDefaultConfig(utils.TimeToNewUint64(enableTime)) + enableConfig := warpcontract.NewDefaultConfig(utils.TimeToNewUint64(enableTime)) // disable warp so we can re-enable it with RequirePrimaryNetworkSigners disableTime := upgrade.InitiallyActiveTime.Add(10 * time.Second) - disableConfig := warp.NewDisableConfig(utils.TimeToNewUint64(disableTime)) + disableConfig := warpcontract.NewDisableConfig(utils.TimeToNewUint64(disableTime)) // re-enable warp with RequirePrimaryNetworkSigners reEnableTime := disableTime.Add(10 * time.Second) - reEnableConfig := warp.NewConfig( + reEnableConfig := warpcontract.NewConfig( utils.TimeToNewUint64(reEnableTime), 0, // QuorumNumerator true, // RequirePrimaryNetworkSigners @@ -458,7 +459,7 @@ func TestReceiveWarpMessage(t *testing.T) { }, { name: "C-Chain message should be signed by subnet without RequirePrimaryNetworkSigners", - sourceChainID: testCChainID, + sourceChainID: vm.ctx.CChainID, msgFrom: fromPrimary, useSigners: signersSubnet, blockTime: upgrade.InitiallyActiveTime.Add(2 * blockGap), @@ -481,7 +482,7 @@ func TestReceiveWarpMessage(t *testing.T) { }, { name: "C-Chain message should be signed by primary with RequirePrimaryNetworkSigners (impacted)", - sourceChainID: testCChainID, + sourceChainID: vm.ctx.CChainID, msgFrom: fromPrimary, useSigners: signersPrimary, blockTime: reEnableTime.Add(2 * blockGap), @@ -607,20 +608,20 @@ func testReceiveWarpMessage( ) require.NoError(err) - getWarpMsgInput, err := warp.PackGetVerifiedWarpMessage(0) + getWarpMsgInput, err := warpcontract.PackGetVerifiedWarpMessage(0) require.NoError(err) getVerifiedWarpMessageTx, err := types.SignTx( predicate.NewPredicateTx( vm.chainConfig.ChainID, vm.txPool.Nonce(testEthAddrs[0]), - &warp.Module.Address, + &warpcontract.Module.Address, 1_000_000, big.NewInt(225*params.GWei), big.NewInt(params.GWei), common.Big0, getWarpMsgInput, types.AccessList{}, - warp.ContractAddress, + warpcontract.ContractAddress, signedMessage.Bytes(), ), types.LatestSignerForChainID(vm.chainConfig.ChainID), @@ -653,7 +654,7 @@ func testReceiveWarpMessage( // An empty bitset indicates success. txResultsBytes := results.GetResults( getVerifiedWarpMessageTx.Hash(), - warp.ContractAddress, + warpcontract.ContractAddress, ) bitset := set.BitsFromBytes(txResultsBytes) require.Zero(bitset.Len()) // Empty bitset indicates success @@ -686,8 +687,8 @@ func testReceiveWarpMessage( verifiedMessageTxReceipt := verifiedMessageReceipts[0] require.Equal(types.ReceiptStatusSuccessful, verifiedMessageTxReceipt.Status) - expectedOutput, err := warp.PackGetVerifiedWarpMessageOutput(warp.GetVerifiedWarpMessageOutput{ - Message: warp.WarpMessage{ + expectedOutput, err := warpcontract.PackGetVerifiedWarpMessageOutput(warpcontract.GetVerifiedWarpMessageOutput{ + Message: warpcontract.WarpMessage{ SourceChainID: common.Hash(sourceChainID), OriginSenderAddress: testEthAddrs[0], Payload: payloadData, @@ -728,8 +729,10 @@ func TestMessageSignatureRequestsToVM(t *testing.T) { // Add the known message and get its signature to confirm. err = vm.warpBackend.AddMessage(warpMessage) require.NoError(t, err) - signature, err := vm.warpBackend.GetMessageSignature(warpMessage.ID()) + signature, err := vm.warpBackend.GetMessageSignature(context.TODO(), warpMessage) require.NoError(t, err) + var knownSignature [bls.SignatureLen]byte + copy(knownSignature[:], signature) tests := map[string]struct { messageID ids.ID @@ -737,7 +740,7 @@ func TestMessageSignatureRequestsToVM(t *testing.T) { }{ "known": { messageID: warpMessage.ID(), - expectedResponse: signature, + expectedResponse: knownSignature, }, "unknown": { messageID: ids.GenerateTestID(), @@ -784,8 +787,10 @@ func TestBlockSignatureRequestsToVM(t *testing.T) { lastAcceptedID, err := vm.LastAccepted(context.Background()) require.NoError(t, err) - signature, err := vm.warpBackend.GetBlockSignature(lastAcceptedID) + signature, err := vm.warpBackend.GetBlockSignature(context.TODO(), lastAcceptedID) require.NoError(t, err) + var knownSignature [bls.SignatureLen]byte + copy(knownSignature[:], signature) tests := map[string]struct { blockID ids.ID @@ -793,7 +798,7 @@ func TestBlockSignatureRequestsToVM(t *testing.T) { }{ "known": { blockID: lastAcceptedID, - expectedResponse: signature, + expectedResponse: knownSignature, }, "unknown": { blockID: ids.GenerateTestID(), @@ -828,3 +833,61 @@ func TestBlockSignatureRequestsToVM(t *testing.T) { }) } } + +func TestClearWarpDB(t *testing.T) { + ctx, db, genesisBytes, issuer, _ := setupGenesis(t, genesisJSONLatest) + vm := &VM{} + err := vm.Initialize(context.Background(), ctx, db, genesisBytes, []byte{}, []byte{}, issuer, []*commonEng.Fx{}, &enginetest.Sender{}) + require.NoError(t, err) + + // use multiple messages to test that all messages get cleared + payloads := [][]byte{[]byte("test1"), []byte("test2"), []byte("test3"), []byte("test4"), []byte("test5")} + messages := []*avalancheWarp.UnsignedMessage{} + + // add all messages + for _, payload := range payloads { + unsignedMsg, err := avalancheWarp.NewUnsignedMessage(vm.ctx.NetworkID, vm.ctx.ChainID, payload) + require.NoError(t, err) + err = vm.warpBackend.AddMessage(unsignedMsg) + require.NoError(t, err) + // ensure that the message was added + _, err = vm.warpBackend.GetMessageSignature(context.TODO(), unsignedMsg) + require.NoError(t, err) + messages = append(messages, unsignedMsg) + } + + require.NoError(t, vm.Shutdown(context.Background())) + + // Restart VM with the same database default should not prune the warp db + vm = &VM{} + // we need new context since the previous one has registered metrics. + ctx, _, _, _, _ = setupGenesis(t, genesisJSONLatest) + err = vm.Initialize(context.Background(), ctx, db, genesisBytes, []byte{}, []byte{}, issuer, []*commonEng.Fx{}, &enginetest.Sender{}) + require.NoError(t, err) + + // check messages are still present + for _, message := range messages { + bytes, err := vm.warpBackend.GetMessageSignature(context.TODO(), message) + require.NoError(t, err) + require.NotEmpty(t, bytes) + } + + require.NoError(t, vm.Shutdown(context.Background())) + + // restart the VM with pruning enabled + vm = &VM{} + config := `{"prune-warp-db-enabled": true}` + ctx, _, _, _, _ = setupGenesis(t, genesisJSONLatest) + err = vm.Initialize(context.Background(), ctx, db, genesisBytes, []byte{}, []byte(config), issuer, []*commonEng.Fx{}, &enginetest.Sender{}) + require.NoError(t, err) + + it := vm.warpDB.NewIterator() + require.False(t, it.Next()) + it.Release() + + // ensure all messages have been deleted + for _, message := range messages { + _, err := vm.warpBackend.GetMessageSignature(context.TODO(), message) + require.ErrorIs(t, err, &commonEng.AppError{Code: warp.ParseErrCode}) + } +} diff --git a/precompile/precompileconfig/config.go b/precompile/precompileconfig/config.go index 43365e3bf9..eb741cbc55 100644 --- a/precompile/precompileconfig/config.go +++ b/precompile/precompileconfig/config.go @@ -5,8 +5,6 @@ package precompileconfig import ( - "github.com/ava-labs/avalanchego/chains/atomic" - "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "github.com/ava-labs/avalanchego/vms/platformvm/warp" @@ -53,21 +51,14 @@ type Predicater interface { VerifyPredicate(predicateContext *PredicateContext, predicateBytes []byte) error } -// SharedMemoryWriter defines an interface to allow a precompile's Accepter to write operations -// into shared memory to be committed atomically on block accept. -type SharedMemoryWriter interface { - AddSharedMemoryRequests(chainID ids.ID, requests *atomic.Requests) -} - type WarpMessageWriter interface { AddMessage(unsignedMessage *warp.UnsignedMessage) error } // AcceptContext defines the context passed in to a precompileconfig's Accepter type AcceptContext struct { - SnowCtx *snow.Context - SharedMemory SharedMemoryWriter - Warp WarpMessageWriter + SnowCtx *snow.Context + Warp WarpMessageWriter } // Accepter is an optional interface for StatefulPrecompiledContracts to implement. diff --git a/scripts/versions.sh b/scripts/versions.sh index 2294b628bf..7072589cb1 100644 --- a/scripts/versions.sh +++ b/scripts/versions.sh @@ -6,4 +6,4 @@ set -euo pipefail # Don't export them as they're used in the context of other calls -AVALANCHE_VERSION=${AVALANCHE_VERSION:-'v1.11.12-rc.3'} +AVALANCHE_VERSION=${AVALANCHE_VERSION:-'v1.12.0-initial-poc.9'} diff --git a/tests/state_test_util.go b/tests/state_test_util.go index a919bbb725..dc3dcb1ea4 100644 --- a/tests/state_test_util.go +++ b/tests/state_test_util.go @@ -66,7 +66,7 @@ func MakePreState(db ethdb.Database, accounts types.GenesisAlloc, snapshotter bo } } // Commit and re-open to start with a clean state. - root, _ := statedb.Commit(0, false, false) + root, _ := statedb.Commit(0, false) // If snapshot is requested, initialize the snapshotter and use it in state. var snaps *snapshot.Tree diff --git a/triedb/database.go b/triedb/database.go index 295c723bbc..7421b74cf0 100644 --- a/triedb/database.go +++ b/triedb/database.go @@ -148,17 +148,6 @@ func (db *Database) Update(root common.Hash, parent common.Hash, block uint64, n return db.backend.Update(root, parent, block, nodes, states) } -func (db *Database) UpdateAndReferenceRoot(root common.Hash, parent common.Hash, block uint64, nodes *trienode.MergedNodeSet, states *triestate.Set) error { - if db.preimages != nil { - db.preimages.commit(false) - } - hdb, ok := db.backend.(*hashdb.Database) - if ok { - return hdb.UpdateAndReferenceRoot(root, parent, block, nodes, states) - } - return db.backend.Update(root, parent, block, nodes, states) -} - // Commit iterates over all the children of a particular node, writes them out // to disk. As a side effect, all pre-images accumulated up to this point are // also written. diff --git a/triedb/hashdb/database.go b/triedb/hashdb/database.go index f5c55b3198..11efee0fb8 100644 --- a/triedb/hashdb/database.go +++ b/triedb/hashdb/database.go @@ -97,8 +97,9 @@ type cache interface { // Config contains the settings for database. type Config struct { - CleanCacheSize int // Maximum memory allowance (in bytes) for caching clean nodes - StatsPrefix string // Prefix for cache stats (disabled if empty) + CleanCacheSize int // Maximum memory allowance (in bytes) for caching clean nodes + StatsPrefix string // Prefix for cache stats (disabled if empty) + ReferenceRootAtomicallyOnUpdate bool // Whether to reference the root node on update } // Defaults is the default setting for database if it's not specified. @@ -137,6 +138,8 @@ type Database struct { childrenSize common.StorageSize // Storage size of the external children tracking lock sync.RWMutex + + referenceRoot bool } // cachedNode is all the information we know about a single cached trie node @@ -174,10 +177,11 @@ func New(diskdb ethdb.Database, config *Config, resolver ChildResolver) *Databas cleans = utils.NewMeteredCache(config.CleanCacheSize, config.StatsPrefix, cacheStatsUpdateFrequency) } return &Database{ - diskdb: diskdb, - resolver: resolver, - cleans: cleans, - dirties: make(map[common.Hash]*cachedNode), + diskdb: diskdb, + resolver: resolver, + cleans: cleans, + dirties: make(map[common.Hash]*cachedNode), + referenceRoot: config.ReferenceRootAtomicallyOnUpdate, } } @@ -627,6 +631,8 @@ func (db *Database) Initialized(genesisRoot common.Hash) bool { // Update inserts the dirty nodes in provided nodeset into database and link the // account trie with multiple storage tries if necessary. +// If ReferenceRootAtomicallyOnUpdate was enabled in the config, it will also add a reference from +// the root to the metaroot while holding the db's lock. func (db *Database) Update(root common.Hash, parent common.Hash, block uint64, nodes *trienode.MergedNodeSet, states *triestate.Set) error { // Ensure the parent state is present and signal a warning if not. if parent != types.EmptyRootHash { @@ -637,26 +643,13 @@ func (db *Database) Update(root common.Hash, parent common.Hash, block uint64, n db.lock.Lock() defer db.lock.Unlock() - return db.update(root, parent, nodes) -} - -// UpdateAndReferenceRoot inserts the dirty nodes in provided nodeset into -// database and links the account trie with multiple storage tries if necessary, -// then adds a reference [from] root to the metaroot while holding the db's lock. -func (db *Database) UpdateAndReferenceRoot(root common.Hash, parent common.Hash, block uint64, nodes *trienode.MergedNodeSet, states *triestate.Set) error { - // Ensure the parent state is present and signal a warning if not. - if parent != types.EmptyRootHash { - if blob, _ := db.node(parent); len(blob) == 0 { - log.Error("parent state is not present") - } - } - db.lock.Lock() - defer db.lock.Unlock() - if err := db.update(root, parent, nodes); err != nil { return err } - db.reference(root, common.Hash{}) + + if db.referenceRoot { + db.reference(root, common.Hash{}) + } return nil } diff --git a/utils/snow.go b/utils/snow.go index 77368f0750..e46e2ac7b1 100644 --- a/utils/snow.go +++ b/utils/snow.go @@ -4,12 +4,24 @@ package utils import ( + "context" + "errors" + "github.com/ava-labs/avalanchego/api/metrics" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" + "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/snow/validators/validatorstest" + "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/logging" + "github.com/ava-labs/avalanchego/vms/platformvm/warp" +) + +var ( + testCChainID = ids.ID{'c', 'c', 'h', 'a', 'i', 'n', 't', 'e', 's', 't'} + testXChainID = ids.ID{'t', 'e', 's', 't', 'x'} + testChainID = ids.ID{'t', 'e', 's', 't', 'c', 'h', 'a', 'i', 'n'} ) func TestSnowContext() *snow.Context { @@ -18,16 +30,49 @@ func TestSnowContext() *snow.Context { panic(err) } pk := bls.PublicFromSecretKey(sk) - return &snow.Context{ - NetworkID: 0, + networkID := constants.UnitTestID + chainID := testChainID + + ctx := &snow.Context{ + NetworkID: networkID, SubnetID: ids.Empty, - ChainID: ids.Empty, - NodeID: ids.EmptyNodeID, + ChainID: chainID, + NodeID: ids.GenerateTestNodeID(), + XChainID: testXChainID, + CChainID: testCChainID, PublicKey: pk, + WarpSigner: warp.NewSigner(sk, networkID, chainID), Log: logging.NoLog{}, BCLookup: ids.NewAliaser(), Metrics: metrics.NewPrefixGatherer(), ChainDataDir: "", - ValidatorState: &validatorstest.State{}, + ValidatorState: NewTestValidatorState(), + } + + return ctx +} + +func NewTestValidatorState() *validatorstest.State { + return &validatorstest.State{ + GetCurrentHeightF: func(context.Context) (uint64, error) { + return 0, nil + }, + GetSubnetIDF: func(_ context.Context, chainID ids.ID) (ids.ID, error) { + subnetID, ok := map[ids.ID]ids.ID{ + constants.PlatformChainID: constants.PrimaryNetworkID, + testXChainID: constants.PrimaryNetworkID, + testCChainID: constants.PrimaryNetworkID, + }[chainID] + if !ok { + return ids.Empty, errors.New("unknown chain") + } + return subnetID, nil + }, + GetValidatorSetF: func(context.Context, uint64, ids.ID) (map[ids.NodeID]*validators.GetValidatorOutput, error) { + return map[ids.NodeID]*validators.GetValidatorOutput{}, nil + }, + GetCurrentValidatorSetF: func(context.Context, ids.ID) (map[ids.ID]*validators.GetCurrentValidatorOutput, uint64, error) { + return map[ids.ID]*validators.GetCurrentValidatorOutput{}, 0, nil + }, } } diff --git a/warp/backend.go b/warp/backend.go index 7e7377ad57..6e1f6a9553 100644 --- a/warp/backend.go +++ b/warp/backend.go @@ -11,20 +11,19 @@ import ( "github.com/ava-labs/avalanchego/cache" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/network/p2p/acp118" "github.com/ava-labs/avalanchego/snow/consensus/snowman" - "github.com/ava-labs/avalanchego/utils/crypto/bls" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" - "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" ) var ( _ Backend = &backend{} errParsingOffChainMessage = errors.New("failed to parse off-chain message") -) -const batchSize = ethdb.IdealBatchSize + messageCacheSize = 500 +) type BlockClient interface { GetAcceptedBlock(ctx context.Context, blockID ids.ID) (snowman.Block, error) @@ -36,19 +35,18 @@ type Backend interface { // AddMessage signs [unsignedMessage] and adds it to the warp backend database AddMessage(unsignedMessage *avalancheWarp.UnsignedMessage) error - // GetMessageSignature returns the signature of the requested message hash. - GetMessageSignature(messageID ids.ID) ([bls.SignatureLen]byte, error) + // GetMessageSignature validates the message and returns the signature of the requested message. + GetMessageSignature(ctx context.Context, message *avalancheWarp.UnsignedMessage) ([]byte, error) - // GetBlockSignature returns the signature of the requested message hash. - GetBlockSignature(blockID ids.ID) ([bls.SignatureLen]byte, error) + // GetBlockSignature returns the signature of a hash payload containing blockID if it's the ID of an accepted block. + GetBlockSignature(ctx context.Context, blockID ids.ID) ([]byte, error) // GetMessage retrieves the [unsignedMessage] from the warp backend database if available - // TODO: After E-Upgrade, the backend no longer needs to store the mapping from messageHash + // TODO: After Etna, the backend no longer needs to store the mapping from messageHash // to unsignedMessage (and this method can be removed). GetMessage(messageHash ids.ID) (*avalancheWarp.UnsignedMessage, error) - // Clear clears the entire db - Clear() error + acp118.Verifier } // backend implements Backend, keeps track of warp messages, and generates message signatures. @@ -58,10 +56,10 @@ type backend struct { db database.Database warpSigner avalancheWarp.Signer blockClient BlockClient - messageSignatureCache *cache.LRU[ids.ID, [bls.SignatureLen]byte] - blockSignatureCache *cache.LRU[ids.ID, [bls.SignatureLen]byte] + signatureCache cache.Cacher[ids.ID, []byte] messageCache *cache.LRU[ids.ID, *avalancheWarp.UnsignedMessage] offchainAddressedCallMsgs map[ids.ID]*avalancheWarp.UnsignedMessage + stats *verifierStats } // NewBackend creates a new Backend, and initializes the signature cache and message tracking database. @@ -71,7 +69,7 @@ func NewBackend( warpSigner avalancheWarp.Signer, blockClient BlockClient, db database.Database, - cacheSize int, + signatureCache cache.Cacher[ids.ID, []byte], offchainMessages [][]byte, ) (Backend, error) { b := &backend{ @@ -80,9 +78,9 @@ func NewBackend( db: db, warpSigner: warpSigner, blockClient: blockClient, - messageSignatureCache: &cache.LRU[ids.ID, [bls.SignatureLen]byte]{Size: cacheSize}, - blockSignatureCache: &cache.LRU[ids.ID, [bls.SignatureLen]byte]{Size: cacheSize}, - messageCache: &cache.LRU[ids.ID, *avalancheWarp.UnsignedMessage]{Size: cacheSize}, + signatureCache: signatureCache, + messageCache: &cache.LRU[ids.ID, *avalancheWarp.UnsignedMessage]{Size: messageCacheSize}, + stats: newVerifierStats(), offchainAddressedCallMsgs: make(map[ids.ID]*avalancheWarp.UnsignedMessage), } return b, b.initOffChainMessages(offchainMessages) @@ -113,15 +111,9 @@ func (b *backend) initOffChainMessages(offchainMessages [][]byte) error { return nil } -func (b *backend) Clear() error { - b.messageSignatureCache.Flush() - b.blockSignatureCache.Flush() - b.messageCache.Flush() - return database.Clear(b.db, batchSize) -} - func (b *backend) AddMessage(unsignedMessage *avalancheWarp.UnsignedMessage) error { messageID := unsignedMessage.ID() + log.Debug("Adding warp message to backend", "messageID", messageID) // In the case when a node restarts, and possibly changes its bls key, the cache gets emptied but the database does not. // So to avoid having incorrect signatures saved in the database after a bls key change, we save the full message in the database. @@ -130,68 +122,52 @@ func (b *backend) AddMessage(unsignedMessage *avalancheWarp.UnsignedMessage) err return fmt.Errorf("failed to put warp signature in db: %w", err) } - var signature [bls.SignatureLen]byte - sig, err := b.warpSigner.Sign(unsignedMessage) - if err != nil { + if _, err := b.signMessage(unsignedMessage); err != nil { return fmt.Errorf("failed to sign warp message: %w", err) } - - copy(signature[:], sig) - b.messageSignatureCache.Put(messageID, signature) - log.Debug("Adding warp message to backend", "messageID", messageID) return nil } -func (b *backend) GetMessageSignature(messageID ids.ID) ([bls.SignatureLen]byte, error) { +func (b *backend) GetMessageSignature(ctx context.Context, unsignedMessage *avalancheWarp.UnsignedMessage) ([]byte, error) { + messageID := unsignedMessage.ID() + log.Debug("Getting warp message from backend", "messageID", messageID) - if sig, ok := b.messageSignatureCache.Get(messageID); ok { + if sig, ok := b.signatureCache.Get(messageID); ok { return sig, nil } - unsignedMessage, err := b.GetMessage(messageID) - if err != nil { - return [bls.SignatureLen]byte{}, fmt.Errorf("failed to get warp message %s from db: %w", messageID.String(), err) + if err := b.Verify(ctx, unsignedMessage, nil); err != nil { + return nil, fmt.Errorf("failed to validate warp message: %w", err) } - - var signature [bls.SignatureLen]byte - sig, err := b.warpSigner.Sign(unsignedMessage) - if err != nil { - return [bls.SignatureLen]byte{}, fmt.Errorf("failed to sign warp message: %w", err) - } - - copy(signature[:], sig) - b.messageSignatureCache.Put(messageID, signature) - return signature, nil + return b.signMessage(unsignedMessage) } -func (b *backend) GetBlockSignature(blockID ids.ID) ([bls.SignatureLen]byte, error) { +func (b *backend) GetBlockSignature(ctx context.Context, blockID ids.ID) ([]byte, error) { log.Debug("Getting block from backend", "blockID", blockID) - if sig, ok := b.blockSignatureCache.Get(blockID); ok { - return sig, nil - } - _, err := b.blockClient.GetAcceptedBlock(context.TODO(), blockID) - if err != nil { - return [bls.SignatureLen]byte{}, fmt.Errorf("failed to get block %s: %w", blockID, err) - } - - var signature [bls.SignatureLen]byte blockHashPayload, err := payload.NewHash(blockID) if err != nil { - return [bls.SignatureLen]byte{}, fmt.Errorf("failed to create new block hash payload: %w", err) + return nil, fmt.Errorf("failed to create new block hash payload: %w", err) } + unsignedMessage, err := avalancheWarp.NewUnsignedMessage(b.networkID, b.sourceChainID, blockHashPayload.Bytes()) if err != nil { - return [bls.SignatureLen]byte{}, fmt.Errorf("failed to create new unsigned warp message: %w", err) + return nil, fmt.Errorf("failed to create new unsigned warp message: %w", err) } - sig, err := b.warpSigner.Sign(unsignedMessage) - if err != nil { - return [bls.SignatureLen]byte{}, fmt.Errorf("failed to sign warp message: %w", err) + + if sig, ok := b.signatureCache.Get(unsignedMessage.ID()); ok { + return sig, nil + } + + if err := b.verifyBlockMessage(ctx, blockHashPayload); err != nil { + return nil, fmt.Errorf("failed to validate block message: %w", err) } - copy(signature[:], sig) - b.blockSignatureCache.Put(blockID, signature) - return signature, nil + sig, err := b.signMessage(unsignedMessage) + if err != nil { + return nil, fmt.Errorf("failed to sign block message: %w", err) + } + return sig, nil } func (b *backend) GetMessage(messageID ids.ID) (*avalancheWarp.UnsignedMessage, error) { @@ -215,3 +191,13 @@ func (b *backend) GetMessage(messageID ids.ID) (*avalancheWarp.UnsignedMessage, return unsignedMessage, nil } + +func (b *backend) signMessage(unsignedMessage *avalancheWarp.UnsignedMessage) ([]byte, error) { + sig, err := b.warpSigner.Sign(unsignedMessage) + if err != nil { + return nil, fmt.Errorf("failed to sign warp message: %w", err) + } + + b.signatureCache.Put(unsignedMessage.ID(), sig) + return sig, nil +} diff --git a/warp/backend_test.go b/warp/backend_test.go index 7b2208a2d4..5a0a64a0c2 100644 --- a/warp/backend_test.go +++ b/warp/backend_test.go @@ -4,13 +4,14 @@ package warp import ( + "context" "testing" + "github.com/ava-labs/avalanchego/cache" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/crypto/bls" - "github.com/ava-labs/avalanchego/utils/hashing" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" "github.com/ava-labs/coreth/warp/warptest" @@ -36,57 +37,14 @@ func init() { } } -func TestClearDB(t *testing.T) { - db := memdb.New() - - sk, err := bls.NewSecretKey() - require.NoError(t, err) - warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) - backendIntf, err := NewBackend(networkID, sourceChainID, warpSigner, nil, db, 500, nil) - require.NoError(t, err) - backend, ok := backendIntf.(*backend) - require.True(t, ok) - - // use multiple messages to test that all messages get cleared - payloads := [][]byte{[]byte("test1"), []byte("test2"), []byte("test3"), []byte("test4"), []byte("test5")} - messageIDs := []ids.ID{} - - // add all messages - for _, payload := range payloads { - unsignedMsg, err := avalancheWarp.NewUnsignedMessage(networkID, sourceChainID, payload) - require.NoError(t, err) - messageID := hashing.ComputeHash256Array(unsignedMsg.Bytes()) - messageIDs = append(messageIDs, messageID) - err = backend.AddMessage(unsignedMsg) - require.NoError(t, err) - // ensure that the message was added - _, err = backend.GetMessageSignature(messageID) - require.NoError(t, err) - } - - err = backend.Clear() - require.NoError(t, err) - require.Zero(t, backend.messageCache.Len()) - require.Zero(t, backend.messageSignatureCache.Len()) - require.Zero(t, backend.blockSignatureCache.Len()) - it := db.NewIterator() - defer it.Release() - require.False(t, it.Next()) - - // ensure all messages have been deleted - for _, messageID := range messageIDs { - _, err := backend.GetMessageSignature(messageID) - require.ErrorContains(t, err, "failed to get warp message") - } -} - func TestAddAndGetValidMessage(t *testing.T) { db := memdb.New() sk, err := bls.NewSecretKey() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) - backend, err := NewBackend(networkID, sourceChainID, warpSigner, nil, db, 500, nil) + messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 500} + backend, err := NewBackend(networkID, sourceChainID, warpSigner, nil, db, messageSignatureCache, nil) require.NoError(t, err) // Add testUnsignedMessage to the warp backend @@ -94,8 +52,7 @@ func TestAddAndGetValidMessage(t *testing.T) { require.NoError(t, err) // Verify that a signature is returned successfully, and compare to expected signature. - messageID := testUnsignedMessage.ID() - signature, err := backend.GetMessageSignature(messageID) + signature, err := backend.GetMessageSignature(context.TODO(), testUnsignedMessage) require.NoError(t, err) expectedSig, err := warpSigner.Sign(testUnsignedMessage) @@ -109,12 +66,12 @@ func TestAddAndGetUnknownMessage(t *testing.T) { sk, err := bls.NewSecretKey() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) - backend, err := NewBackend(networkID, sourceChainID, warpSigner, nil, db, 500, nil) + messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 500} + backend, err := NewBackend(networkID, sourceChainID, warpSigner, nil, db, messageSignatureCache, nil) require.NoError(t, err) // Try getting a signature for a message that was not added. - messageID := testUnsignedMessage.ID() - _, err = backend.GetMessageSignature(messageID) + _, err = backend.GetMessageSignature(context.TODO(), testUnsignedMessage) require.Error(t, err) } @@ -128,7 +85,8 @@ func TestGetBlockSignature(t *testing.T) { sk, err := bls.NewSecretKey() require.NoError(err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) - backend, err := NewBackend(networkID, sourceChainID, warpSigner, blockClient, db, 500, nil) + messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 500} + backend, err := NewBackend(networkID, sourceChainID, warpSigner, blockClient, db, messageSignatureCache, nil) require.NoError(err) blockHashPayload, err := payload.NewHash(blkID) @@ -138,11 +96,11 @@ func TestGetBlockSignature(t *testing.T) { expectedSig, err := warpSigner.Sign(unsignedMessage) require.NoError(err) - signature, err := backend.GetBlockSignature(blkID) + signature, err := backend.GetBlockSignature(context.TODO(), blkID) require.NoError(err) require.Equal(expectedSig, signature[:]) - _, err = backend.GetBlockSignature(ids.GenerateTestID()) + _, err = backend.GetBlockSignature(context.TODO(), ids.GenerateTestID()) require.Error(err) } @@ -154,7 +112,8 @@ func TestZeroSizedCache(t *testing.T) { warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) // Verify zero sized cache works normally, because the lru cache will be initialized to size 1 for any size parameter <= 0. - backend, err := NewBackend(networkID, sourceChainID, warpSigner, nil, db, 0, nil) + messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 0} + backend, err := NewBackend(networkID, sourceChainID, warpSigner, nil, db, messageSignatureCache, nil) require.NoError(t, err) // Add testUnsignedMessage to the warp backend @@ -162,8 +121,7 @@ func TestZeroSizedCache(t *testing.T) { require.NoError(t, err) // Verify that a signature is returned successfully, and compare to expected signature. - messageID := testUnsignedMessage.ID() - signature, err := backend.GetMessageSignature(messageID) + signature, err := backend.GetMessageSignature(context.TODO(), testUnsignedMessage) require.NoError(t, err) expectedSig, err := warpSigner.Sign(testUnsignedMessage) @@ -192,7 +150,7 @@ func TestOffChainMessages(t *testing.T) { require.NoError(err) require.Equal(testUnsignedMessage.Bytes(), msg.Bytes()) - signature, err := b.GetMessageSignature(testUnsignedMessage.ID()) + signature, err := b.GetMessageSignature(context.TODO(), testUnsignedMessage) require.NoError(err) expectedSignatureBytes, err := warpSigner.Sign(msg) require.NoError(err) @@ -208,7 +166,8 @@ func TestOffChainMessages(t *testing.T) { require := require.New(t) db := memdb.New() - backend, err := NewBackend(networkID, sourceChainID, warpSigner, nil, db, 0, test.offchainMessages) + messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 0} + backend, err := NewBackend(networkID, sourceChainID, warpSigner, nil, db, messageSignatureCache, test.offchainMessages) require.ErrorIs(err, test.err) if test.check != nil { test.check(require, backend) diff --git a/warp/handlers/signature_request.go b/warp/handlers/signature_request.go index 8a8b4e4e1e..bb9c2c7855 100644 --- a/warp/handlers/signature_request.go +++ b/warp/handlers/signature_request.go @@ -16,7 +16,7 @@ import ( ) // SignatureRequestHandler serves warp signature requests. It is a peer.RequestHandler for message.MessageSignatureRequest. -// TODO: After E-Upgrade, this handler can be removed and SignatureRequestHandlerP2P is sufficient. +// TODO: After Etna, this handler can be removed and SignatureRequestHandlerP2P is sufficient. type SignatureRequestHandler struct { backend warp.Backend codec codec.Manager @@ -45,13 +45,20 @@ func (s *SignatureRequestHandler) OnMessageSignatureRequest(ctx context.Context, s.stats.UpdateMessageSignatureRequestTime(time.Since(startTime)) }() - signature, err := s.backend.GetMessageSignature(signatureRequest.MessageID) + var signature [bls.SignatureLen]byte + unsignedMessage, err := s.backend.GetMessage(signatureRequest.MessageID) if err != nil { - log.Debug("Unknown warp signature requested", "messageID", signatureRequest.MessageID) + log.Debug("Unknown warp message requested", "messageID", signatureRequest.MessageID) s.stats.IncMessageSignatureMiss() - signature = [bls.SignatureLen]byte{} } else { - s.stats.IncMessageSignatureHit() + sig, err := s.backend.GetMessageSignature(ctx, unsignedMessage) + if err != nil { + log.Debug("Unknown warp signature requested", "messageID", signatureRequest.MessageID) + s.stats.IncMessageSignatureMiss() + } else { + s.stats.IncMessageSignatureHit() + copy(signature[:], sig) + } } response := message.SignatureResponse{Signature: signature} @@ -73,13 +80,14 @@ func (s *SignatureRequestHandler) OnBlockSignatureRequest(ctx context.Context, n s.stats.UpdateBlockSignatureRequestTime(time.Since(startTime)) }() - signature, err := s.backend.GetBlockSignature(request.BlockID) + var signature [bls.SignatureLen]byte + sig, err := s.backend.GetBlockSignature(ctx, request.BlockID) if err != nil { log.Debug("Unknown warp signature requested", "blockID", request.BlockID) s.stats.IncBlockSignatureMiss() - signature = [bls.SignatureLen]byte{} } else { s.stats.IncBlockSignatureHit() + copy(signature[:], sig) } response := message.SignatureResponse{Signature: signature} diff --git a/warp/handlers/signature_request_p2p.go b/warp/handlers/signature_request_p2p.go deleted file mode 100644 index 47fe2d0908..0000000000 --- a/warp/handlers/signature_request_p2p.go +++ /dev/null @@ -1,151 +0,0 @@ -// (c) 2024, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package handlers - -import ( - "context" - "fmt" - "time" - - "github.com/ava-labs/avalanchego/codec" - "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/network/p2p" - "github.com/ava-labs/avalanchego/proto/pb/sdk" - "github.com/ava-labs/avalanchego/snow/engine/common" - "github.com/ava-labs/avalanchego/utils/crypto/bls" - avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" - "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" - "github.com/ava-labs/coreth/warp" - "google.golang.org/protobuf/proto" -) - -var _ p2p.Handler = (*SignatureRequestHandlerP2P)(nil) - -const ( - ErrFailedToParse = iota - ErrFailedToGetSig - ErrFailedToMarshal -) - -// SignatureRequestHandlerP2P serves warp signature requests using the p2p -// framework from avalanchego. It is a peer.RequestHandler for -// message.MessageSignatureRequest. -type SignatureRequestHandlerP2P struct { - backend warp.Backend - codec codec.Manager - stats *handlerStats -} - -func NewSignatureRequestHandlerP2P(backend warp.Backend, codec codec.Manager) *SignatureRequestHandlerP2P { - return &SignatureRequestHandlerP2P{ - backend: backend, - codec: codec, - stats: newStats(), - } -} - -func (s *SignatureRequestHandlerP2P) AppRequest( - ctx context.Context, - nodeID ids.NodeID, - deadline time.Time, - requestBytes []byte, -) ([]byte, *common.AppError) { - // Per ACP-118, the requestBytes are the serialized form of - // sdk.SignatureRequest. - req := new(sdk.SignatureRequest) - if err := proto.Unmarshal(requestBytes, req); err != nil { - return nil, &common.AppError{ - Code: ErrFailedToParse, - Message: "failed to unmarshal request: " + err.Error(), - } - } - - unsignedMessage, err := avalancheWarp.ParseUnsignedMessage(req.Message) - if err != nil { - return nil, &common.AppError{ - Code: ErrFailedToParse, - Message: "failed to parse unsigned message: " + err.Error(), - } - } - parsed, err := payload.Parse(unsignedMessage.Payload) - if err != nil { - return nil, &common.AppError{ - Code: ErrFailedToParse, - Message: "failed to parse payload: " + err.Error(), - } - } - - var sig [bls.SignatureLen]byte - switch p := parsed.(type) { - case *payload.AddressedCall: - // Note we pass the unsigned message ID to GetMessageSignature since - // that is what the backend expects. - // However, we verify the types and format of the payload to ensure - // the message conforms to the ACP-118 spec. - sig, err = s.GetMessageSignature(unsignedMessage.ID()) - if err != nil { - s.stats.IncMessageSignatureMiss() - } else { - s.stats.IncMessageSignatureHit() - } - case *payload.Hash: - sig, err = s.GetBlockSignature(p.Hash) - if err != nil { - s.stats.IncBlockSignatureMiss() - } else { - s.stats.IncBlockSignatureHit() - } - default: - return nil, &common.AppError{ - Code: ErrFailedToParse, - Message: fmt.Sprintf("unknown payload type: %T", p), - } - } - if err != nil { - return nil, &common.AppError{ - Code: ErrFailedToGetSig, - Message: "failed to get signature: " + err.Error(), - } - } - - // Per ACP-118, the responseBytes are the serialized form of - // sdk.SignatureResponse. - resp := &sdk.SignatureResponse{Signature: sig[:]} - respBytes, err := proto.Marshal(resp) - if err != nil { - return nil, &common.AppError{ - Code: ErrFailedToMarshal, - Message: "failed to marshal response: " + err.Error(), - } - } - return respBytes, nil -} - -func (s *SignatureRequestHandlerP2P) GetMessageSignature(messageID ids.ID) ([bls.SignatureLen]byte, error) { - startTime := time.Now() - s.stats.IncMessageSignatureRequest() - - // Always report signature request time - defer func() { - s.stats.UpdateMessageSignatureRequestTime(time.Since(startTime)) - }() - - return s.backend.GetMessageSignature(messageID) -} - -func (s *SignatureRequestHandlerP2P) GetBlockSignature(blockID ids.ID) ([bls.SignatureLen]byte, error) { - startTime := time.Now() - s.stats.IncBlockSignatureRequest() - - // Always report signature request time - defer func() { - s.stats.UpdateBlockSignatureRequestTime(time.Since(startTime)) - }() - - return s.backend.GetBlockSignature(blockID) -} - -func (s *SignatureRequestHandlerP2P) AppGossip( - ctx context.Context, nodeID ids.NodeID, gossipBytes []byte) { -} diff --git a/warp/handlers/signature_request_p2p_test.go b/warp/handlers/signature_request_p2p_test.go deleted file mode 100644 index 36d6507771..0000000000 --- a/warp/handlers/signature_request_p2p_test.go +++ /dev/null @@ -1,232 +0,0 @@ -// (c) 2024, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package handlers - -import ( - "context" - "testing" - "time" - - "github.com/ava-labs/avalanchego/database/memdb" - "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/proto/pb/sdk" - "github.com/ava-labs/avalanchego/snow/engine/common" - "github.com/ava-labs/avalanchego/utils/crypto/bls" - avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" - "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" - "github.com/ava-labs/coreth/plugin/evm/message" - "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/coreth/warp" - "github.com/ava-labs/coreth/warp/warptest" - "github.com/stretchr/testify/require" - "google.golang.org/protobuf/proto" -) - -func TestMessageSignatureHandlerP2P(t *testing.T) { - database := memdb.New() - snowCtx := utils.TestSnowContext() - blsSecretKey, err := bls.NewSecretKey() - require.NoError(t, err) - warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) - - addressedPayload, err := payload.NewAddressedCall([]byte{1, 2, 3}, []byte{1, 2, 3}) - require.NoError(t, err) - offchainMessage, err := avalancheWarp.NewUnsignedMessage(snowCtx.NetworkID, snowCtx.ChainID, addressedPayload.Bytes()) - require.NoError(t, err) - - backend, err := warp.NewBackend(snowCtx.NetworkID, snowCtx.ChainID, warpSigner, warptest.EmptyBlockClient, database, 100, [][]byte{offchainMessage.Bytes()}) - require.NoError(t, err) - - offchainPayload, err := payload.NewAddressedCall([]byte{0, 0, 0}, []byte("test")) - require.NoError(t, err) - msg, err := avalancheWarp.NewUnsignedMessage(snowCtx.NetworkID, snowCtx.ChainID, offchainPayload.Bytes()) - require.NoError(t, err) - messageID := msg.ID() - require.NoError(t, backend.AddMessage(msg)) - signature, err := backend.GetMessageSignature(messageID) - require.NoError(t, err) - offchainSignature, err := backend.GetMessageSignature(offchainMessage.ID()) - require.NoError(t, err) - - unknownPayload, err := payload.NewAddressedCall([]byte{0, 0, 0}, []byte("unknown message")) - require.NoError(t, err) - unknownMessage, err := avalancheWarp.NewUnsignedMessage(snowCtx.NetworkID, snowCtx.ChainID, unknownPayload.Bytes()) - require.NoError(t, err) - - tests := map[string]struct { - setup func() (request sdk.SignatureRequest, expectedResponse []byte) - verifyStats func(t *testing.T, stats *handlerStats) - err error - }{ - "known message": { - setup: func() (request sdk.SignatureRequest, expectedResponse []byte) { - return sdk.SignatureRequest{Message: msg.Bytes()}, signature[:] - }, - verifyStats: func(t *testing.T, stats *handlerStats) { - require.EqualValues(t, 1, stats.messageSignatureRequest.Snapshot().Count()) - require.EqualValues(t, 1, stats.messageSignatureHit.Snapshot().Count()) - require.EqualValues(t, 0, stats.messageSignatureMiss.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureRequest.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureHit.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureMiss.Snapshot().Count()) - }, - }, - "offchain message": { - setup: func() (request sdk.SignatureRequest, expectedResponse []byte) { - return sdk.SignatureRequest{Message: offchainMessage.Bytes()}, offchainSignature[:] - }, - verifyStats: func(t *testing.T, stats *handlerStats) { - require.EqualValues(t, 1, stats.messageSignatureRequest.Snapshot().Count()) - require.EqualValues(t, 1, stats.messageSignatureHit.Snapshot().Count()) - require.EqualValues(t, 0, stats.messageSignatureMiss.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureRequest.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureHit.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureMiss.Snapshot().Count()) - }, - }, - "unknown message": { - setup: func() (request sdk.SignatureRequest, expectedResponse []byte) { - return sdk.SignatureRequest{Message: unknownMessage.Bytes()}, nil - }, - verifyStats: func(t *testing.T, stats *handlerStats) { - require.EqualValues(t, 1, stats.messageSignatureRequest.Snapshot().Count()) - require.EqualValues(t, 0, stats.messageSignatureHit.Snapshot().Count()) - require.EqualValues(t, 1, stats.messageSignatureMiss.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureRequest.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureHit.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureMiss.Snapshot().Count()) - }, - err: &common.AppError{Code: ErrFailedToGetSig}, - }, - } - - for name, test := range tests { - t.Run(name, func(t *testing.T) { - handler := NewSignatureRequestHandlerP2P(backend, message.Codec) - handler.stats.Clear() - - request, expectedResponse := test.setup() - requestBytes, err := proto.Marshal(&request) - require.NoError(t, err) - responseBytes, appErr := handler.AppRequest(context.Background(), ids.GenerateTestNodeID(), time.Time{}, requestBytes) - if test.err != nil { - require.ErrorIs(t, appErr, test.err) - } else { - require.Nil(t, appErr) - } - - test.verifyStats(t, handler.stats) - - // If the expected response is empty, assert that the handler returns an empty response and return early. - if len(expectedResponse) == 0 { - require.Len(t, responseBytes, 0, "expected response to be empty") - return - } - var response sdk.SignatureResponse - err = proto.Unmarshal(responseBytes, &response) - require.NoError(t, err, "error unmarshalling SignatureResponse") - - require.Equal(t, expectedResponse, response.Signature) - }) - } -} - -func TestBlockSignatureHandlerP2P(t *testing.T) { - database := memdb.New() - snowCtx := utils.TestSnowContext() - blsSecretKey, err := bls.NewSecretKey() - require.NoError(t, err) - - warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) - blkID := ids.GenerateTestID() - blockClient := warptest.MakeBlockClient(blkID) - backend, err := warp.NewBackend( - snowCtx.NetworkID, - snowCtx.ChainID, - warpSigner, - blockClient, - database, - 100, - nil, - ) - require.NoError(t, err) - - signature, err := backend.GetBlockSignature(blkID) - require.NoError(t, err) - unknownBlockID := ids.GenerateTestID() - - toMessageBytes := func(id ids.ID) []byte { - idPayload, err := payload.NewHash(id) - require.NoError(t, err) - - msg, err := avalancheWarp.NewUnsignedMessage(snowCtx.NetworkID, snowCtx.ChainID, idPayload.Bytes()) - require.NoError(t, err) - - return msg.Bytes() - } - - tests := map[string]struct { - setup func() (request sdk.SignatureRequest, expectedResponse []byte) - verifyStats func(t *testing.T, stats *handlerStats) - err error - }{ - "known block": { - setup: func() (request sdk.SignatureRequest, expectedResponse []byte) { - return sdk.SignatureRequest{Message: toMessageBytes(blkID)}, signature[:] - }, - verifyStats: func(t *testing.T, stats *handlerStats) { - require.EqualValues(t, 0, stats.messageSignatureRequest.Snapshot().Count()) - require.EqualValues(t, 0, stats.messageSignatureHit.Snapshot().Count()) - require.EqualValues(t, 0, stats.messageSignatureMiss.Snapshot().Count()) - require.EqualValues(t, 1, stats.blockSignatureRequest.Snapshot().Count()) - require.EqualValues(t, 1, stats.blockSignatureHit.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureMiss.Snapshot().Count()) - }, - }, - "unknown block": { - setup: func() (request sdk.SignatureRequest, expectedResponse []byte) { - return sdk.SignatureRequest{Message: toMessageBytes(unknownBlockID)}, nil - }, - verifyStats: func(t *testing.T, stats *handlerStats) { - require.EqualValues(t, 0, stats.messageSignatureRequest.Snapshot().Count()) - require.EqualValues(t, 0, stats.messageSignatureHit.Snapshot().Count()) - require.EqualValues(t, 0, stats.messageSignatureMiss.Snapshot().Count()) - require.EqualValues(t, 1, stats.blockSignatureRequest.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureHit.Snapshot().Count()) - require.EqualValues(t, 1, stats.blockSignatureMiss.Snapshot().Count()) - }, - err: &common.AppError{Code: ErrFailedToGetSig}, - }, - } - - for name, test := range tests { - t.Run(name, func(t *testing.T) { - handler := NewSignatureRequestHandlerP2P(backend, message.Codec) - handler.stats.Clear() - - request, expectedResponse := test.setup() - requestBytes, err := proto.Marshal(&request) - require.NoError(t, err) - responseBytes, appErr := handler.AppRequest(context.Background(), ids.GenerateTestNodeID(), time.Time{}, requestBytes) - if test.err != nil { - require.ErrorIs(t, appErr, test.err) - } else { - require.Nil(t, appErr) - } - - test.verifyStats(t, handler.stats) - - // If the expected response is empty, assert that the handler returns an empty response and return early. - if len(expectedResponse) == 0 { - require.Len(t, responseBytes, 0, "expected response to be empty") - return - } - var response sdk.SignatureResponse - err = proto.Unmarshal(responseBytes, &response) - require.NoError(t, err, "error unmarshalling SignatureResponse") - - require.Equal(t, expectedResponse, response.Signature) - }) - } -} diff --git a/warp/handlers/signature_request_test.go b/warp/handlers/signature_request_test.go index b50a1b519b..dd2271988b 100644 --- a/warp/handlers/signature_request_test.go +++ b/warp/handlers/signature_request_test.go @@ -7,6 +7,7 @@ import ( "context" "testing" + "github.com/ava-labs/avalanchego/cache" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/crypto/bls" @@ -31,16 +32,17 @@ func TestMessageSignatureHandler(t *testing.T) { offchainMessage, err := avalancheWarp.NewUnsignedMessage(snowCtx.NetworkID, snowCtx.ChainID, addressedPayload.Bytes()) require.NoError(t, err) - backend, err := warp.NewBackend(snowCtx.NetworkID, snowCtx.ChainID, warpSigner, warptest.EmptyBlockClient, database, 100, [][]byte{offchainMessage.Bytes()}) + messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 100} + backend, err := warp.NewBackend(snowCtx.NetworkID, snowCtx.ChainID, warpSigner, warptest.EmptyBlockClient, database, messageSignatureCache, [][]byte{offchainMessage.Bytes()}) require.NoError(t, err) msg, err := avalancheWarp.NewUnsignedMessage(snowCtx.NetworkID, snowCtx.ChainID, []byte("test")) require.NoError(t, err) messageID := msg.ID() require.NoError(t, backend.AddMessage(msg)) - signature, err := backend.GetMessageSignature(messageID) + signature, err := backend.GetMessageSignature(context.TODO(), msg) require.NoError(t, err) - offchainSignature, err := backend.GetMessageSignature(offchainMessage.ID()) + offchainSignature, err := backend.GetMessageSignature(context.TODO(), offchainMessage) require.NoError(t, err) unknownMessageID := ids.GenerateTestID() @@ -101,7 +103,6 @@ func TestMessageSignatureHandler(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { handler := NewSignatureRequestHandler(backend, message.Codec) - handler.stats.Clear() request, expectedResponse := test.setup() responseBytes, err := handler.OnMessageSignatureRequest(context.Background(), ids.GenerateTestNodeID(), 1, request) @@ -132,18 +133,19 @@ func TestBlockSignatureHandler(t *testing.T) { warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) blkID := ids.GenerateTestID() blockClient := warptest.MakeBlockClient(blkID) + messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 100} backend, err := warp.NewBackend( snowCtx.NetworkID, snowCtx.ChainID, warpSigner, blockClient, database, - 100, + messageSignatureCache, nil, ) require.NoError(t, err) - signature, err := backend.GetBlockSignature(blkID) + signature, err := backend.GetBlockSignature(context.TODO(), blkID) require.NoError(t, err) unknownMessageID := ids.GenerateTestID() @@ -188,7 +190,6 @@ func TestBlockSignatureHandler(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { handler := NewSignatureRequestHandler(backend, message.Codec) - handler.stats.Clear() request, expectedResponse := test.setup() responseBytes, err := handler.OnBlockSignatureRequest(context.Background(), ids.GenerateTestNodeID(), 1, request) diff --git a/warp/handlers/stats.go b/warp/handlers/stats.go index 9e2ea373aa..ef3f31ae9a 100644 --- a/warp/handlers/stats.go +++ b/warp/handlers/stats.go @@ -24,14 +24,14 @@ type handlerStats struct { func newStats() *handlerStats { return &handlerStats{ - messageSignatureRequest: metrics.GetOrRegisterCounter("message_signature_request_count", nil), - messageSignatureHit: metrics.GetOrRegisterCounter("message_signature_request_hit", nil), - messageSignatureMiss: metrics.GetOrRegisterCounter("message_signature_request_miss", nil), - messageSignatureRequestDuration: metrics.GetOrRegisterGauge("message_signature_request_duration", nil), - blockSignatureRequest: metrics.GetOrRegisterCounter("block_signature_request_count", nil), - blockSignatureHit: metrics.GetOrRegisterCounter("block_signature_request_hit", nil), - blockSignatureMiss: metrics.GetOrRegisterCounter("block_signature_request_miss", nil), - blockSignatureRequestDuration: metrics.GetOrRegisterGauge("block_signature_request_duration", nil), + messageSignatureRequest: metrics.NewRegisteredCounter("message_signature_request_count", nil), + messageSignatureHit: metrics.NewRegisteredCounter("message_signature_request_hit", nil), + messageSignatureMiss: metrics.NewRegisteredCounter("message_signature_request_miss", nil), + messageSignatureRequestDuration: metrics.NewRegisteredGauge("message_signature_request_duration", nil), + blockSignatureRequest: metrics.NewRegisteredCounter("block_signature_request_count", nil), + blockSignatureHit: metrics.NewRegisteredCounter("block_signature_request_hit", nil), + blockSignatureMiss: metrics.NewRegisteredCounter("block_signature_request_miss", nil), + blockSignatureRequestDuration: metrics.NewRegisteredGauge("block_signature_request_duration", nil), } } @@ -47,13 +47,3 @@ func (h *handlerStats) IncBlockSignatureMiss() { h.blockSignatureMiss.Inc(1) func (h *handlerStats) UpdateBlockSignatureRequestTime(duration time.Duration) { h.blockSignatureRequestDuration.Inc(int64(duration)) } -func (h *handlerStats) Clear() { - h.messageSignatureRequest.Clear() - h.messageSignatureHit.Clear() - h.messageSignatureMiss.Clear() - h.messageSignatureRequestDuration.Update(0) - h.blockSignatureRequest.Clear() - h.blockSignatureHit.Clear() - h.blockSignatureMiss.Clear() - h.blockSignatureRequestDuration.Update(0) -} diff --git a/warp/service.go b/warp/service.go index 8b92da80db..610fc85a91 100644 --- a/warp/service.go +++ b/warp/service.go @@ -54,7 +54,11 @@ func (a *API) GetMessage(ctx context.Context, messageID ids.ID) (hexutil.Bytes, // GetMessageSignature returns the BLS signature associated with a messageID. func (a *API) GetMessageSignature(ctx context.Context, messageID ids.ID) (hexutil.Bytes, error) { - signature, err := a.backend.GetMessageSignature(messageID) + unsignedMessage, err := a.backend.GetMessage(messageID) + if err != nil { + return nil, fmt.Errorf("failed to get message %s with error %w", messageID, err) + } + signature, err := a.backend.GetMessageSignature(ctx, unsignedMessage) if err != nil { return nil, fmt.Errorf("failed to get signature for message %s with error %w", messageID, err) } @@ -63,7 +67,7 @@ func (a *API) GetMessageSignature(ctx context.Context, messageID ids.ID) (hexuti // GetBlockSignature returns the BLS signature associated with a blockID. func (a *API) GetBlockSignature(ctx context.Context, blockID ids.ID) (hexutil.Bytes, error) { - signature, err := a.backend.GetBlockSignature(blockID) + signature, err := a.backend.GetBlockSignature(ctx, blockID) if err != nil { return nil, fmt.Errorf("failed to get signature for block %s with error %w", blockID, err) } diff --git a/warp/verifier_backend.go b/warp/verifier_backend.go new file mode 100644 index 0000000000..c70563c585 --- /dev/null +++ b/warp/verifier_backend.go @@ -0,0 +1,64 @@ +// (c) 2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package warp + +import ( + "context" + "fmt" + + "github.com/ava-labs/avalanchego/snow/engine/common" + avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" + "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" +) + +const ( + ParseErrCode = iota + 1 + VerifyErrCode +) + +// Verify verifies the signature of the message +// It also implements the acp118.Verifier interface +func (b *backend) Verify(ctx context.Context, unsignedMessage *avalancheWarp.UnsignedMessage, _ []byte) *common.AppError { + messageID := unsignedMessage.ID() + // Known on-chain messages should be signed + if _, err := b.GetMessage(messageID); err == nil { + return nil + } + + parsed, err := payload.Parse(unsignedMessage.Payload) + if err != nil { + b.stats.IncMessageParseFail() + return &common.AppError{ + Code: ParseErrCode, + Message: "failed to parse payload: " + err.Error(), + } + } + + switch p := parsed.(type) { + case *payload.Hash: + return b.verifyBlockMessage(ctx, p) + default: + b.stats.IncMessageParseFail() + return &common.AppError{ + Code: ParseErrCode, + Message: fmt.Sprintf("unknown payload type: %T", p), + } + } +} + +// verifyBlockMessage returns nil if blockHashPayload contains the ID +// of an accepted block indicating it should be signed by the VM. +func (b *backend) verifyBlockMessage(ctx context.Context, blockHashPayload *payload.Hash) *common.AppError { + blockID := blockHashPayload.Hash + _, err := b.blockClient.GetAcceptedBlock(ctx, blockID) + if err != nil { + b.stats.IncBlockSignatureValidationFail() + return &common.AppError{ + Code: VerifyErrCode, + Message: fmt.Sprintf("failed to get block %s: %s", blockID, err.Error()), + } + } + + return nil +} diff --git a/warp/verifier_backend_test.go b/warp/verifier_backend_test.go new file mode 100644 index 0000000000..5ea3a37e0f --- /dev/null +++ b/warp/verifier_backend_test.go @@ -0,0 +1,255 @@ +// (c) 2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package warp + +import ( + "context" + "testing" + "time" + + "github.com/ava-labs/avalanchego/cache" + "github.com/ava-labs/avalanchego/database/memdb" + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/network/p2p/acp118" + "github.com/ava-labs/avalanchego/proto/pb/sdk" + "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/utils/crypto/bls" + avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" + "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" + "github.com/ava-labs/coreth/utils" + "github.com/ava-labs/coreth/warp/warptest" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +func TestAddressedCallSignatures(t *testing.T) { + database := memdb.New() + snowCtx := utils.TestSnowContext() + blsSecretKey, err := bls.NewSecretKey() + require.NoError(t, err) + warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) + + offChainPayload, err := payload.NewAddressedCall([]byte{1, 2, 3}, []byte{1, 2, 3}) + require.NoError(t, err) + offchainMessage, err := avalancheWarp.NewUnsignedMessage(snowCtx.NetworkID, snowCtx.ChainID, offChainPayload.Bytes()) + require.NoError(t, err) + offchainSignature, err := warpSigner.Sign(offchainMessage) + require.NoError(t, err) + + tests := map[string]struct { + setup func(backend Backend) (request []byte, expectedResponse []byte) + verifyStats func(t *testing.T, stats *verifierStats) + err error + }{ + "known message": { + setup: func(backend Backend) (request []byte, expectedResponse []byte) { + knownPayload, err := payload.NewAddressedCall([]byte{0, 0, 0}, []byte("test")) + require.NoError(t, err) + msg, err := avalancheWarp.NewUnsignedMessage(snowCtx.NetworkID, snowCtx.ChainID, knownPayload.Bytes()) + require.NoError(t, err) + signature, err := warpSigner.Sign(msg) + require.NoError(t, err) + + backend.AddMessage(msg) + return msg.Bytes(), signature[:] + }, + verifyStats: func(t *testing.T, stats *verifierStats) { + require.EqualValues(t, 0, stats.messageParseFail.Snapshot().Count()) + require.EqualValues(t, 0, stats.blockSignatureValidationFail.Snapshot().Count()) + }, + }, + "offchain message": { + setup: func(_ Backend) (request []byte, expectedResponse []byte) { + return offchainMessage.Bytes(), offchainSignature[:] + }, + verifyStats: func(t *testing.T, stats *verifierStats) { + require.EqualValues(t, 0, stats.messageParseFail.Snapshot().Count()) + require.EqualValues(t, 0, stats.blockSignatureValidationFail.Snapshot().Count()) + }, + }, + "unknown message": { + setup: func(_ Backend) (request []byte, expectedResponse []byte) { + unknownPayload, err := payload.NewAddressedCall([]byte{0, 0, 0}, []byte("unknown message")) + require.NoError(t, err) + unknownMessage, err := avalancheWarp.NewUnsignedMessage(snowCtx.NetworkID, snowCtx.ChainID, unknownPayload.Bytes()) + require.NoError(t, err) + return unknownMessage.Bytes(), nil + }, + verifyStats: func(t *testing.T, stats *verifierStats) { + require.EqualValues(t, 1, stats.messageParseFail.Snapshot().Count()) + require.EqualValues(t, 0, stats.blockSignatureValidationFail.Snapshot().Count()) + }, + err: &common.AppError{Code: ParseErrCode}, + }, + } + + for name, test := range tests { + for _, withCache := range []bool{true, false} { + if withCache { + name += "_with_cache" + } else { + name += "_no_cache" + } + t.Run(name, func(t *testing.T) { + var sigCache cache.Cacher[ids.ID, []byte] + if withCache { + sigCache = &cache.LRU[ids.ID, []byte]{Size: 100} + } else { + sigCache = &cache.Empty[ids.ID, []byte]{} + } + warpBackend, err := NewBackend(snowCtx.NetworkID, snowCtx.ChainID, warpSigner, warptest.EmptyBlockClient, database, sigCache, [][]byte{offchainMessage.Bytes()}) + require.NoError(t, err) + handler := acp118.NewCachedHandler(sigCache, warpBackend, warpSigner) + + requestBytes, expectedResponse := test.setup(warpBackend) + protoMsg := &sdk.SignatureRequest{Message: requestBytes} + protoBytes, err := proto.Marshal(protoMsg) + require.NoError(t, err) + responseBytes, appErr := handler.AppRequest(context.Background(), ids.GenerateTestNodeID(), time.Time{}, protoBytes) + if test.err != nil { + require.Error(t, appErr) + require.ErrorIs(t, appErr, test.err) + } else { + require.Nil(t, appErr) + } + + test.verifyStats(t, warpBackend.(*backend).stats) + + // If the expected response is empty, assert that the handler returns an empty response and return early. + if len(expectedResponse) == 0 { + require.Len(t, responseBytes, 0, "expected response to be empty") + return + } + // check cache is populated + if withCache { + require.NotZero(t, warpBackend.(*backend).signatureCache.Len()) + } else { + require.Zero(t, warpBackend.(*backend).signatureCache.Len()) + } + response := &sdk.SignatureResponse{} + require.NoError(t, proto.Unmarshal(responseBytes, response)) + require.NoError(t, err, "error unmarshalling SignatureResponse") + + require.Equal(t, expectedResponse, response.Signature) + }) + } + } +} + +func TestBlockSignatures(t *testing.T) { + database := memdb.New() + snowCtx := utils.TestSnowContext() + blsSecretKey, err := bls.NewSecretKey() + require.NoError(t, err) + + warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) + knownBlkID := ids.GenerateTestID() + blockClient := warptest.MakeBlockClient(knownBlkID) + + toMessageBytes := func(id ids.ID) []byte { + idPayload, err := payload.NewHash(id) + if err != nil { + panic(err) + } + + msg, err := avalancheWarp.NewUnsignedMessage(snowCtx.NetworkID, snowCtx.ChainID, idPayload.Bytes()) + if err != nil { + panic(err) + } + + return msg.Bytes() + } + + tests := map[string]struct { + setup func() (request []byte, expectedResponse []byte) + verifyStats func(t *testing.T, stats *verifierStats) + err error + }{ + "known block": { + setup: func() (request []byte, expectedResponse []byte) { + hashPayload, err := payload.NewHash(knownBlkID) + require.NoError(t, err) + unsignedMessage, err := avalancheWarp.NewUnsignedMessage(snowCtx.NetworkID, snowCtx.ChainID, hashPayload.Bytes()) + require.NoError(t, err) + signature, err := warpSigner.Sign(unsignedMessage) + require.NoError(t, err) + return toMessageBytes(knownBlkID), signature[:] + }, + verifyStats: func(t *testing.T, stats *verifierStats) { + require.EqualValues(t, 0, stats.blockSignatureValidationFail.Snapshot().Count()) + require.EqualValues(t, 0, stats.messageParseFail.Snapshot().Count()) + }, + }, + "unknown block": { + setup: func() (request []byte, expectedResponse []byte) { + unknownBlockID := ids.GenerateTestID() + return toMessageBytes(unknownBlockID), nil + }, + verifyStats: func(t *testing.T, stats *verifierStats) { + require.EqualValues(t, 1, stats.blockSignatureValidationFail.Snapshot().Count()) + require.EqualValues(t, 0, stats.messageParseFail.Snapshot().Count()) + }, + err: &common.AppError{Code: VerifyErrCode}, + }, + } + + for name, test := range tests { + for _, withCache := range []bool{true, false} { + if withCache { + name += "_with_cache" + } else { + name += "_no_cache" + } + t.Run(name, func(t *testing.T) { + var sigCache cache.Cacher[ids.ID, []byte] + if withCache { + sigCache = &cache.LRU[ids.ID, []byte]{Size: 100} + } else { + sigCache = &cache.Empty[ids.ID, []byte]{} + } + warpBackend, err := NewBackend( + snowCtx.NetworkID, + snowCtx.ChainID, + warpSigner, + blockClient, + database, + sigCache, + nil, + ) + require.NoError(t, err) + handler := acp118.NewCachedHandler(sigCache, warpBackend, warpSigner) + + requestBytes, expectedResponse := test.setup() + protoMsg := &sdk.SignatureRequest{Message: requestBytes} + protoBytes, err := proto.Marshal(protoMsg) + require.NoError(t, err) + responseBytes, appErr := handler.AppRequest(context.Background(), ids.GenerateTestNodeID(), time.Time{}, protoBytes) + if test.err != nil { + require.NotNil(t, appErr) + require.ErrorIs(t, test.err, appErr) + } else { + require.Nil(t, appErr) + } + + test.verifyStats(t, warpBackend.(*backend).stats) + + // If the expected response is empty, assert that the handler returns an empty response and return early. + if len(expectedResponse) == 0 { + require.Len(t, responseBytes, 0, "expected response to be empty") + return + } + // check cache is populated + if withCache { + require.NotZero(t, warpBackend.(*backend).signatureCache.Len()) + } else { + require.Zero(t, warpBackend.(*backend).signatureCache.Len()) + } + var response sdk.SignatureResponse + err = proto.Unmarshal(responseBytes, &response) + require.NoError(t, err, "error unmarshalling SignatureResponse") + require.Equal(t, expectedResponse, response.Signature) + }) + } + } +} diff --git a/warp/verifier_stats.go b/warp/verifier_stats.go new file mode 100644 index 0000000000..3ee90312d9 --- /dev/null +++ b/warp/verifier_stats.go @@ -0,0 +1,29 @@ +// (c) 2023, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package warp + +import ( + "github.com/ava-labs/coreth/metrics" +) + +type verifierStats struct { + messageParseFail metrics.Counter + // BlockRequest metrics + blockSignatureValidationFail metrics.Counter +} + +func newVerifierStats() *verifierStats { + return &verifierStats{ + messageParseFail: metrics.NewRegisteredCounter("message_parse_fail", nil), + blockSignatureValidationFail: metrics.NewRegisteredCounter("block_signature_validation_fail", nil), + } +} + +func (h *verifierStats) IncBlockSignatureValidationFail() { + h.blockSignatureValidationFail.Inc(1) +} + +func (h *verifierStats) IncMessageParseFail() { + h.messageParseFail.Inc(1) +} From c06af9bb10be60babe9ecbdc2d0582cef68f40bc Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Sat, 16 Nov 2024 00:01:15 +0300 Subject: [PATCH 04/69] bump avago to v1.11.13-rc.0 (#688) --- go.mod | 2 +- go.sum | 4 ++-- scripts/versions.sh | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 8bb078c376..97ac0c6033 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.22.8 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.12.0-initial-poc.9 + github.com/ava-labs/avalanchego v1.11.13-rc.0 github.com/cespare/cp v0.1.0 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 diff --git a/go.sum b/go.sum index 644f445ac7..88d27d9e50 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,8 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/avalanchego v1.12.0-initial-poc.9 h1:dQhb+KlPoud+AkRV3A0suKCTodlUSzflGcZElESeVKo= -github.com/ava-labs/avalanchego v1.12.0-initial-poc.9/go.mod h1:86tO6F1FT8emclUwdQ2WCwAtAerqjm5A4IbV6XxNUyM= +github.com/ava-labs/avalanchego v1.11.13-rc.0 h1:yxhZbLlZ+29wR6W29rz0QryZxk35iyMNr1IhX9NPFCU= +github.com/ava-labs/avalanchego v1.11.13-rc.0/go.mod h1:86tO6F1FT8emclUwdQ2WCwAtAerqjm5A4IbV6XxNUyM= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/scripts/versions.sh b/scripts/versions.sh index 7072589cb1..225b0592d4 100644 --- a/scripts/versions.sh +++ b/scripts/versions.sh @@ -6,4 +6,4 @@ set -euo pipefail # Don't export them as they're used in the context of other calls -AVALANCHE_VERSION=${AVALANCHE_VERSION:-'v1.12.0-initial-poc.9'} +AVALANCHE_VERSION=${AVALANCHE_VERSION:-'v1.11.13-rc.0'} From e73e655356b7df05193e50d5aa56866b3be68e04 Mon Sep 17 00:00:00 2001 From: Richard Pringle Date: Wed, 4 Dec 2024 18:26:41 -0500 Subject: [PATCH 05/69] Encapsulate Signer (#693) * Remove the bls dependency --------- Co-authored-by: Darioush Jalali --- go.mod | 2 +- go.sum | 4 +-- plugin/evm/vm_test.go | 4 +-- plugin/evm/vm_warp_test.go | 20 ++++++------ precompile/contracts/warp/predicate_test.go | 10 +++--- .../warp/signature_verification_test.go | 32 +++++++++---------- scripts/versions.sh | 2 +- utils/snow.go | 4 +-- warp/aggregator/aggregator_test.go | 16 +++++----- warp/backend_test.go | 10 +++--- warp/handlers/signature_request_test.go | 4 +-- warp/verifier_backend_test.go | 4 +-- 12 files changed, 56 insertions(+), 56 deletions(-) diff --git a/go.mod b/go.mod index 97ac0c6033..a3f0c501c5 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.22.8 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.11.13-rc.0 + github.com/ava-labs/avalanchego v1.12.0-initial-poc.9.0.20241129153017-3f46a5a4a084 github.com/cespare/cp v0.1.0 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 diff --git a/go.sum b/go.sum index 88d27d9e50..4ccdf04f33 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,8 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/avalanchego v1.11.13-rc.0 h1:yxhZbLlZ+29wR6W29rz0QryZxk35iyMNr1IhX9NPFCU= -github.com/ava-labs/avalanchego v1.11.13-rc.0/go.mod h1:86tO6F1FT8emclUwdQ2WCwAtAerqjm5A4IbV6XxNUyM= +github.com/ava-labs/avalanchego v1.12.0-initial-poc.9.0.20241129153017-3f46a5a4a084 h1:sZcRy4DXLquvwj/GBr9jE4NkQN3Vy+UK1eENbefxQ0w= +github.com/ava-labs/avalanchego v1.12.0-initial-poc.9.0.20241129153017-3f46a5a4a084/go.mod h1:8f6zzG+5CDDw8+Lxkz5ODe94I8ZH8kT4BTroCNtTATo= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 3d60b23356..94b9cd2ead 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -228,12 +228,12 @@ func NewContext() *snow.Context { return subnetID, nil }, } - blsSecretKey, err := bls.NewSecretKey() + blsSecretKey, err := bls.NewSigner() if err != nil { panic(err) } ctx.WarpSigner = avalancheWarp.NewSigner(blsSecretKey, ctx.NetworkID, ctx.ChainID) - ctx.PublicKey = bls.PublicFromSecretKey(blsSecretKey) + ctx.PublicKey = blsSecretKey.PublicKey() return ctx } diff --git a/plugin/evm/vm_warp_test.go b/plugin/evm/vm_warp_test.go index 7893588ac2..e44f5ba606 100644 --- a/plugin/evm/vm_warp_test.go +++ b/plugin/evm/vm_warp_test.go @@ -265,16 +265,16 @@ func testWarpVMTransaction(t *testing.T, unsignedMessage *avalancheWarp.Unsigned defer logsSub.Unsubscribe() nodeID1 := ids.GenerateTestNodeID() - blsSecretKey1, err := bls.NewSecretKey() + blsSecretKey1, err := bls.NewSigner() require.NoError(err) - blsPublicKey1 := bls.PublicFromSecretKey(blsSecretKey1) - blsSignature1 := bls.Sign(blsSecretKey1, unsignedMessage.Bytes()) + blsPublicKey1 := blsSecretKey1.PublicKey() + blsSignature1 := blsSecretKey1.Sign(unsignedMessage.Bytes()) nodeID2 := ids.GenerateTestNodeID() - blsSecretKey2, err := bls.NewSecretKey() + blsSecretKey2, err := bls.NewSigner() require.NoError(err) - blsPublicKey2 := bls.PublicFromSecretKey(blsSecretKey2) - blsSignature2 := bls.Sign(blsSecretKey2, unsignedMessage.Bytes()) + blsPublicKey2 := blsSecretKey2.PublicKey() + blsSignature2 := blsSecretKey2.Sign(unsignedMessage.Bytes()) blsAggregatedSignature, err := bls.AggregateSignatures([]*bls.Signature{blsSignature1, blsSignature2}) require.NoError(err) @@ -523,18 +523,18 @@ func testReceiveWarpMessage( type signer struct { networkID ids.ID nodeID ids.NodeID - secret *bls.SecretKey + secret bls.Signer signature *bls.Signature weight uint64 } newSigner := func(networkID ids.ID, weight uint64) signer { - secret, err := bls.NewSecretKey() + secret, err := bls.NewSigner() require.NoError(err) return signer{ networkID: networkID, nodeID: ids.GenerateTestNodeID(), secret: secret, - signature: bls.Sign(secret, unsignedMessage.Bytes()), + signature: secret.Sign(unsignedMessage.Bytes()), weight: weight, } } @@ -582,7 +582,7 @@ func testReceiveWarpMessage( for _, s := range signers { vdrOutput[s.nodeID] = &validators.GetValidatorOutput{ NodeID: s.nodeID, - PublicKey: bls.PublicFromSecretKey(s.secret), + PublicKey: s.secret.PublicKey(), Weight: s.weight, } } diff --git a/precompile/contracts/warp/predicate_test.go b/precompile/contracts/warp/predicate_test.go index 04ddd46705..a5fe8265b7 100644 --- a/precompile/contracts/warp/predicate_test.go +++ b/precompile/contracts/warp/predicate_test.go @@ -93,7 +93,7 @@ func init() { } for _, testVdr := range testVdrs { - blsSignature := bls.Sign(testVdr.sk, unsignedMsg.Bytes()) + blsSignature := testVdr.sk.Sign(unsignedMsg.Bytes()) blsSignatures = append(blsSignatures, blsSignature) } @@ -102,7 +102,7 @@ func init() { type testValidator struct { nodeID ids.NodeID - sk *bls.SecretKey + sk bls.Signer vdr *avalancheWarp.Validator } @@ -111,13 +111,13 @@ func (v *testValidator) Compare(o *testValidator) int { } func newTestValidator() *testValidator { - sk, err := bls.NewSecretKey() + sk, err := bls.NewSigner() if err != nil { panic(err) } nodeID := ids.GenerateTestNodeID() - pk := bls.PublicFromSecretKey(sk) + pk := sk.PublicKey() return &testValidator{ nodeID: nodeID, sk: sk, @@ -240,7 +240,7 @@ func testWarpMessageFromPrimaryNetwork(t *testing.T, requirePrimaryNetworkSigner PublicKey: testVdrs[i].vdr.PublicKey, } getValidatorsOutput[testVdrs[i].nodeID] = validatorOutput - blsSignatures = append(blsSignatures, bls.Sign(testVdrs[i].sk, unsignedMsg.Bytes())) + blsSignatures = append(blsSignatures, testVdrs[i].sk.Sign(unsignedMsg.Bytes())) } aggregateSignature, err := bls.AggregateSignatures(blsSignatures) require.NoError(err) diff --git a/precompile/contracts/warp/signature_verification_test.go b/precompile/contracts/warp/signature_verification_test.go index 5b54cd29b8..d52f0a0f89 100644 --- a/precompile/contracts/warp/signature_verification_test.go +++ b/precompile/contracts/warp/signature_verification_test.go @@ -212,8 +212,8 @@ func TestSignatureVerification(t *testing.T) { signers.Add(1) unsignedBytes := unsignedMsg.Bytes() - vdr0Sig := bls.Sign(testVdrs[0].sk, unsignedBytes) - vdr1Sig := bls.Sign(testVdrs[1].sk, unsignedBytes) + vdr0Sig := testVdrs[0].sk.Sign(unsignedBytes) + vdr1Sig := testVdrs[1].sk.Sign(unsignedBytes) aggSig, err := bls.AggregateSignatures([]*bls.Signature{vdr0Sig, vdr1Sig}) require.NoError(err) aggSigBytes := [bls.SignatureLen]byte{} @@ -284,7 +284,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) unsignedBytes := unsignedMsg.Bytes() - vdr0Sig := bls.Sign(testVdrs[0].sk, unsignedBytes) + vdr0Sig := testVdrs[0].sk.Sign(unsignedBytes) aggSigBytes := [bls.SignatureLen]byte{} copy(aggSigBytes[:], bls.SignatureToBytes(vdr0Sig)) @@ -323,10 +323,10 @@ func TestSignatureVerification(t *testing.T) { signers.Add(1) unsignedBytes := unsignedMsg.Bytes() - vdr0Sig := bls.Sign(testVdrs[0].sk, unsignedBytes) + vdr0Sig := testVdrs[0].sk.Sign(unsignedBytes) // Give sig from vdr[2] even though the bit vector says it // should be from vdr[1] - vdr2Sig := bls.Sign(testVdrs[2].sk, unsignedBytes) + vdr2Sig := testVdrs[2].sk.Sign(unsignedBytes) aggSig, err := bls.AggregateSignatures([]*bls.Signature{vdr0Sig, vdr2Sig}) require.NoError(err) aggSigBytes := [bls.SignatureLen]byte{} @@ -367,7 +367,7 @@ func TestSignatureVerification(t *testing.T) { signers.Add(1) unsignedBytes := unsignedMsg.Bytes() - vdr0Sig := bls.Sign(testVdrs[0].sk, unsignedBytes) + vdr0Sig := testVdrs[0].sk.Sign(unsignedBytes) // Don't give the sig from vdr[1] aggSigBytes := [bls.SignatureLen]byte{} copy(aggSigBytes[:], bls.SignatureToBytes(vdr0Sig)) @@ -407,11 +407,11 @@ func TestSignatureVerification(t *testing.T) { signers.Add(1) unsignedBytes := unsignedMsg.Bytes() - vdr0Sig := bls.Sign(testVdrs[0].sk, unsignedBytes) - vdr1Sig := bls.Sign(testVdrs[1].sk, unsignedBytes) + vdr0Sig := testVdrs[0].sk.Sign(unsignedBytes) + vdr1Sig := testVdrs[1].sk.Sign(unsignedBytes) // Give sig from vdr[2] even though the bit vector doesn't have // it - vdr2Sig := bls.Sign(testVdrs[2].sk, unsignedBytes) + vdr2Sig := testVdrs[2].sk.Sign(unsignedBytes) aggSig, err := bls.AggregateSignatures([]*bls.Signature{vdr0Sig, vdr1Sig, vdr2Sig}) require.NoError(err) aggSigBytes := [bls.SignatureLen]byte{} @@ -454,8 +454,8 @@ func TestSignatureVerification(t *testing.T) { signers.Add(2) unsignedBytes := unsignedMsg.Bytes() - vdr1Sig := bls.Sign(testVdrs[1].sk, unsignedBytes) - vdr2Sig := bls.Sign(testVdrs[2].sk, unsignedBytes) + vdr1Sig := testVdrs[1].sk.Sign(unsignedBytes) + vdr2Sig := testVdrs[2].sk.Sign(unsignedBytes) aggSig, err := bls.AggregateSignatures([]*bls.Signature{vdr1Sig, vdr2Sig}) require.NoError(err) aggSigBytes := [bls.SignatureLen]byte{} @@ -498,8 +498,8 @@ func TestSignatureVerification(t *testing.T) { signers.Add(2) unsignedBytes := unsignedMsg.Bytes() - vdr1Sig := bls.Sign(testVdrs[1].sk, unsignedBytes) - vdr2Sig := bls.Sign(testVdrs[2].sk, unsignedBytes) + vdr1Sig := testVdrs[1].sk.Sign(unsignedBytes) + vdr2Sig := testVdrs[2].sk.Sign(unsignedBytes) aggSig, err := bls.AggregateSignatures([]*bls.Signature{vdr1Sig, vdr2Sig}) require.NoError(err) aggSigBytes := [bls.SignatureLen]byte{} @@ -559,8 +559,8 @@ func TestSignatureVerification(t *testing.T) { signers.Add(1) // vdr[2] unsignedBytes := unsignedMsg.Bytes() - vdr1Sig := bls.Sign(testVdrs[1].sk, unsignedBytes) - vdr2Sig := bls.Sign(testVdrs[2].sk, unsignedBytes) + vdr1Sig := testVdrs[1].sk.Sign(unsignedBytes) + vdr2Sig := testVdrs[2].sk.Sign(unsignedBytes) aggSig, err := bls.AggregateSignatures([]*bls.Signature{vdr1Sig, vdr2Sig}) require.NoError(err) aggSigBytes := [bls.SignatureLen]byte{} @@ -621,7 +621,7 @@ func TestSignatureVerification(t *testing.T) { unsignedBytes := unsignedMsg.Bytes() // Because vdr[1] and vdr[2] share a key, only one of them sign. - vdr2Sig := bls.Sign(testVdrs[2].sk, unsignedBytes) + vdr2Sig := testVdrs[2].sk.Sign(unsignedBytes) aggSigBytes := [bls.SignatureLen]byte{} copy(aggSigBytes[:], bls.SignatureToBytes(vdr2Sig)) diff --git a/scripts/versions.sh b/scripts/versions.sh index 225b0592d4..2f7a86f576 100644 --- a/scripts/versions.sh +++ b/scripts/versions.sh @@ -6,4 +6,4 @@ set -euo pipefail # Don't export them as they're used in the context of other calls -AVALANCHE_VERSION=${AVALANCHE_VERSION:-'v1.11.13-rc.0'} +AVALANCHE_VERSION=${AVALANCHE_VERSION:-'3f46a5a4a084'} diff --git a/utils/snow.go b/utils/snow.go index e46e2ac7b1..36b9b7b7fb 100644 --- a/utils/snow.go +++ b/utils/snow.go @@ -25,11 +25,11 @@ var ( ) func TestSnowContext() *snow.Context { - sk, err := bls.NewSecretKey() + sk, err := bls.NewSigner() if err != nil { panic(err) } - pk := bls.PublicFromSecretKey(sk) + pk := sk.PublicKey() networkID := constants.UnitTestID chainID := testChainID diff --git a/warp/aggregator/aggregator_test.go b/warp/aggregator/aggregator_test.go index a423f75b25..98e90607db 100644 --- a/warp/aggregator/aggregator_test.go +++ b/warp/aggregator/aggregator_test.go @@ -17,10 +17,10 @@ import ( avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" ) -func newValidator(t testing.TB, weight uint64) (*bls.SecretKey, *avalancheWarp.Validator) { - sk, err := bls.NewSecretKey() +func newValidator(t testing.TB, weight uint64) (bls.Signer, *avalancheWarp.Validator) { + sk, err := bls.NewSigner() require.NoError(t, err) - pk := bls.PublicFromSecretKey(sk) + pk := sk.PublicKey() return sk, &avalancheWarp.Validator{ PublicKey: pk, PublicKeyBytes: bls.PublicKeyToCompressedBytes(pk), @@ -43,17 +43,17 @@ func TestAggregateSignatures(t *testing.T) { vdr1sk, vdr1 := newValidator(t, vdrWeight) vdr2sk, vdr2 := newValidator(t, vdrWeight+1) vdr3sk, vdr3 := newValidator(t, vdrWeight-1) - sig1 := bls.Sign(vdr1sk, unsignedMsg.Bytes()) - sig2 := bls.Sign(vdr2sk, unsignedMsg.Bytes()) - sig3 := bls.Sign(vdr3sk, unsignedMsg.Bytes()) + sig1 := vdr1sk.Sign(unsignedMsg.Bytes()) + sig2 := vdr2sk.Sign(unsignedMsg.Bytes()) + sig3 := vdr3sk.Sign(unsignedMsg.Bytes()) vdrToSig := map[*avalancheWarp.Validator]*bls.Signature{ vdr1: sig1, vdr2: sig2, vdr3: sig3, } - nonVdrSk, err := bls.NewSecretKey() + nonVdrSk, err := bls.NewSigner() require.NoError(t, err) - nonVdrSig := bls.Sign(nonVdrSk, unsignedMsg.Bytes()) + nonVdrSig := nonVdrSk.Sign(unsignedMsg.Bytes()) vdrs := []*avalancheWarp.Validator{ { PublicKey: vdr1.PublicKey, diff --git a/warp/backend_test.go b/warp/backend_test.go index 5a0a64a0c2..4935875ece 100644 --- a/warp/backend_test.go +++ b/warp/backend_test.go @@ -40,7 +40,7 @@ func init() { func TestAddAndGetValidMessage(t *testing.T) { db := memdb.New() - sk, err := bls.NewSecretKey() + sk, err := bls.NewSigner() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 500} @@ -63,7 +63,7 @@ func TestAddAndGetValidMessage(t *testing.T) { func TestAddAndGetUnknownMessage(t *testing.T) { db := memdb.New() - sk, err := bls.NewSecretKey() + sk, err := bls.NewSigner() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 500} @@ -82,7 +82,7 @@ func TestGetBlockSignature(t *testing.T) { blockClient := warptest.MakeBlockClient(blkID) db := memdb.New() - sk, err := bls.NewSecretKey() + sk, err := bls.NewSigner() require.NoError(err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 500} @@ -107,7 +107,7 @@ func TestGetBlockSignature(t *testing.T) { func TestZeroSizedCache(t *testing.T) { db := memdb.New() - sk, err := bls.NewSecretKey() + sk, err := bls.NewSigner() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) @@ -135,7 +135,7 @@ func TestOffChainMessages(t *testing.T) { check func(require *require.Assertions, b Backend) err error } - sk, err := bls.NewSecretKey() + sk, err := bls.NewSigner() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) diff --git a/warp/handlers/signature_request_test.go b/warp/handlers/signature_request_test.go index dd2271988b..77a4af087e 100644 --- a/warp/handlers/signature_request_test.go +++ b/warp/handlers/signature_request_test.go @@ -23,7 +23,7 @@ import ( func TestMessageSignatureHandler(t *testing.T) { database := memdb.New() snowCtx := utils.TestSnowContext() - blsSecretKey, err := bls.NewSecretKey() + blsSecretKey, err := bls.NewSigner() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) @@ -127,7 +127,7 @@ func TestMessageSignatureHandler(t *testing.T) { func TestBlockSignatureHandler(t *testing.T) { database := memdb.New() snowCtx := utils.TestSnowContext() - blsSecretKey, err := bls.NewSecretKey() + blsSecretKey, err := bls.NewSigner() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) diff --git a/warp/verifier_backend_test.go b/warp/verifier_backend_test.go index 5ea3a37e0f..4bf11541b0 100644 --- a/warp/verifier_backend_test.go +++ b/warp/verifier_backend_test.go @@ -26,7 +26,7 @@ import ( func TestAddressedCallSignatures(t *testing.T) { database := memdb.New() snowCtx := utils.TestSnowContext() - blsSecretKey, err := bls.NewSecretKey() + blsSecretKey, err := bls.NewSigner() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) @@ -140,7 +140,7 @@ func TestAddressedCallSignatures(t *testing.T) { func TestBlockSignatures(t *testing.T) { database := memdb.New() snowCtx := utils.TestSnowContext() - blsSecretKey, err := bls.NewSecretKey() + blsSecretKey, err := bls.NewSigner() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) From 9d4ce7bf22db6a9e5d37cf26d643753e2d768208 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 10 Dec 2024 10:32:39 -0800 Subject: [PATCH 06/69] Release notes and avalanchego update (#696) * Release notes and avalanchego update * restore avago version * bump avago to master * ammend notes * go mod tidy * bump version * update notes --- RELEASES.md | 8 ++++++++ go.mod | 2 +- go.sum | 4 ++-- plugin/evm/version.go | 2 +- scripts/versions.sh | 2 +- 5 files changed, 13 insertions(+), 5 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index 64a6fb87ee..6a088dac32 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,5 +1,13 @@ # Release Notes +## [v0.14.0](https://github.com/ava-labs/coreth/releases/tag/v0.14.0) +- Minor version update to correspond to avalanchego v1.12.0 / Etna. +- Remove unused historical opcodes CALLEX, BALANCEMC +- Remove unused pre-AP2 handling of genesis contract +- Fix to track tx size in block building +- Test fixes +- Update go version to 1.22 + ## [v0.13.8](https://github.com/ava-labs/coreth/releases/tag/v0.13.8) - Update geth dependency to v1.13.14 - eupgrade: lowering the base fee to 1 nAVAX diff --git a/go.mod b/go.mod index a3f0c501c5..2a6106661b 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.22.8 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.12.0-initial-poc.9.0.20241129153017-3f46a5a4a084 + github.com/ava-labs/avalanchego v1.12.1-0.20241209214115-1dc4192013aa github.com/cespare/cp v0.1.0 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 diff --git a/go.sum b/go.sum index 4ccdf04f33..9ddf41790c 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,8 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/avalanchego v1.12.0-initial-poc.9.0.20241129153017-3f46a5a4a084 h1:sZcRy4DXLquvwj/GBr9jE4NkQN3Vy+UK1eENbefxQ0w= -github.com/ava-labs/avalanchego v1.12.0-initial-poc.9.0.20241129153017-3f46a5a4a084/go.mod h1:8f6zzG+5CDDw8+Lxkz5ODe94I8ZH8kT4BTroCNtTATo= +github.com/ava-labs/avalanchego v1.12.1-0.20241209214115-1dc4192013aa h1:8eSy+tegp9Kq2zft54wk0FyWU87utdrVwsj9EBIb/NA= +github.com/ava-labs/avalanchego v1.12.1-0.20241209214115-1dc4192013aa/go.mod h1:256D2s2FIKo07uUeY25uDXFuqBo6TeWIJqeEA+Xchwk= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/plugin/evm/version.go b/plugin/evm/version.go index 6151bbbe8e..b4772b640e 100644 --- a/plugin/evm/version.go +++ b/plugin/evm/version.go @@ -11,7 +11,7 @@ var ( // GitCommit is set by the build script GitCommit string // Version is the version of Coreth - Version string = "v0.13.9" + Version string = "v0.14.0" ) func init() { diff --git a/scripts/versions.sh b/scripts/versions.sh index 2f7a86f576..33282d011a 100644 --- a/scripts/versions.sh +++ b/scripts/versions.sh @@ -6,4 +6,4 @@ set -euo pipefail # Don't export them as they're used in the context of other calls -AVALANCHE_VERSION=${AVALANCHE_VERSION:-'3f46a5a4a084'} +AVALANCHE_VERSION=${AVALANCHE_VERSION:-'1dc4192013aa'} From 7a90507f3cbebfe85a65b4b26cf5383a87e951f3 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Thu, 12 Dec 2024 09:16:07 -0800 Subject: [PATCH 07/69] prepare release cycle v0.14.1 (#698) --- RELEASES.md | 3 +++ plugin/evm/version.go | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/RELEASES.md b/RELEASES.md index 6a088dac32..bbe2c02a09 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,5 +1,8 @@ # Release Notes +## [v0.14.1](https://github.com/ava-labs/coreth/releases/tag/v0.14.1) +- TBD + ## [v0.14.0](https://github.com/ava-labs/coreth/releases/tag/v0.14.0) - Minor version update to correspond to avalanchego v1.12.0 / Etna. - Remove unused historical opcodes CALLEX, BALANCEMC diff --git a/plugin/evm/version.go b/plugin/evm/version.go index b4772b640e..e4b93c457e 100644 --- a/plugin/evm/version.go +++ b/plugin/evm/version.go @@ -11,7 +11,7 @@ var ( // GitCommit is set by the build script GitCommit string // Version is the version of Coreth - Version string = "v0.14.0" + Version string = "v0.14.1" ) func init() { From 340fe936267710654fc2a21500dd4aa0228269f1 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Mon, 23 Dec 2024 07:04:49 -0800 Subject: [PATCH 08/69] Remove eth_getAssetBalance API (#715) --- RELEASES.md | 2 +- ethclient/ethclient.go | 10 ---------- internal/ethapi/api.go | 12 ------------ 3 files changed, 1 insertion(+), 23 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index bbe2c02a09..b977d63812 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,7 +1,7 @@ # Release Notes ## [v0.14.1](https://github.com/ava-labs/coreth/releases/tag/v0.14.1) -- TBD +- Remove API eth_getAssetBalance that was used to query ANT balances (deprecated since v0.10.0) ## [v0.14.0](https://github.com/ava-labs/coreth/releases/tag/v0.14.0) - Minor version update to correspond to avalanchego v1.12.0 / Etna. diff --git a/ethclient/ethclient.go b/ethclient/ethclient.go index 5861210aca..422cf37fcb 100644 --- a/ethclient/ethclient.go +++ b/ethclient/ethclient.go @@ -34,7 +34,6 @@ import ( "fmt" "math/big" - "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/interfaces" @@ -90,7 +89,6 @@ type Client interface { SubscribeNewHead(context.Context, chan<- *types.Header) (interfaces.Subscription, error) NetworkID(context.Context) (*big.Int, error) BalanceAt(context.Context, common.Address, *big.Int) (*big.Int, error) - AssetBalanceAt(context.Context, common.Address, ids.ID, *big.Int) (*big.Int, error) BalanceAtHash(ctx context.Context, account common.Address, blockHash common.Hash) (*big.Int, error) StorageAt(context.Context, common.Address, common.Hash, *big.Int) ([]byte, error) StorageAtHash(ctx context.Context, account common.Address, key common.Hash, blockHash common.Hash) ([]byte, error) @@ -467,14 +465,6 @@ func (ec *client) BalanceAt(ctx context.Context, account common.Address, blockNu return (*big.Int)(&result), err } -// AssetBalanceAt returns the [assetID] balance of the given account -// The block number can be nil, in which case the balance is taken from the latest known block. -func (ec *client) AssetBalanceAt(ctx context.Context, account common.Address, assetID ids.ID, blockNumber *big.Int) (*big.Int, error) { - var result hexutil.Big - err := ec.c.CallContext(ctx, &result, "eth_getAssetBalance", account, ToBlockNumArg(blockNumber), assetID) - return (*big.Int)(&result), err -} - // BalanceAtHash returns the wei balance of the given account. func (ec *client) BalanceAtHash(ctx context.Context, account common.Address, blockHash common.Hash) (*big.Int, error) { var result hexutil.Big diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 3b72aeae33..93aadbe14c 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -35,7 +35,6 @@ import ( "strings" "time" - "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/coreth/accounts" "github.com/ava-labs/coreth/accounts/keystore" "github.com/ava-labs/coreth/accounts/scwallet" @@ -646,17 +645,6 @@ func (s *BlockChainAPI) GetBalance(ctx context.Context, address common.Address, return (*hexutil.Big)(b), state.Error() } -// GetAssetBalance returns the amount of [assetID] for the given address in the state of the -// given block number. The rpc.LatestBlockNumber, rpc.PendingBlockNumber, and -// rpc.AcceptedBlockNumber meta block numbers are also allowed. -func (s *BlockChainAPI) GetAssetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash, assetID ids.ID) (*hexutil.Big, error) { - state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) - if state == nil || err != nil { - return nil, err - } - return (*hexutil.Big)(state.GetBalanceMultiCoin(address, common.Hash(assetID))), state.Error() -} - // AccountResult structs for GetProof type AccountResult struct { Address common.Address `json:"address"` From 6b4dbb4b2298a7c34332292e701bb1a986deb918 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Thu, 26 Dec 2024 04:15:15 -0800 Subject: [PATCH 09/69] Simplify txpool min base fee code (post etna cleanup) (#717) --- plugin/evm/vm.go | 31 +------------------------------ plugin/evm/vm_test.go | 28 ---------------------------- 2 files changed, 1 insertion(+), 58 deletions(-) diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 50606b0af7..60b6ab240b 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -727,41 +727,12 @@ func (vm *VM) initializeChain(lastAcceptedHash common.Hash) error { // Set the gas parameters for the tx pool to the minimum gas price for the // latest upgrade. vm.txPool.SetGasTip(big.NewInt(0)) - vm.setMinFeeAtEtna() + vm.txPool.SetMinFee(big.NewInt(params.EtnaMinBaseFee)) vm.eth.Start() return vm.initChainState(vm.blockChain.LastAcceptedBlock()) } -// TODO: remove this after Etna is activated -func (vm *VM) setMinFeeAtEtna() { - now := vm.clock.Time() - if vm.chainConfig.EtnaTimestamp == nil { - // If Etna is not set, set the min fee according to the latest upgrade - vm.txPool.SetMinFee(big.NewInt(params.ApricotPhase4MinBaseFee)) - return - } else if vm.chainConfig.IsEtna(uint64(now.Unix())) { - // If Etna is activated, set the min fee to the Etna min fee - vm.txPool.SetMinFee(big.NewInt(params.EtnaMinBaseFee)) - return - } - - vm.txPool.SetMinFee(big.NewInt(params.ApricotPhase4MinBaseFee)) - vm.shutdownWg.Add(1) - go func() { - defer vm.shutdownWg.Done() - - wait := utils.Uint64ToTime(vm.chainConfig.EtnaTimestamp).Sub(now) - t := time.NewTimer(wait) - select { - case <-t.C: // Wait for Etna to be activated - vm.txPool.SetMinFee(big.NewInt(params.EtnaMinBaseFee)) - case <-vm.shutdownChan: - } - t.Stop() - }() -} - // initializeStateSyncClient initializes the client for performing state sync. // If state sync is disabled, this function will wipe any ongoing summary from // disk to ensure that we do not continue syncing from an invalid snapshot. diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 94b9cd2ead..8fcb1961cd 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -115,12 +115,6 @@ var ( return &cpy } - activateEtna = func(cfg *params.ChainConfig, etnaTime uint64) *params.ChainConfig { - cpy := *cfg - cpy.EtnaTimestamp = &etnaTime - return &cpy - } - genesisJSONApricotPhase0 = genesisJSON(params.TestLaunchConfig) genesisJSONApricotPhase1 = genesisJSON(params.TestApricotPhase1Config) genesisJSONApricotPhase2 = genesisJSON(params.TestApricotPhase2Config) @@ -3987,25 +3981,3 @@ func TestNoBlobsAllowed(t *testing.T) { err = vmBlock.Verify(ctx) require.ErrorContains(err, "blobs not enabled on avalanche networks") } - -func TestMinFeeSetAtEtna(t *testing.T) { - require := require.New(t) - now := time.Now() - etnaTime := uint64(now.Add(1 * time.Second).Unix()) - - genesis := genesisJSON( - activateEtna(params.TestEtnaChainConfig, etnaTime), - ) - clock := mockable.Clock{} - clock.Set(now) - - _, vm, _, _, _ := GenesisVMWithClock(t, false, genesis, "", "", clock) - initial := vm.txPool.MinFee() - require.Equal(params.ApricotPhase4MinBaseFee, initial.Int64()) - - require.Eventually( - func() bool { return params.EtnaMinBaseFee == vm.txPool.MinFee().Int64() }, - 5*time.Second, - 1*time.Second, - ) -} From 1732ff5fd6f31c3a64832d0880d4e611b04eb694 Mon Sep 17 00:00:00 2001 From: cuiweiyuan Date: Fri, 27 Dec 2024 00:34:03 +0800 Subject: [PATCH 10/69] chore: fix function name in comment (#718) Co-authored-by: Darioush Jalali --- rpc/handler.go | 2 +- sync/statesync/state_syncer.go | 2 +- triedb/pathdb/database_test.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/rpc/handler.go b/rpc/handler.go index adffe5cbad..a15f6b20be 100644 --- a/rpc/handler.go +++ b/rpc/handler.go @@ -356,7 +356,7 @@ func (h *handler) addRequestOp(op *requestOp) { } } -// removeRequestOps stops waiting for the given request IDs. +// removeRequestOp stops waiting for the given request IDs. func (h *handler) removeRequestOp(op *requestOp) { for _, id := range op.ids { delete(h.respWait, string(id)) diff --git a/sync/statesync/state_syncer.go b/sync/statesync/state_syncer.go index 305b981b8f..ec8b138863 100644 --- a/sync/statesync/state_syncer.go +++ b/sync/statesync/state_syncer.go @@ -132,7 +132,7 @@ func (t *stateSync) onStorageTrieFinished(root common.Hash) error { return nil } -// onMainTrieFinishes is called after the main trie finishes syncing. +// onMainTrieFinished is called after the main trie finishes syncing. func (t *stateSync) onMainTrieFinished() error { t.codeSyncer.notifyAccountTrieCompleted() diff --git a/triedb/pathdb/database_test.go b/triedb/pathdb/database_test.go index ed7d237480..d7d15afea0 100644 --- a/triedb/pathdb/database_test.go +++ b/triedb/pathdb/database_test.go @@ -315,7 +315,7 @@ func (t *tester) generate(parent common.Hash) (common.Hash, *trienode.MergedNode return root, ctx.nodes, triestate.New(ctx.accountOrigin, ctx.storageOrigin, nil) } -// lastRoot returns the latest root hash, or empty if nothing is cached. +// lastHash returns the latest root hash, or empty if nothing is cached. func (t *tester) lastHash() common.Hash { if len(t.roots) == 0 { return common.Hash{} From 1df5f451ba245bc15e6bd99bf9fdbdfdb0a272ea Mon Sep 17 00:00:00 2001 From: Quentin McGaw Date: Fri, 27 Dec 2024 13:42:19 +0100 Subject: [PATCH 11/69] chore(ci): remove `check-latest: true` to ensure the specified Go version is used (#722) --- .github/workflows/ci.yml | 3 --- .github/workflows/sync-subnet-evm-branch.yml | 1 - 2 files changed, 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7bf047ead..553c2761d7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,7 +32,6 @@ jobs: - uses: actions/setup-go@v5 with: go-version: "~1.22.8" - check-latest: true - name: change avalanchego dep if: ${{ github.event_name == 'workflow_dispatch' }} run: | @@ -74,7 +73,6 @@ jobs: - uses: actions/setup-go@v5 with: go-version: "~1.22.8" - check-latest: true - name: change avalanchego dep if: ${{ github.event_name == 'workflow_dispatch' }} run: | @@ -113,7 +111,6 @@ jobs: - uses: actions/setup-go@v5 with: go-version: "~1.22.8" - check-latest: true - name: Run e2e tests run: E2E_SERIAL=1 ./scripts/tests.e2e.sh shell: bash diff --git a/.github/workflows/sync-subnet-evm-branch.yml b/.github/workflows/sync-subnet-evm-branch.yml index 97e8554ef8..e053aec587 100644 --- a/.github/workflows/sync-subnet-evm-branch.yml +++ b/.github/workflows/sync-subnet-evm-branch.yml @@ -17,4 +17,3 @@ jobs: - uses: actions/setup-go@v5 with: go-version: "~1.22.8" - check-latest: true From 90ce3413978f51a1332b2f5584d1e225ebbfa3ca Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Mon, 30 Dec 2024 22:01:22 +0300 Subject: [PATCH 12/69] fix test generator (#724) --- triedb/pathdb/database_test.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/triedb/pathdb/database_test.go b/triedb/pathdb/database_test.go index d7d15afea0..477cc86625 100644 --- a/triedb/pathdb/database_test.go +++ b/triedb/pathdb/database_test.go @@ -228,7 +228,11 @@ func (t *tester) generate(parent common.Hash) (common.Hash, *trienode.MergedNode dirties = make(map[common.Hash]struct{}) ) for i := 0; i < 20; i++ { - switch rand.Intn(opLen) { + op := createAccountOp + if i > 0 { + op = rand.Intn(opLen) + } + switch op { case createAccountOp: // account creation addr := testutil.RandomAddress() From 351149733d351723d007963c96bb00916eec582a Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Mon, 30 Dec 2024 22:12:23 +0300 Subject: [PATCH 13/69] new atomic pkg (#699) * new atomic pkg * bump avago * bump versions * change newimport clk to time * move utils * bump avago * go mod tidy * use address methods from avago * bump avago * bump e2e avago version --- go.mod | 12 +- go.sum | 26 +- plugin/evm/admin.go | 7 +- plugin/evm/{ => atomic}/codec.go | 15 +- plugin/evm/{ => atomic}/export_tx.go | 245 +++++++++--- plugin/evm/{ => atomic}/import_tx.go | 165 ++++---- plugin/evm/{ => atomic}/metadata.go | 2 +- plugin/evm/{ => atomic}/status.go | 6 +- plugin/evm/{ => atomic}/tx.go | 119 +++--- plugin/evm/atomic_backend.go | 51 ++- plugin/evm/atomic_state.go | 13 +- plugin/evm/atomic_trie.go | 11 +- plugin/evm/atomic_trie_test.go | 53 +-- plugin/evm/atomic_tx_repository.go | 41 +- plugin/evm/atomic_tx_repository_test.go | 25 +- plugin/evm/block.go | 11 +- plugin/evm/{ => client}/client.go | 92 ++++- .../evm/{ => client}/client_interface_test.go | 2 +- plugin/evm/client/utils.go | 13 + plugin/evm/export_tx_test.go | 365 ++++++++++-------- plugin/evm/formatting.go | 21 - plugin/evm/gossip.go | 9 +- plugin/evm/gossip_test.go | 11 +- plugin/evm/handler.go | 7 +- plugin/evm/import_tx_test.go | 259 ++++++------- plugin/evm/mempool.go | 57 +-- plugin/evm/mempool_atomic_gossiping_test.go | 3 +- plugin/evm/mempool_test.go | 5 +- plugin/evm/service.go | 104 +---- plugin/evm/syncervm_test.go | 17 +- plugin/evm/test_tx.go | 44 +-- plugin/evm/tx_gossip_test.go | 33 +- plugin/evm/tx_heap.go | 17 +- plugin/evm/tx_heap_test.go | 13 +- plugin/evm/tx_test.go | 57 +-- plugin/evm/user.go | 7 +- plugin/evm/vm.go | 349 +++++------------ plugin/evm/vm_test.go | 119 +++--- scripts/versions.sh | 2 +- 39 files changed, 1271 insertions(+), 1137 deletions(-) rename plugin/evm/{ => atomic}/codec.go (91%) rename plugin/evm/{ => atomic}/export_tx.go (57%) rename plugin/evm/{ => atomic}/import_tx.go (70%) rename plugin/evm/{ => atomic}/metadata.go (98%) rename plugin/evm/{ => atomic}/status.go (95%) rename plugin/evm/{ => atomic}/tx.go (75%) rename plugin/evm/{ => client}/client.go (78%) rename plugin/evm/{ => client}/client_interface_test.go (97%) create mode 100644 plugin/evm/client/utils.go diff --git a/go.mod b/go.mod index 2a6106661b..5d184fd9e5 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.22.8 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.12.1-0.20241209214115-1dc4192013aa + github.com/ava-labs/avalanchego v1.12.2-0.20241224181600-fade5be3051d github.com/cespare/cp v0.1.0 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 @@ -38,11 +38,11 @@ require ( github.com/urfave/cli/v2 v2.25.7 go.uber.org/goleak v1.3.0 go.uber.org/mock v0.4.0 - golang.org/x/crypto v0.26.0 + golang.org/x/crypto v0.31.0 golang.org/x/exp v0.0.0-20231127185646-65229373498e - golang.org/x/sync v0.8.0 - golang.org/x/sys v0.24.0 - golang.org/x/text v0.17.0 + golang.org/x/sync v0.10.0 + golang.org/x/sys v0.28.0 + golang.org/x/text v0.21.0 golang.org/x/time v0.3.0 google.golang.org/protobuf v1.34.2 gopkg.in/natefinch/lumberjack.v2 v2.0.0 @@ -121,7 +121,7 @@ require ( go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.26.0 // indirect golang.org/x/net v0.28.0 // indirect - golang.org/x/term v0.23.0 // indirect + golang.org/x/term v0.27.0 // indirect gonum.org/v1/gonum v0.11.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20240604185151-ef581f913117 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240827150818-7e3bb234dfed // indirect diff --git a/go.sum b/go.sum index 9ddf41790c..40a7c0d3cf 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,10 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/avalanchego v1.12.1-0.20241209214115-1dc4192013aa h1:8eSy+tegp9Kq2zft54wk0FyWU87utdrVwsj9EBIb/NA= -github.com/ava-labs/avalanchego v1.12.1-0.20241209214115-1dc4192013aa/go.mod h1:256D2s2FIKo07uUeY25uDXFuqBo6TeWIJqeEA+Xchwk= +github.com/ava-labs/avalanchego v1.12.2-0.20241224161435-3998475d671d h1:QCtjS4ANcNfCdL6Z2sKpanDVJNt1MU0bUyVdW0g5zuU= +github.com/ava-labs/avalanchego v1.12.2-0.20241224161435-3998475d671d/go.mod h1:cDoT0Hq3P+/XfCyVvzrBj66yoid2I5LnMuj7LIkap+o= +github.com/ava-labs/avalanchego v1.12.2-0.20241224181600-fade5be3051d h1:iPlsqC9pIy4emCo8wyI/VmVmfljpzmw58ZqahVdcehI= +github.com/ava-labs/avalanchego v1.12.2-0.20241224181600-fade5be3051d/go.mod h1:dKawab3nXqwI7ZcOFatTOv//l1V0t8MRBnhXoOqbN4E= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= @@ -601,8 +603,8 @@ golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw= -golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54= +golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= +golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -708,8 +710,8 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= -golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -776,12 +778,12 @@ golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= -golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.23.0 h1:F6D4vR+EHoL9/sWAWgAR1H2DcHr4PareCbAaCo1RpuU= -golang.org/x/term v0.23.0/go.mod h1:DgV24QBUrK6jhZXl+20l6UWznPlwAHm1Q1mGHtydmSk= +golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= +golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -792,8 +794,8 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= -golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= -golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= diff --git a/plugin/evm/admin.go b/plugin/evm/admin.go index fd8d7f8d6e..e90be473a7 100644 --- a/plugin/evm/admin.go +++ b/plugin/evm/admin.go @@ -9,6 +9,7 @@ import ( "github.com/ava-labs/avalanchego/api" "github.com/ava-labs/avalanchego/utils/profiler" + "github.com/ava-labs/coreth/plugin/evm/client" "github.com/ethereum/go-ethereum/log" ) @@ -65,11 +66,7 @@ func (p *Admin) LockProfile(_ *http.Request, _ *struct{}, _ *api.EmptyReply) err return p.profiler.LockProfile() } -type SetLogLevelArgs struct { - Level string `json:"level"` -} - -func (p *Admin) SetLogLevel(_ *http.Request, args *SetLogLevelArgs, reply *api.EmptyReply) error { +func (p *Admin) SetLogLevel(_ *http.Request, args *client.SetLogLevelArgs, reply *api.EmptyReply) error { log.Info("EVM: SetLogLevel called", "logLevel", args.Level) p.vm.ctx.Lock.Lock() diff --git a/plugin/evm/codec.go b/plugin/evm/atomic/codec.go similarity index 91% rename from plugin/evm/codec.go rename to plugin/evm/atomic/codec.go index e4c38761e3..3376eeb049 100644 --- a/plugin/evm/codec.go +++ b/plugin/evm/atomic/codec.go @@ -1,9 +1,10 @@ // (c) 2019-2021, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package atomic import ( + "errors" "fmt" "github.com/ava-labs/avalanchego/codec" @@ -12,8 +13,14 @@ import ( "github.com/ava-labs/avalanchego/vms/secp256k1fx" ) -// Codec does serialization and deserialization -var Codec codec.Manager +const CodecVersion = uint16(0) + +var ( + // Codec does serialization and deserialization + Codec codec.Manager + + errMissingAtomicTxs = errors.New("cannot build a block with non-empty extra data and zero atomic transactions") +) func init() { Codec = codec.NewDefaultManager() @@ -35,7 +42,7 @@ func init() { lc.RegisterType(&secp256k1fx.Credential{}), lc.RegisterType(&secp256k1fx.Input{}), lc.RegisterType(&secp256k1fx.OutputOwners{}), - Codec.RegisterCodec(codecVersion, lc), + Codec.RegisterCodec(CodecVersion, lc), ) if errs.Errored() { panic(errs.Err) diff --git a/plugin/evm/export_tx.go b/plugin/evm/atomic/export_tx.go similarity index 57% rename from plugin/evm/export_tx.go rename to plugin/evm/atomic/export_tx.go index a187007046..4938ddc53e 100644 --- a/plugin/evm/export_tx.go +++ b/plugin/evm/atomic/export_tx.go @@ -1,7 +1,7 @@ // (c) 2019-2020, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package atomic import ( "context" @@ -9,14 +9,13 @@ import ( "fmt" "math/big" - "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/params" "github.com/holiman/uint256" "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/avalanchego/utils" + avalancheutils "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/math" @@ -30,10 +29,15 @@ import ( ) var ( - _ UnsignedAtomicTx = &UnsignedExportTx{} - _ secp256k1fx.UnsignedTx = &UnsignedExportTx{} - errExportNonAVAXInputBanff = errors.New("export input cannot contain non-AVAX in Banff") - errExportNonAVAXOutputBanff = errors.New("export output cannot contain non-AVAX in Banff") + _ UnsignedAtomicTx = &UnsignedExportTx{} + _ secp256k1fx.UnsignedTx = &UnsignedExportTx{} + ErrExportNonAVAXInputBanff = errors.New("export input cannot contain non-AVAX in Banff") + ErrExportNonAVAXOutputBanff = errors.New("export output cannot contain non-AVAX in Banff") + ErrNoExportOutputs = errors.New("tx has no export outputs") + errPublicKeySignatureMismatch = errors.New("signature doesn't match public key") + errOverflowExport = errors.New("overflow when computing export amount + txFee") + errInsufficientFunds = errors.New("insufficient funds") + errInvalidNonce = errors.New("invalid nonce") ) // UnsignedExportTx is an unsigned ExportTx @@ -73,13 +77,13 @@ func (utx *UnsignedExportTx) Verify( ) error { switch { case utx == nil: - return errNilTx + return ErrNilTx case len(utx.ExportedOutputs) == 0: - return errNoExportOutputs + return ErrNoExportOutputs case utx.NetworkID != ctx.NetworkID: - return errWrongNetworkID + return ErrWrongNetworkID case ctx.ChainID != utx.BlockchainID: - return errWrongBlockchainID + return ErrWrongChainID } // Make sure that the tx has a valid peer chain ID @@ -87,11 +91,11 @@ func (utx *UnsignedExportTx) Verify( // Note that SameSubnet verifies that [tx.DestinationChain] isn't this // chain's ID if err := verify.SameSubnet(context.TODO(), ctx, utx.DestinationChain); err != nil { - return errWrongChainID + return ErrWrongChainID } } else { if utx.DestinationChain != ctx.XChainID { - return errWrongChainID + return ErrWrongChainID } } @@ -100,7 +104,7 @@ func (utx *UnsignedExportTx) Verify( return err } if rules.IsBanff && in.AssetID != ctx.AVAXAssetID { - return errExportNonAVAXInputBanff + return ErrExportNonAVAXInputBanff } } @@ -110,17 +114,17 @@ func (utx *UnsignedExportTx) Verify( } assetID := out.AssetID() if assetID != ctx.AVAXAssetID && utx.DestinationChain == constants.PlatformChainID { - return errWrongChainID + return ErrWrongChainID } if rules.IsBanff && assetID != ctx.AVAXAssetID { - return errExportNonAVAXOutputBanff + return ErrExportNonAVAXOutputBanff } } if !avax.IsSortedTransferableOutputs(utx.ExportedOutputs, Codec) { - return errOutputsNotSorted + return ErrOutputsNotSorted } - if rules.IsApricotPhase1 && !utils.IsSortedAndUnique(utx.Ins) { - return errInputsNotSortedUnique + if rules.IsApricotPhase1 && !avalancheutils.IsSortedAndUnique(utx.Ins) { + return ErrInputsNotSortedUnique } return nil @@ -176,13 +180,14 @@ func (utx *UnsignedExportTx) Burned(assetID ids.ID) (uint64, error) { // SemanticVerify this transaction is valid. func (utx *UnsignedExportTx) SemanticVerify( - vm *VM, + backend *Backend, stx *Tx, - _ *Block, + parent AtomicBlockContext, baseFee *big.Int, - rules params.Rules, ) error { - if err := utx.Verify(vm.ctx, rules); err != nil { + ctx := backend.Ctx + rules := backend.Rules + if err := utx.Verify(ctx, rules); err != nil { return err } @@ -199,10 +204,10 @@ func (utx *UnsignedExportTx) SemanticVerify( if err != nil { return err } - fc.Produce(vm.ctx.AVAXAssetID, txFee) + fc.Produce(ctx.AVAXAssetID, txFee) // Apply fees to export transactions before Apricot Phase 3 default: - fc.Produce(vm.ctx.AVAXAssetID, params.AvalancheAtomicTxFee) + fc.Produce(ctx.AVAXAssetID, params.AvalancheAtomicTxFee) } for _, out := range utx.ExportedOutputs { fc.Produce(out.AssetID(), out.Output().Amount()) @@ -231,11 +236,11 @@ func (utx *UnsignedExportTx) SemanticVerify( if len(cred.Sigs) != 1 { return fmt.Errorf("expected one signature for EVM Input Credential, but found: %d", len(cred.Sigs)) } - pubKey, err := vm.secpCache.RecoverPublicKey(utx.Bytes(), cred.Sigs[0][:]) + pubKey, err := backend.SecpCache.RecoverPublicKey(utx.Bytes(), cred.Sigs[0][:]) if err != nil { return err } - if input.Address != PublicKeyToEthAddress(pubKey) { + if input.Address != pubKey.EthAddress() { return errPublicKeySignatureMismatch } } @@ -258,7 +263,7 @@ func (utx *UnsignedExportTx) AtomicOps() (ids.ID, *atomic.Requests, error) { Out: out.Out, } - utxoBytes, err := Codec.Marshal(codecVersion, utxo) + utxoBytes, err := Codec.Marshal(CodecVersion, utxo) if err != nil { return ids.ID{}, nil, err } @@ -277,8 +282,11 @@ func (utx *UnsignedExportTx) AtomicOps() (ids.ID, *atomic.Requests, error) { return utx.DestinationChain, &atomic.Requests{PutRequests: elems}, nil } -// newExportTx returns a new ExportTx -func (vm *VM) newExportTx( +// NewExportTx returns a new ExportTx +func NewExportTx( + ctx *snow.Context, + rules params.Rules, + state StateDB, assetID ids.ID, // AssetID of the tokens to export amount uint64, // Amount of tokens to export chainID ids.ID, // Chain to send the UTXOs to @@ -306,8 +314,8 @@ func (vm *VM) newExportTx( ) // consume non-AVAX - if assetID != vm.ctx.AVAXAssetID { - ins, signers, err = vm.GetSpendableFunds(keys, assetID, amount) + if assetID != ctx.AVAXAssetID { + ins, signers, err = GetSpendableFunds(ctx, state, keys, assetID, amount) if err != nil { return nil, fmt.Errorf("couldn't generate tx inputs/signers: %w", err) } @@ -315,18 +323,17 @@ func (vm *VM) newExportTx( avaxNeeded = amount } - rules := vm.currentRules() switch { case rules.IsApricotPhase3: utx := &UnsignedExportTx{ - NetworkID: vm.ctx.NetworkID, - BlockchainID: vm.ctx.ChainID, + NetworkID: ctx.NetworkID, + BlockchainID: ctx.ChainID, DestinationChain: chainID, Ins: ins, ExportedOutputs: outs, } tx := &Tx{UnsignedAtomicTx: utx} - if err := tx.Sign(vm.codec, nil); err != nil { + if err := tx.Sign(Codec, nil); err != nil { return nil, err } @@ -336,14 +343,14 @@ func (vm *VM) newExportTx( return nil, err } - avaxIns, avaxSigners, err = vm.GetSpendableAVAXWithFee(keys, avaxNeeded, cost, baseFee) + avaxIns, avaxSigners, err = GetSpendableAVAXWithFee(ctx, state, keys, avaxNeeded, cost, baseFee) default: var newAvaxNeeded uint64 newAvaxNeeded, err = math.Add64(avaxNeeded, params.AvalancheAtomicTxFee) if err != nil { return nil, errOverflowExport } - avaxIns, avaxSigners, err = vm.GetSpendableFunds(keys, vm.ctx.AVAXAssetID, newAvaxNeeded) + avaxIns, avaxSigners, err = GetSpendableFunds(ctx, state, keys, ctx.AVAXAssetID, newAvaxNeeded) } if err != nil { return nil, fmt.Errorf("couldn't generate tx inputs/signers: %w", err) @@ -351,26 +358,26 @@ func (vm *VM) newExportTx( ins = append(ins, avaxIns...) signers = append(signers, avaxSigners...) - avax.SortTransferableOutputs(outs, vm.codec) + avax.SortTransferableOutputs(outs, Codec) SortEVMInputsAndSigners(ins, signers) // Create the transaction utx := &UnsignedExportTx{ - NetworkID: vm.ctx.NetworkID, - BlockchainID: vm.ctx.ChainID, + NetworkID: ctx.NetworkID, + BlockchainID: ctx.ChainID, DestinationChain: chainID, Ins: ins, ExportedOutputs: outs, } tx := &Tx{UnsignedAtomicTx: utx} - if err := tx.Sign(vm.codec, signers); err != nil { + if err := tx.Sign(Codec, signers); err != nil { return nil, err } - return tx, utx.Verify(vm.ctx, vm.currentRules()) + return tx, utx.Verify(ctx, rules) } // EVMStateTransfer executes the state update from the atomic export transaction -func (utx *UnsignedExportTx) EVMStateTransfer(ctx *snow.Context, state *state.StateDB) error { +func (utx *UnsignedExportTx) EVMStateTransfer(ctx *snow.Context, state StateDB) error { addrs := map[[20]byte]uint64{} for _, from := range utx.Ins { if from.AssetID == ctx.AVAXAssetID { @@ -379,7 +386,7 @@ func (utx *UnsignedExportTx) EVMStateTransfer(ctx *snow.Context, state *state.St // denomination before export. amount := new(uint256.Int).Mul( uint256.NewInt(from.Amount), - uint256.NewInt(x2cRate.Uint64()), + uint256.NewInt(X2CRate.Uint64()), ) if state.GetBalance(from.Address).Cmp(amount) < 0 { return errInsufficientFunds @@ -403,3 +410,151 @@ func (utx *UnsignedExportTx) EVMStateTransfer(ctx *snow.Context, state *state.St } return nil } + +// GetSpendableFunds returns a list of EVMInputs and keys (in corresponding +// order) to total [amount] of [assetID] owned by [keys]. +// Note: we return [][]*secp256k1.PrivateKey even though each input +// corresponds to a single key, so that the signers can be passed in to +// [tx.Sign] which supports multiple keys on a single input. +func GetSpendableFunds( + ctx *snow.Context, + state StateDB, + keys []*secp256k1.PrivateKey, + assetID ids.ID, + amount uint64, +) ([]EVMInput, [][]*secp256k1.PrivateKey, error) { + inputs := []EVMInput{} + signers := [][]*secp256k1.PrivateKey{} + // Note: we assume that each key in [keys] is unique, so that iterating over + // the keys will not produce duplicated nonces in the returned EVMInput slice. + for _, key := range keys { + if amount == 0 { + break + } + addr := key.EthAddress() + var balance uint64 + if assetID == ctx.AVAXAssetID { + // If the asset is AVAX, we divide by the x2cRate to convert back to the correct + // denomination of AVAX that can be exported. + balance = new(uint256.Int).Div(state.GetBalance(addr), X2CRate).Uint64() + } else { + balance = state.GetBalanceMultiCoin(addr, common.Hash(assetID)).Uint64() + } + if balance == 0 { + continue + } + if amount < balance { + balance = amount + } + nonce := state.GetNonce(addr) + + inputs = append(inputs, EVMInput{ + Address: addr, + Amount: balance, + AssetID: assetID, + Nonce: nonce, + }) + signers = append(signers, []*secp256k1.PrivateKey{key}) + amount -= balance + } + + if amount > 0 { + return nil, nil, errInsufficientFunds + } + + return inputs, signers, nil +} + +// GetSpendableAVAXWithFee returns a list of EVMInputs and keys (in corresponding +// order) to total [amount] + [fee] of [AVAX] owned by [keys]. +// This function accounts for the added cost of the additional inputs needed to +// create the transaction and makes sure to skip any keys with a balance that is +// insufficient to cover the additional fee. +// Note: we return [][]*secp256k1.PrivateKey even though each input +// corresponds to a single key, so that the signers can be passed in to +// [tx.Sign] which supports multiple keys on a single input. +func GetSpendableAVAXWithFee( + ctx *snow.Context, + state StateDB, + keys []*secp256k1.PrivateKey, + amount uint64, + cost uint64, + baseFee *big.Int, +) ([]EVMInput, [][]*secp256k1.PrivateKey, error) { + initialFee, err := CalculateDynamicFee(cost, baseFee) + if err != nil { + return nil, nil, err + } + + newAmount, err := math.Add64(amount, initialFee) + if err != nil { + return nil, nil, err + } + amount = newAmount + + inputs := []EVMInput{} + signers := [][]*secp256k1.PrivateKey{} + // Note: we assume that each key in [keys] is unique, so that iterating over + // the keys will not produce duplicated nonces in the returned EVMInput slice. + for _, key := range keys { + if amount == 0 { + break + } + + prevFee, err := CalculateDynamicFee(cost, baseFee) + if err != nil { + return nil, nil, err + } + + newCost := cost + EVMInputGas + newFee, err := CalculateDynamicFee(newCost, baseFee) + if err != nil { + return nil, nil, err + } + + additionalFee := newFee - prevFee + + addr := key.EthAddress() + // Since the asset is AVAX, we divide by the x2cRate to convert back to + // the correct denomination of AVAX that can be exported. + balance := new(uint256.Int).Div(state.GetBalance(addr), X2CRate).Uint64() + // If the balance for [addr] is insufficient to cover the additional cost + // of adding an input to the transaction, skip adding the input altogether + if balance <= additionalFee { + continue + } + + // Update the cost for the next iteration + cost = newCost + + newAmount, err := math.Add64(amount, additionalFee) + if err != nil { + return nil, nil, err + } + amount = newAmount + + // Use the entire [balance] as an input, but if the required [amount] + // is less than the balance, update the [inputAmount] to spend the + // minimum amount to finish the transaction. + inputAmount := balance + if amount < balance { + inputAmount = amount + } + nonce := state.GetNonce(addr) + + inputs = append(inputs, EVMInput{ + Address: addr, + Amount: inputAmount, + AssetID: ctx.AVAXAssetID, + Nonce: nonce, + }) + signers = append(signers, []*secp256k1.PrivateKey{key}) + amount -= inputAmount + } + + if amount > 0 { + return nil, nil, errInsufficientFunds + } + + return inputs, signers, nil +} diff --git a/plugin/evm/import_tx.go b/plugin/evm/atomic/import_tx.go similarity index 70% rename from plugin/evm/import_tx.go rename to plugin/evm/atomic/import_tx.go index b447a717ee..9213299d8c 100644 --- a/plugin/evm/import_tx.go +++ b/plugin/evm/atomic/import_tx.go @@ -1,7 +1,7 @@ // (c) 2019-2020, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package atomic import ( "context" @@ -10,7 +10,6 @@ import ( "math/big" "slices" - "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/params" "github.com/holiman/uint256" @@ -31,8 +30,19 @@ import ( var ( _ UnsignedAtomicTx = &UnsignedImportTx{} _ secp256k1fx.UnsignedTx = &UnsignedImportTx{} - errImportNonAVAXInputBanff = errors.New("import input cannot contain non-AVAX in Banff") - errImportNonAVAXOutputBanff = errors.New("import output cannot contain non-AVAX in Banff") + ErrImportNonAVAXInputBanff = errors.New("import input cannot contain non-AVAX in Banff") + ErrImportNonAVAXOutputBanff = errors.New("import output cannot contain non-AVAX in Banff") + ErrNoImportInputs = errors.New("tx has no imported inputs") + ErrConflictingAtomicInputs = errors.New("invalid block due to conflicting atomic inputs") + ErrWrongChainID = errors.New("tx has wrong chain ID") + ErrNoEVMOutputs = errors.New("tx has no EVM outputs") + ErrInputsNotSortedUnique = errors.New("inputs not sorted and unique") + ErrOutputsNotSortedUnique = errors.New("outputs not sorted and unique") + ErrOutputsNotSorted = errors.New("tx outputs not sorted") + ErrAssetIDMismatch = errors.New("asset IDs in the input don't match the utxo") + errNilBaseFeeApricotPhase3 = errors.New("nil base fee is invalid after apricotPhase3") + errInsufficientFundsForFee = errors.New("insufficient AVAX funds to pay transaction fee") + errRejectedParent = errors.New("rejected parent") ) // UnsignedImportTx is an unsigned ImportTx @@ -66,15 +76,15 @@ func (utx *UnsignedImportTx) Verify( ) error { switch { case utx == nil: - return errNilTx + return ErrNilTx case len(utx.ImportedInputs) == 0: - return errNoImportInputs + return ErrNoImportInputs case utx.NetworkID != ctx.NetworkID: - return errWrongNetworkID + return ErrWrongNetworkID case ctx.ChainID != utx.BlockchainID: - return errWrongBlockchainID + return ErrWrongChainID case rules.IsApricotPhase3 && len(utx.Outs) == 0: - return errNoEVMOutputs + return ErrNoEVMOutputs } // Make sure that the tx has a valid peer chain ID @@ -82,11 +92,11 @@ func (utx *UnsignedImportTx) Verify( // Note that SameSubnet verifies that [tx.SourceChain] isn't this // chain's ID if err := verify.SameSubnet(context.TODO(), ctx, utx.SourceChain); err != nil { - return errWrongChainID + return ErrWrongChainID } } else { if utx.SourceChain != ctx.XChainID { - return errWrongChainID + return ErrWrongChainID } } @@ -95,7 +105,7 @@ func (utx *UnsignedImportTx) Verify( return fmt.Errorf("EVM Output failed verification: %w", err) } if rules.IsBanff && out.AssetID != ctx.AVAXAssetID { - return errImportNonAVAXOutputBanff + return ErrImportNonAVAXOutputBanff } } @@ -104,20 +114,20 @@ func (utx *UnsignedImportTx) Verify( return fmt.Errorf("atomic input failed verification: %w", err) } if rules.IsBanff && in.AssetID() != ctx.AVAXAssetID { - return errImportNonAVAXInputBanff + return ErrImportNonAVAXInputBanff } } if !utils.IsSortedAndUnique(utx.ImportedInputs) { - return errInputsNotSortedUnique + return ErrInputsNotSortedUnique } if rules.IsApricotPhase2 { if !utils.IsSortedAndUnique(utx.Outs) { - return errOutputsNotSortedUnique + return ErrOutputsNotSortedUnique } } else if rules.IsApricotPhase1 { if !slices.IsSortedFunc(utx.Outs, EVMOutput.Compare) { - return errOutputsNotSorted + return ErrOutputsNotSorted } } @@ -177,13 +187,14 @@ func (utx *UnsignedImportTx) Burned(assetID ids.ID) (uint64, error) { // SemanticVerify this transaction is valid. func (utx *UnsignedImportTx) SemanticVerify( - vm *VM, + backend *Backend, stx *Tx, - parent *Block, + parent AtomicBlockContext, baseFee *big.Int, - rules params.Rules, ) error { - if err := utx.Verify(vm.ctx, rules); err != nil { + ctx := backend.Ctx + rules := backend.Rules + if err := utx.Verify(ctx, rules); err != nil { return err } @@ -200,11 +211,11 @@ func (utx *UnsignedImportTx) SemanticVerify( if err != nil { return err } - fc.Produce(vm.ctx.AVAXAssetID, txFee) + fc.Produce(ctx.AVAXAssetID, txFee) // Apply fees to import transactions as of Apricot Phase 2 case rules.IsApricotPhase2: - fc.Produce(vm.ctx.AVAXAssetID, params.AvalancheAtomicTxFee) + fc.Produce(ctx.AVAXAssetID, params.AvalancheAtomicTxFee) } for _, out := range utx.Outs { fc.Produce(out.AssetID, out.Amount) @@ -221,7 +232,7 @@ func (utx *UnsignedImportTx) SemanticVerify( return fmt.Errorf("import tx contained mismatched number of inputs/credentials (%d vs. %d)", len(utx.ImportedInputs), len(stx.Creds)) } - if !vm.bootstrapped.Get() { + if !backend.Bootstrapped { // Allow for force committing during bootstrapping return nil } @@ -232,7 +243,7 @@ func (utx *UnsignedImportTx) SemanticVerify( utxoIDs[i] = inputID[:] } // allUTXOBytes is guaranteed to be the same length as utxoIDs - allUTXOBytes, err := vm.ctx.SharedMemory.Get(utx.SourceChain, utxoIDs) + allUTXOBytes, err := ctx.SharedMemory.Get(utx.SourceChain, utxoIDs) if err != nil { return fmt.Errorf("failed to fetch import UTXOs from %s due to: %w", utx.SourceChain, err) } @@ -241,7 +252,7 @@ func (utx *UnsignedImportTx) SemanticVerify( utxoBytes := allUTXOBytes[i] utxo := &avax.UTXO{} - if _, err := vm.codec.Unmarshal(utxoBytes, utxo); err != nil { + if _, err := Codec.Unmarshal(utxoBytes, utxo); err != nil { return fmt.Errorf("failed to unmarshal UTXO: %w", err) } @@ -250,15 +261,15 @@ func (utx *UnsignedImportTx) SemanticVerify( utxoAssetID := utxo.AssetID() inAssetID := in.AssetID() if utxoAssetID != inAssetID { - return errAssetIDMismatch + return ErrAssetIDMismatch } - if err := vm.fx.VerifyTransfer(utx, in.In, cred, utxo.Out); err != nil { + if err := backend.Fx.VerifyTransfer(utx, in.In, cred, utxo.Out); err != nil { return fmt.Errorf("import tx transfer failed verification: %w", err) } } - return vm.conflicts(utx.InputUTXOs(), parent) + return conflicts(backend, utx.InputUTXOs(), parent) } // AtomicOps returns imported inputs spent on this transaction @@ -275,28 +286,11 @@ func (utx *UnsignedImportTx) AtomicOps() (ids.ID, *atomic.Requests, error) { return utx.SourceChain, &atomic.Requests{RemoveRequests: utxoIDs}, nil } -// newImportTx returns a new ImportTx -func (vm *VM) newImportTx( - chainID ids.ID, // chain to import from - to common.Address, // Address of recipient - baseFee *big.Int, // fee to use post-AP3 - keys []*secp256k1.PrivateKey, // Keys to import the funds -) (*Tx, error) { - kc := secp256k1fx.NewKeychain() - for _, key := range keys { - kc.Add(key) - } - - atomicUTXOs, _, _, err := vm.GetAtomicUTXOs(chainID, kc.Addresses(), ids.ShortEmpty, ids.Empty, -1) - if err != nil { - return nil, fmt.Errorf("problem retrieving atomic UTXOs: %w", err) - } - - return vm.newImportTxWithUTXOs(chainID, to, baseFee, kc, atomicUTXOs) -} - -// newImportTx returns a new ImportTx -func (vm *VM) newImportTxWithUTXOs( +// NewImportTx returns a new ImportTx +func NewImportTx( + ctx *snow.Context, + rules params.Rules, + time uint64, chainID ids.ID, // chain to import from to common.Address, // Address of recipient baseFee *big.Int, // fee to use post-AP3 @@ -307,9 +301,8 @@ func (vm *VM) newImportTxWithUTXOs( signers := [][]*secp256k1.PrivateKey{} importedAmount := make(map[ids.ID]uint64) - now := vm.clock.Unix() for _, utxo := range atomicUTXOs { - inputIntf, utxoSigners, err := kc.Spend(utxo.Out, now) + inputIntf, utxoSigners, err := kc.Spend(utxo.Out, time) if err != nil { continue } @@ -330,7 +323,7 @@ func (vm *VM) newImportTxWithUTXOs( signers = append(signers, utxoSigners) } avax.SortTransferableInputsWithSigners(importedInputs, signers) - importedAVAXAmount := importedAmount[vm.ctx.AVAXAssetID] + importedAVAXAmount := importedAmount[ctx.AVAXAssetID] outs := make([]EVMOutput, 0, len(importedAmount)) // This will create unique outputs (in the context of sorting) @@ -338,7 +331,7 @@ func (vm *VM) newImportTxWithUTXOs( for assetID, amount := range importedAmount { // Skip the AVAX amount since it is included separately to account for // the fee - if assetID == vm.ctx.AVAXAssetID || amount == 0 { + if assetID == ctx.AVAXAssetID || amount == 0 { continue } outs = append(outs, EVMOutput{ @@ -348,8 +341,6 @@ func (vm *VM) newImportTxWithUTXOs( }) } - rules := vm.currentRules() - var ( txFeeWithoutChange uint64 txFeeWithChange uint64 @@ -360,14 +351,14 @@ func (vm *VM) newImportTxWithUTXOs( return nil, errNilBaseFeeApricotPhase3 } utx := &UnsignedImportTx{ - NetworkID: vm.ctx.NetworkID, - BlockchainID: vm.ctx.ChainID, + NetworkID: ctx.NetworkID, + BlockchainID: ctx.ChainID, Outs: outs, ImportedInputs: importedInputs, SourceChain: chainID, } tx := &Tx{UnsignedAtomicTx: utx} - if err := tx.Sign(vm.codec, nil); err != nil { + if err := tx.Sign(Codec, nil); err != nil { return nil, err } @@ -399,7 +390,7 @@ func (vm *VM) newImportTxWithUTXOs( outs = append(outs, EVMOutput{ Address: to, Amount: importedAVAXAmount - txFeeWithChange, - AssetID: vm.ctx.AVAXAssetID, + AssetID: ctx.AVAXAssetID, }) } @@ -407,35 +398,35 @@ func (vm *VM) newImportTxWithUTXOs( // Note: this can happen if there is exactly enough AVAX to pay the // transaction fee, but no other funds to be imported. if len(outs) == 0 { - return nil, errNoEVMOutputs + return nil, ErrNoEVMOutputs } utils.Sort(outs) // Create the transaction utx := &UnsignedImportTx{ - NetworkID: vm.ctx.NetworkID, - BlockchainID: vm.ctx.ChainID, + NetworkID: ctx.NetworkID, + BlockchainID: ctx.ChainID, Outs: outs, ImportedInputs: importedInputs, SourceChain: chainID, } tx := &Tx{UnsignedAtomicTx: utx} - if err := tx.Sign(vm.codec, signers); err != nil { + if err := tx.Sign(Codec, signers); err != nil { return nil, err } - return tx, utx.Verify(vm.ctx, vm.currentRules()) + return tx, utx.Verify(ctx, rules) } // EVMStateTransfer performs the state transfer to increase the balances of // accounts accordingly with the imported EVMOutputs -func (utx *UnsignedImportTx) EVMStateTransfer(ctx *snow.Context, state *state.StateDB) error { +func (utx *UnsignedImportTx) EVMStateTransfer(ctx *snow.Context, state StateDB) error { for _, to := range utx.Outs { if to.AssetID == ctx.AVAXAssetID { log.Debug("import_tx", "src", utx.SourceChain, "addr", to.Address, "amount", to.Amount, "assetID", "AVAX") // If the asset is AVAX, convert the input amount in nAVAX to gWei by // multiplying by the x2c rate. - amount := new(uint256.Int).Mul(uint256.NewInt(to.Amount), x2cRate) + amount := new(uint256.Int).Mul(uint256.NewInt(to.Amount), X2CRate) state.AddBalance(to.Address, amount) } else { log.Debug("import_tx", "src", utx.SourceChain, "addr", to.Address, "amount", to.Amount, "assetID", to.AssetID) @@ -445,3 +436,43 @@ func (utx *UnsignedImportTx) EVMStateTransfer(ctx *snow.Context, state *state.St } return nil } + +// conflicts returns an error if [inputs] conflicts with any of the atomic inputs contained in [ancestor] +// or any of its ancestor blocks going back to the last accepted block in its ancestry. If [ancestor] is +// accepted, then nil will be returned immediately. +// If the ancestry of [ancestor] cannot be fetched, then [errRejectedParent] may be returned. +func conflicts(backend *Backend, inputs set.Set[ids.ID], ancestor AtomicBlockContext) error { + fetcher := backend.BlockFetcher + lastAcceptedBlock := fetcher.LastAcceptedBlockInternal() + lastAcceptedHeight := lastAcceptedBlock.Height() + for ancestor.Height() > lastAcceptedHeight { + // If any of the atomic transactions in the ancestor conflict with [inputs] + // return an error. + for _, atomicTx := range ancestor.AtomicTxs() { + if inputs.Overlaps(atomicTx.InputUTXOs()) { + return ErrConflictingAtomicInputs + } + } + + // Move up the chain. + nextAncestorID := ancestor.Parent() + // If the ancestor is unknown, then the parent failed + // verification when it was called. + // If the ancestor is rejected, then this block shouldn't be + // inserted into the canonical chain because the parent is + // will be missing. + // If the ancestor is processing, then the block may have + // been verified. + nextAncestorIntf, err := fetcher.GetBlockInternal(context.TODO(), nextAncestorID) + if err != nil { + return errRejectedParent + } + nextAncestor, ok := nextAncestorIntf.(AtomicBlockContext) + if !ok { + return fmt.Errorf("ancestor block %s had unexpected type %T", nextAncestor.ID(), nextAncestorIntf) + } + ancestor = nextAncestor + } + + return nil +} diff --git a/plugin/evm/metadata.go b/plugin/evm/atomic/metadata.go similarity index 98% rename from plugin/evm/metadata.go rename to plugin/evm/atomic/metadata.go index 2665d329bc..7cd570f7ec 100644 --- a/plugin/evm/metadata.go +++ b/plugin/evm/atomic/metadata.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package atomic import ( "github.com/ava-labs/avalanchego/ids" diff --git a/plugin/evm/status.go b/plugin/evm/atomic/status.go similarity index 95% rename from plugin/evm/status.go rename to plugin/evm/atomic/status.go index 14d1b009a7..c7c72d0987 100644 --- a/plugin/evm/status.go +++ b/plugin/evm/atomic/status.go @@ -1,16 +1,14 @@ // (c) 2019-2020, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package atomic import ( "errors" "fmt" ) -var ( - errUnknownStatus = errors.New("unknown status") -) +var errUnknownStatus = errors.New("unknown status") // Status ... type Status uint32 diff --git a/plugin/evm/tx.go b/plugin/evm/atomic/tx.go similarity index 75% rename from plugin/evm/tx.go rename to plugin/evm/atomic/tx.go index 9361f71976..a911402dea 100644 --- a/plugin/evm/tx.go +++ b/plugin/evm/atomic/tx.go @@ -1,44 +1,50 @@ // (c) 2019-2020, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package atomic import ( "bytes" + "context" "errors" "fmt" "math/big" "sort" "github.com/ethereum/go-ethereum/common" + "github.com/holiman/uint256" - "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/params" "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/avalanchego/utils" + "github.com/ava-labs/avalanchego/snow/consensus/snowman" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/hashing" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/avalanchego/vms/components/verify" + "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/secp256k1fx" ) +const ( + X2CRateUint64 uint64 = 1_000_000_000 + x2cRateMinus1Uint64 uint64 = X2CRateUint64 - 1 +) + var ( - errWrongBlockchainID = errors.New("wrong blockchain ID provided") - errWrongNetworkID = errors.New("tx was issued with a different network ID") - errNilTx = errors.New("tx is nil") - errNoValueOutput = errors.New("output has no value") - errNoValueInput = errors.New("input has no value") - errNilOutput = errors.New("nil output") - errNilInput = errors.New("nil input") - errEmptyAssetID = errors.New("empty asset ID is not valid") - errNilBaseFee = errors.New("cannot calculate dynamic fee with nil baseFee") - errFeeOverflow = errors.New("overflow occurred while calculating the fee") + ErrWrongNetworkID = errors.New("tx was issued with a different network ID") + ErrNilTx = errors.New("tx is nil") + errNoValueOutput = errors.New("output has no value") + ErrNoValueInput = errors.New("input has no value") + errNilOutput = errors.New("nil output") + errNilInput = errors.New("nil input") + errEmptyAssetID = errors.New("empty asset ID is not valid") + errNilBaseFee = errors.New("cannot calculate dynamic fee with nil baseFee") + errFeeOverflow = errors.New("overflow occurred while calculating the fee") ) // Constants for calculating the gas consumed by atomic transactions @@ -46,6 +52,12 @@ var ( TxBytesGas uint64 = 1 EVMOutputGas uint64 = (common.AddressLength + wrappers.LongLen + hashing.HashLen) * TxBytesGas EVMInputGas uint64 = (common.AddressLength+wrappers.LongLen+hashing.HashLen+wrappers.LongLen)*TxBytesGas + secp256k1fx.CostPerSignature + // X2CRate is the conversion rate between the smallest denomination on the X-Chain + // 1 nAVAX and the smallest denomination on the C-Chain 1 wei. Where 1 nAVAX = 1 gWei. + // This is only required for AVAX because the denomination of 1 AVAX is 9 decimal + // places on the X and P chains, but is 18 decimal places within the EVM. + X2CRate = uint256.NewInt(X2CRateUint64) + x2cRateMinus1 = uint256.NewInt(x2cRateMinus1Uint64) ) // EVMOutput defines an output that is added to the EVM state created by import transactions @@ -98,7 +110,7 @@ func (in *EVMInput) Verify() error { case in == nil: return errNilInput case in.Amount == 0: - return errNoValueInput + return ErrNoValueInput case in.AssetID == ids.Empty: return errEmptyAssetID } @@ -115,6 +127,39 @@ type UnsignedTx interface { SignedBytes() []byte } +type Backend struct { + Ctx *snow.Context + Fx fx.Fx + Rules params.Rules + Bootstrapped bool + BlockFetcher BlockFetcher + SecpCache *secp256k1.RecoverCache +} + +type BlockFetcher interface { + LastAcceptedBlockInternal() snowman.Block + GetBlockInternal(context.Context, ids.ID) (snowman.Block, error) +} + +type AtomicBlockContext interface { + AtomicTxs() []*Tx + snowman.Block +} + +type StateDB interface { + AddBalance(common.Address, *uint256.Int) + AddBalanceMultiCoin(common.Address, common.Hash, *big.Int) + + SubBalance(common.Address, *uint256.Int) + SubBalanceMultiCoin(common.Address, common.Hash, *big.Int) + + GetBalance(common.Address) *uint256.Int + GetBalanceMultiCoin(common.Address, common.Hash) *big.Int + + GetNonce(common.Address) uint64 + SetNonce(common.Address, uint64) +} + // UnsignedAtomicTx is an unsigned operation that can be atomically accepted type UnsignedAtomicTx interface { UnsignedTx @@ -124,13 +169,14 @@ type UnsignedAtomicTx interface { // Verify attempts to verify that the transaction is well formed Verify(ctx *snow.Context, rules params.Rules) error // Attempts to verify this transaction with the provided state. - SemanticVerify(vm *VM, stx *Tx, parent *Block, baseFee *big.Int, rules params.Rules) error + // SemanticVerify this transaction is valid. + SemanticVerify(backend *Backend, stx *Tx, parent AtomicBlockContext, baseFee *big.Int) error // AtomicOps returns the blockchainID and set of atomic requests that // must be applied to shared memory for this transaction to be accepted. // The set of atomic requests must be returned in a consistent order. AtomicOps() (ids.ID, *atomic.Requests, error) - EVMStateTransfer(ctx *snow.Context, state *state.StateDB) error + EVMStateTransfer(ctx *snow.Context, state StateDB) error } // Tx is a signed transaction @@ -157,7 +203,7 @@ func (tx *Tx) Compare(other *Tx) int { // Sign this transaction with the provided signers func (tx *Tx) Sign(c codec.Manager, signers [][]*secp256k1.PrivateKey) error { - unsignedBytes, err := c.Marshal(codecVersion, &tx.UnsignedAtomicTx) + unsignedBytes, err := c.Marshal(CodecVersion, &tx.UnsignedAtomicTx) if err != nil { return fmt.Errorf("couldn't marshal UnsignedAtomicTx: %w", err) } @@ -178,7 +224,7 @@ func (tx *Tx) Sign(c codec.Manager, signers [][]*secp256k1.PrivateKey) error { tx.Creds = append(tx.Creds, cred) // Attach credential } - signedBytes, err := c.Marshal(codecVersion, tx) + signedBytes, err := c.Marshal(CodecVersion, tx) if err != nil { return fmt.Errorf("couldn't marshal Tx: %w", err) } @@ -216,7 +262,7 @@ func (tx *Tx) BlockFeeContribution(fixedFee bool, avaxAssetID ids.ID, baseFee *b // Calculate the amount of AVAX that has been burned above the required fee denominated // in C-Chain native 18 decimal places - blockFeeContribution := new(big.Int).Mul(new(big.Int).SetUint64(excessBurned), x2cRate.ToBig()) + blockFeeContribution := new(big.Int).Mul(new(big.Int).SetUint64(excessBurned), X2CRate.ToBig()) return blockFeeContribution, new(big.Int).SetUint64(gasUsed), nil } @@ -255,7 +301,7 @@ func CalculateDynamicFee(cost uint64, baseFee *big.Int) (uint64, error) { bigCost := new(big.Int).SetUint64(cost) fee := new(big.Int).Mul(bigCost, baseFee) feeToRoundUp := new(big.Int).Add(fee, x2cRateMinus1.ToBig()) - feeInNAVAX := new(big.Int).Div(feeToRoundUp, x2cRate.ToBig()) + feeInNAVAX := new(big.Int).Div(feeToRoundUp, X2CRate.ToBig()) if !feeInNAVAX.IsUint64() { // the fee is more than can fit in a uint64 return 0, errFeeOverflow @@ -266,36 +312,3 @@ func CalculateDynamicFee(cost uint64, baseFee *big.Int) (uint64, error) { func calcBytesCost(len int) uint64 { return uint64(len) * TxBytesGas } - -// mergeAtomicOps merges atomic requests represented by [txs] -// to the [output] map, depending on whether [chainID] is present in the map. -func mergeAtomicOps(txs []*Tx) (map[ids.ID]*atomic.Requests, error) { - if len(txs) > 1 { - // txs should be stored in order of txID to ensure consistency - // with txs initialized from the txID index. - copyTxs := make([]*Tx, len(txs)) - copy(copyTxs, txs) - utils.Sort(copyTxs) - txs = copyTxs - } - output := make(map[ids.ID]*atomic.Requests) - for _, tx := range txs { - chainID, txRequests, err := tx.UnsignedAtomicTx.AtomicOps() - if err != nil { - return nil, err - } - mergeAtomicOpsToMap(output, chainID, txRequests) - } - return output, nil -} - -// mergeAtomicOps merges atomic ops for [chainID] represented by [requests] -// to the [output] map provided. -func mergeAtomicOpsToMap(output map[ids.ID]*atomic.Requests, chainID ids.ID, requests *atomic.Requests) { - if request, exists := output[chainID]; exists { - request.PutRequests = append(request.PutRequests, requests.PutRequests...) - request.RemoveRequests = append(request.RemoveRequests, requests.RemoveRequests...) - } else { - output[chainID] = requests - } -} diff --git a/plugin/evm/atomic_backend.go b/plugin/evm/atomic_backend.go index 5a84ac3748..2420021d6f 100644 --- a/plugin/evm/atomic_backend.go +++ b/plugin/evm/atomic_backend.go @@ -8,13 +8,15 @@ import ( "fmt" "time" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/wrappers" + "github.com/ava-labs/coreth/plugin/evm/atomic" syncclient "github.com/ava-labs/coreth/sync/client" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" @@ -32,7 +34,7 @@ type AtomicBackend interface { // and it's the caller's responsibility to call either Accept or Reject on // the AtomicState which can be retreived from GetVerifiedAtomicState to commit the // changes or abort them and free memory. - InsertTxs(blockHash common.Hash, blockHeight uint64, parentHash common.Hash, txs []*Tx) (common.Hash, error) + InsertTxs(blockHash common.Hash, blockHeight uint64, parentHash common.Hash, txs []*atomic.Tx) (common.Hash, error) // Returns an AtomicState corresponding to a block hash that has been inserted // but not Accepted or Rejected yet. @@ -73,7 +75,7 @@ type atomicBackend struct { bonusBlocks map[uint64]ids.ID // Map of height to blockID for blocks to skip indexing db *versiondb.Database // Underlying database metadataDB database.Database // Underlying database containing the atomic trie metadata - sharedMemory atomic.SharedMemory + sharedMemory avalancheatomic.SharedMemory repo AtomicTxRepository atomicTrie AtomicTrie @@ -84,7 +86,7 @@ type atomicBackend struct { // NewAtomicBackend creates an AtomicBackend from the specified dependencies func NewAtomicBackend( - db *versiondb.Database, sharedMemory atomic.SharedMemory, + db *versiondb.Database, sharedMemory avalancheatomic.SharedMemory, bonusBlocks map[uint64]ids.ID, repo AtomicTxRepository, lastAcceptedHeight uint64, lastAcceptedHash common.Hash, commitInterval uint64, ) (AtomicBackend, error) { @@ -150,7 +152,7 @@ func (a *atomicBackend) initialize(lastAcceptedHeight uint64) error { // iterate over the transactions, indexing them if the height is < commit height // otherwise, add the atomic operations from the transaction to the uncommittedOpsMap height = binary.BigEndian.Uint64(iter.Key()) - txs, err := ExtractAtomicTxs(iter.Value(), true, a.codec) + txs, err := atomic.ExtractAtomicTxs(iter.Value(), true, a.codec) if err != nil { return err } @@ -266,7 +268,7 @@ func (a *atomicBackend) ApplyToSharedMemory(lastAcceptedBlock uint64) error { it.Next() } - batchOps := make(map[ids.ID]*atomic.Requests) + batchOps := make(map[ids.ID]*avalancheatomic.Requests) for it.Next() { height := it.BlockNumber() if height > lastAcceptedBlock { @@ -318,7 +320,7 @@ func (a *atomicBackend) ApplyToSharedMemory(lastAcceptedBlock uint64) error { lastHeight = height lastBlockchainID = blockchainID putRequests, removeRequests = 0, 0 - batchOps = make(map[ids.ID]*atomic.Requests) + batchOps = make(map[ids.ID]*avalancheatomic.Requests) } } if err := it.Error(); err != nil { @@ -395,7 +397,7 @@ func (a *atomicBackend) SetLastAccepted(lastAcceptedHash common.Hash) { // and it's the caller's responsibility to call either Accept or Reject on // the AtomicState which can be retreived from GetVerifiedAtomicState to commit the // changes or abort them and free memory. -func (a *atomicBackend) InsertTxs(blockHash common.Hash, blockHeight uint64, parentHash common.Hash, txs []*Tx) (common.Hash, error) { +func (a *atomicBackend) InsertTxs(blockHash common.Hash, blockHeight uint64, parentHash common.Hash, txs []*atomic.Tx) (common.Hash, error) { // access the atomic trie at the parent block parentRoot, err := a.getAtomicRootAt(parentHash) if err != nil { @@ -455,3 +457,36 @@ func (a *atomicBackend) IsBonus(blockHeight uint64, blockHash common.Hash) bool func (a *atomicBackend) AtomicTrie() AtomicTrie { return a.atomicTrie } + +// mergeAtomicOps merges atomic requests represented by [txs] +// to the [output] map, depending on whether [chainID] is present in the map. +func mergeAtomicOps(txs []*atomic.Tx) (map[ids.ID]*avalancheatomic.Requests, error) { + if len(txs) > 1 { + // txs should be stored in order of txID to ensure consistency + // with txs initialized from the txID index. + copyTxs := make([]*atomic.Tx, len(txs)) + copy(copyTxs, txs) + utils.Sort(copyTxs) + txs = copyTxs + } + output := make(map[ids.ID]*avalancheatomic.Requests) + for _, tx := range txs { + chainID, txRequests, err := tx.UnsignedAtomicTx.AtomicOps() + if err != nil { + return nil, err + } + mergeAtomicOpsToMap(output, chainID, txRequests) + } + return output, nil +} + +// mergeAtomicOps merges atomic ops for [chainID] represented by [requests] +// to the [output] map provided. +func mergeAtomicOpsToMap(output map[ids.ID]*avalancheatomic.Requests, chainID ids.ID, requests *avalancheatomic.Requests) { + if request, exists := output[chainID]; exists { + request.PutRequests = append(request.PutRequests, requests.PutRequests...) + request.RemoveRequests = append(request.RemoveRequests, requests.RemoveRequests...) + } else { + output[chainID] = requests + } +} diff --git a/plugin/evm/atomic_state.go b/plugin/evm/atomic_state.go index 667e4c2517..911f1afb3a 100644 --- a/plugin/evm/atomic_state.go +++ b/plugin/evm/atomic_state.go @@ -6,9 +6,10 @@ package evm import ( "fmt" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" ) @@ -25,7 +26,7 @@ type AtomicState interface { Root() common.Hash // Accept applies the state change to VM's persistent storage // Changes are persisted atomically along with the provided [commitBatch]. - Accept(commitBatch database.Batch, requests map[ids.ID]*atomic.Requests) error + Accept(commitBatch database.Batch, requests map[ids.ID]*avalancheatomic.Requests) error // Reject frees memory associated with the state change. Reject() error } @@ -36,8 +37,8 @@ type atomicState struct { backend *atomicBackend blockHash common.Hash blockHeight uint64 - txs []*Tx - atomicOps map[ids.ID]*atomic.Requests + txs []*atomic.Tx + atomicOps map[ids.ID]*avalancheatomic.Requests atomicRoot common.Hash } @@ -46,7 +47,7 @@ func (a *atomicState) Root() common.Hash { } // Accept applies the state change to VM's persistent storage. -func (a *atomicState) Accept(commitBatch database.Batch, requests map[ids.ID]*atomic.Requests) error { +func (a *atomicState) Accept(commitBatch database.Batch, requests map[ids.ID]*avalancheatomic.Requests) error { // Add the new requests to the batch to be accepted for chainID, requests := range requests { mergeAtomicOpsToMap(a.atomicOps, chainID, requests) @@ -83,7 +84,7 @@ func (a *atomicState) Accept(commitBatch database.Batch, requests map[ids.ID]*at // to shared memory. if a.backend.IsBonus(a.blockHeight, a.blockHash) { log.Info("skipping atomic tx acceptance on bonus block", "block", a.blockHash) - return atomic.WriteAll(commitBatch, atomicChangesBatch) + return avalancheatomic.WriteAll(commitBatch, atomicChangesBatch) } // Otherwise, atomically commit pending changes in the version db with diff --git a/plugin/evm/atomic_trie.go b/plugin/evm/atomic_trie.go index 2760850d18..d734268e23 100644 --- a/plugin/evm/atomic_trie.go +++ b/plugin/evm/atomic_trie.go @@ -7,7 +7,7 @@ import ( "fmt" "time" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" @@ -17,6 +17,7 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/trie" "github.com/ava-labs/coreth/trie/trienode" "github.com/ava-labs/coreth/triedb" @@ -52,7 +53,7 @@ type AtomicTrie interface { OpenTrie(hash common.Hash) (*trie.Trie, error) // UpdateTrie updates [tr] to inlude atomicOps for height. - UpdateTrie(tr *trie.Trie, height uint64, atomicOps map[ids.ID]*atomic.Requests) error + UpdateTrie(tr *trie.Trie, height uint64, atomicOps map[ids.ID]*avalancheatomic.Requests) error // Iterator returns an AtomicTrieIterator to iterate the trie at the given // root hash starting at [cursor]. @@ -108,7 +109,7 @@ type AtomicTrieIterator interface { // AtomicOps returns a map of blockchainIDs to the set of atomic requests // for that blockchainID at the current block number - AtomicOps() *atomic.Requests + AtomicOps() *avalancheatomic.Requests // Error returns error, if any encountered during this iteration Error() error @@ -221,9 +222,9 @@ func (a *atomicTrie) commit(height uint64, root common.Hash) error { return a.updateLastCommitted(root, height) } -func (a *atomicTrie) UpdateTrie(trie *trie.Trie, height uint64, atomicOps map[ids.ID]*atomic.Requests) error { +func (a *atomicTrie) UpdateTrie(trie *trie.Trie, height uint64, atomicOps map[ids.ID]*avalancheatomic.Requests) error { for blockchainID, requests := range atomicOps { - valueBytes, err := a.codec.Marshal(codecVersion, requests) + valueBytes, err := a.codec.Marshal(atomic.CodecVersion, requests) if err != nil { // highly unlikely but possible if atomic.Element // has a change that is unsupported by the codec diff --git a/plugin/evm/atomic_trie_test.go b/plugin/evm/atomic_trie_test.go index 5334c87101..193226f588 100644 --- a/plugin/evm/atomic_trie_test.go +++ b/plugin/evm/atomic_trie_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/leveldb" "github.com/ava-labs/avalanchego/database/memdb" @@ -19,24 +19,25 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/wrappers" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ethereum/go-ethereum/common" ) const testCommitInterval = 100 -func (tx *Tx) mustAtomicOps() map[ids.ID]*atomic.Requests { +func mustAtomicOps(tx *atomic.Tx) map[ids.ID]*avalancheatomic.Requests { id, reqs, err := tx.AtomicOps() if err != nil { panic(err) } - return map[ids.ID]*atomic.Requests{id: reqs} + return map[ids.ID]*avalancheatomic.Requests{id: reqs} } // indexAtomicTxs updates [tr] with entries in [atomicOps] at height by creating // a new snapshot, calculating a new root, and calling InsertTrie followed // by AcceptTrie on the new root. -func indexAtomicTxs(tr AtomicTrie, height uint64, atomicOps map[ids.ID]*atomic.Requests) error { +func indexAtomicTxs(tr AtomicTrie, height uint64, atomicOps map[ids.ID]*avalancheatomic.Requests) error { snapshot, err := tr.OpenTrie(tr.LastAcceptedRoot()) if err != nil { return err @@ -143,7 +144,7 @@ func TestAtomicTrieInitialize(t *testing.T) { if err != nil { t.Fatal(err) } - operationsMap := make(map[uint64]map[ids.ID]*atomic.Requests) + operationsMap := make(map[uint64]map[ids.ID]*avalancheatomic.Requests) writeTxs(t, repo, 1, test.lastAcceptedHeight+1, test.numTxsPerBlock, nil, operationsMap) // Construct the atomic trie for the first time @@ -230,7 +231,7 @@ func TestIndexerInitializesOnlyOnce(t *testing.T) { codec := testTxCodec() repo, err := NewAtomicTxRepository(db, codec, lastAcceptedHeight) assert.NoError(t, err) - operationsMap := make(map[uint64]map[ids.ID]*atomic.Requests) + operationsMap := make(map[uint64]map[ids.ID]*avalancheatomic.Requests) writeTxs(t, repo, 1, lastAcceptedHeight+1, constTxsPerHeight(2), nil, operationsMap) // Initialize atomic repository @@ -246,7 +247,7 @@ func TestIndexerInitializesOnlyOnce(t *testing.T) { // re-initialize the atomic trie since initialize is not supposed to run again the height // at the trie should still be the old height with the old commit hash without any changes. // This scenario is not realistic, but is used to test potential double initialization behavior. - err = repo.Write(15, []*Tx{testDataExportTx()}) + err = repo.Write(15, []*atomic.Tx{testDataExportTx()}) assert.NoError(t, err) // Re-initialize the atomic trie @@ -281,7 +282,7 @@ func TestIndexerWriteAndRead(t *testing.T) { // process 305 blocks so that we get three commits (100, 200, 300) for height := uint64(1); height <= testCommitInterval*3+5; /*=305*/ height++ { - atomicRequests := testDataImportTx().mustAtomicOps() + atomicRequests := mustAtomicOps(testDataImportTx()) err := indexAtomicTxs(atomicTrie, height, atomicRequests) assert.NoError(t, err) if height%testCommitInterval == 0 { @@ -314,9 +315,9 @@ func TestAtomicOpsAreNotTxOrderDependent(t *testing.T) { for height := uint64(0); height <= testCommitInterval; /*=205*/ height++ { tx1 := testDataImportTx() tx2 := testDataImportTx() - atomicRequests1, err := mergeAtomicOps([]*Tx{tx1, tx2}) + atomicRequests1, err := mergeAtomicOps([]*atomic.Tx{tx1, tx2}) assert.NoError(t, err) - atomicRequests2, err := mergeAtomicOps([]*Tx{tx2, tx1}) + atomicRequests2, err := mergeAtomicOps([]*atomic.Tx{tx2, tx1}) assert.NoError(t, err) err = indexAtomicTxs(atomicTrie1, height, atomicRequests1) @@ -343,7 +344,7 @@ func TestAtomicTrieDoesNotSkipBonusBlocks(t *testing.T) { if err != nil { t.Fatal(err) } - operationsMap := make(map[uint64]map[ids.ID]*atomic.Requests) + operationsMap := make(map[uint64]map[ids.ID]*avalancheatomic.Requests) writeTxs(t, repo, 1, lastAcceptedHeight, constTxsPerHeight(numTxsPerBlock), nil, operationsMap) bonusBlocks := map[uint64]ids.ID{ @@ -368,9 +369,9 @@ func TestAtomicTrieDoesNotSkipBonusBlocks(t *testing.T) { func TestIndexingNilShouldNotImpactTrie(t *testing.T) { // operations to index - ops := make([]map[ids.ID]*atomic.Requests, 0) + ops := make([]map[ids.ID]*avalancheatomic.Requests, 0) for i := 0; i <= testCommitInterval; i++ { - ops = append(ops, testDataImportTx().mustAtomicOps()) + ops = append(ops, mustAtomicOps(testDataImportTx())) } // without nils @@ -411,19 +412,19 @@ func TestIndexingNilShouldNotImpactTrie(t *testing.T) { } type sharedMemories struct { - thisChain atomic.SharedMemory - peerChain atomic.SharedMemory + thisChain avalancheatomic.SharedMemory + peerChain avalancheatomic.SharedMemory thisChainID ids.ID peerChainID ids.ID } -func (s *sharedMemories) addItemsToBeRemovedToPeerChain(ops map[ids.ID]*atomic.Requests) error { +func (s *sharedMemories) addItemsToBeRemovedToPeerChain(ops map[ids.ID]*avalancheatomic.Requests) error { for _, reqs := range ops { - puts := make(map[ids.ID]*atomic.Requests) - puts[s.thisChainID] = &atomic.Requests{} + puts := make(map[ids.ID]*avalancheatomic.Requests) + puts[s.thisChainID] = &avalancheatomic.Requests{} for _, key := range reqs.RemoveRequests { val := []byte{0x1} - puts[s.thisChainID].PutRequests = append(puts[s.thisChainID].PutRequests, &atomic.Element{Key: key, Value: val}) + puts[s.thisChainID].PutRequests = append(puts[s.thisChainID].PutRequests, &avalancheatomic.Element{Key: key, Value: val}) } if err := s.peerChain.Apply(puts); err != nil { return err @@ -432,7 +433,7 @@ func (s *sharedMemories) addItemsToBeRemovedToPeerChain(ops map[ids.ID]*atomic.R return nil } -func (s *sharedMemories) assertOpsApplied(t *testing.T, ops map[ids.ID]*atomic.Requests) { +func (s *sharedMemories) assertOpsApplied(t *testing.T, ops map[ids.ID]*avalancheatomic.Requests) { t.Helper() for _, reqs := range ops { // should be able to get put requests @@ -452,7 +453,7 @@ func (s *sharedMemories) assertOpsApplied(t *testing.T, ops map[ids.ID]*atomic.R } } -func (s *sharedMemories) assertOpsNotApplied(t *testing.T, ops map[ids.ID]*atomic.Requests) { +func (s *sharedMemories) assertOpsNotApplied(t *testing.T, ops map[ids.ID]*avalancheatomic.Requests) { t.Helper() for _, reqs := range ops { // should not be able to get put requests @@ -470,7 +471,7 @@ func (s *sharedMemories) assertOpsNotApplied(t *testing.T, ops map[ids.ID]*atomi } } -func newSharedMemories(atomicMemory *atomic.Memory, thisChainID, peerChainID ids.ID) *sharedMemories { +func newSharedMemories(atomicMemory *avalancheatomic.Memory, thisChainID, peerChainID ids.ID) *sharedMemories { return &sharedMemories{ thisChain: atomicMemory.NewSharedMemory(thisChainID), peerChain: atomicMemory.NewSharedMemory(peerChainID), @@ -529,11 +530,11 @@ func TestApplyToSharedMemory(t *testing.T) { codec := testTxCodec() repo, err := NewAtomicTxRepository(db, codec, test.lastAcceptedHeight) assert.NoError(t, err) - operationsMap := make(map[uint64]map[ids.ID]*atomic.Requests) + operationsMap := make(map[uint64]map[ids.ID]*avalancheatomic.Requests) writeTxs(t, repo, 1, test.lastAcceptedHeight+1, constTxsPerHeight(2), nil, operationsMap) // Initialize atomic repository - m := atomic.NewMemory(db) + m := avalancheatomic.NewMemory(db) sharedMemories := newSharedMemories(m, testCChainID, blockChainID) backend, err := NewAtomicBackend(db, sharedMemories.thisChain, test.bonusBlockHeights, repo, test.lastAcceptedHeight, common.Hash{}, test.commitInterval) assert.NoError(t, err) @@ -594,7 +595,7 @@ func BenchmarkAtomicTrieInit(b *testing.B) { db := versiondb.New(memdb.New()) codec := testTxCodec() - operationsMap := make(map[uint64]map[ids.ID]*atomic.Requests) + operationsMap := make(map[uint64]map[ids.ID]*avalancheatomic.Requests) lastAcceptedHeight := uint64(25000) // add 25000 * 3 = 75000 transactions @@ -629,7 +630,7 @@ func BenchmarkAtomicTrieIterate(b *testing.B) { db := versiondb.New(memdb.New()) codec := testTxCodec() - operationsMap := make(map[uint64]map[ids.ID]*atomic.Requests) + operationsMap := make(map[uint64]map[ids.ID]*avalancheatomic.Requests) lastAcceptedHeight := uint64(25_000) // add 25000 * 3 = 75000 transactions diff --git a/plugin/evm/atomic_tx_repository.go b/plugin/evm/atomic_tx_repository.go index 4ee44576fe..d1074f60f2 100644 --- a/plugin/evm/atomic_tx_repository.go +++ b/plugin/evm/atomic_tx_repository.go @@ -19,6 +19,7 @@ import ( "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/utils/wrappers" + "github.com/ava-labs/coreth/plugin/evm/atomic" ) const ( @@ -39,10 +40,10 @@ var ( // atomic transactions type AtomicTxRepository interface { GetIndexHeight() (uint64, error) - GetByTxID(txID ids.ID) (*Tx, uint64, error) - GetByHeight(height uint64) ([]*Tx, error) - Write(height uint64, txs []*Tx) error - WriteBonus(height uint64, txs []*Tx) error + GetByTxID(txID ids.ID) (*atomic.Tx, uint64, error) + GetByHeight(height uint64) ([]*atomic.Tx, error) + Write(height uint64, txs []*atomic.Tx) error + WriteBonus(height uint64, txs []*atomic.Tx) error IterateByHeight(start uint64) database.Iterator Codec() codec.Manager @@ -136,7 +137,7 @@ func (a *atomicTxRepository) initializeHeightIndex(lastAcceptedHeight uint64) er // Get the tx iter is pointing to, len(txs) == 1 is expected here. txBytes := iterValue[wrappers.LongLen+wrappers.IntLen:] - tx, err := ExtractAtomicTx(txBytes, a.codec) + tx, err := atomic.ExtractAtomicTx(txBytes, a.codec) if err != nil { return err } @@ -198,10 +199,10 @@ func (a *atomicTxRepository) GetIndexHeight() (uint64, error) { return indexHeight, nil } -// GetByTxID queries [acceptedAtomicTxDB] for the [txID], parses a [*Tx] object +// GetByTxID queries [acceptedAtomicTxDB] for the [txID], parses a [*atomic.Tx] object // if an entry is found, and returns it with the block height the atomic tx it // represents was accepted on, along with an optional error. -func (a *atomicTxRepository) GetByTxID(txID ids.ID) (*Tx, uint64, error) { +func (a *atomicTxRepository) GetByTxID(txID ids.ID) (*atomic.Tx, uint64, error) { indexedTxBytes, err := a.acceptedAtomicTxDB.Get(txID[:]) if err != nil { return nil, 0, err @@ -215,7 +216,7 @@ func (a *atomicTxRepository) GetByTxID(txID ids.ID) (*Tx, uint64, error) { packer := wrappers.Packer{Bytes: indexedTxBytes} height := packer.UnpackLong() txBytes := packer.UnpackBytes() - tx, err := ExtractAtomicTx(txBytes, a.codec) + tx, err := atomic.ExtractAtomicTx(txBytes, a.codec) if err != nil { return nil, 0, err } @@ -229,40 +230,40 @@ func (a *atomicTxRepository) GetByTxID(txID ids.ID) (*Tx, uint64, error) { // no atomic transactions in the block accepted at [height]. // If [height] is greater than the last accepted height, then this will always return // [database.ErrNotFound] -func (a *atomicTxRepository) GetByHeight(height uint64) ([]*Tx, error) { +func (a *atomicTxRepository) GetByHeight(height uint64) ([]*atomic.Tx, error) { heightBytes := make([]byte, wrappers.LongLen) binary.BigEndian.PutUint64(heightBytes, height) return a.getByHeightBytes(heightBytes) } -func (a *atomicTxRepository) getByHeightBytes(heightBytes []byte) ([]*Tx, error) { +func (a *atomicTxRepository) getByHeightBytes(heightBytes []byte) ([]*atomic.Tx, error) { txsBytes, err := a.acceptedAtomicTxByHeightDB.Get(heightBytes) if err != nil { return nil, err } - return ExtractAtomicTxsBatch(txsBytes, a.codec) + return atomic.ExtractAtomicTxsBatch(txsBytes, a.codec) } // Write updates indexes maintained on atomic txs, so they can be queried // by txID or height. This method must be called only once per height, // and [txs] must include all atomic txs for the block accepted at the // corresponding height. -func (a *atomicTxRepository) Write(height uint64, txs []*Tx) error { +func (a *atomicTxRepository) Write(height uint64, txs []*atomic.Tx) error { return a.write(height, txs, false) } // WriteBonus is similar to Write, except the [txID] => [height] is not // overwritten if already exists. -func (a *atomicTxRepository) WriteBonus(height uint64, txs []*Tx) error { +func (a *atomicTxRepository) WriteBonus(height uint64, txs []*atomic.Tx) error { return a.write(height, txs, true) } -func (a *atomicTxRepository) write(height uint64, txs []*Tx, bonus bool) error { +func (a *atomicTxRepository) write(height uint64, txs []*atomic.Tx, bonus bool) error { if len(txs) > 1 { // txs should be stored in order of txID to ensure consistency // with txs initialized from the txID index. - copyTxs := make([]*Tx, len(txs)) + copyTxs := make([]*atomic.Tx, len(txs)) copy(copyTxs, txs) utils.Sort(copyTxs) txs = copyTxs @@ -300,8 +301,8 @@ func (a *atomicTxRepository) write(height uint64, txs []*Tx, bonus bool) error { // indexTxByID writes [tx] into the [acceptedAtomicTxDB] stored as // [height] + [tx bytes] -func (a *atomicTxRepository) indexTxByID(heightBytes []byte, tx *Tx) error { - txBytes, err := a.codec.Marshal(codecVersion, tx) +func (a *atomicTxRepository) indexTxByID(heightBytes []byte, tx *atomic.Tx) error { + txBytes, err := a.codec.Marshal(atomic.CodecVersion, tx) if err != nil { return err } @@ -320,8 +321,8 @@ func (a *atomicTxRepository) indexTxByID(heightBytes []byte, tx *Tx) error { } // indexTxsAtHeight adds [height] -> [txs] to the [acceptedAtomicTxByHeightDB] -func (a *atomicTxRepository) indexTxsAtHeight(heightBytes []byte, txs []*Tx) error { - txsBytes, err := a.codec.Marshal(codecVersion, txs) +func (a *atomicTxRepository) indexTxsAtHeight(heightBytes []byte, txs []*atomic.Tx) error { + txsBytes, err := a.codec.Marshal(atomic.CodecVersion, txs) if err != nil { return err } @@ -335,7 +336,7 @@ func (a *atomicTxRepository) indexTxsAtHeight(heightBytes []byte, txs []*Tx) err // [tx] to the slice of transactions stored there. // This function is used while initializing the atomic repository to re-index the atomic transactions // by txID into the height -> txs index. -func (a *atomicTxRepository) appendTxToHeightIndex(heightBytes []byte, tx *Tx) error { +func (a *atomicTxRepository) appendTxToHeightIndex(heightBytes []byte, tx *atomic.Tx) error { txs, err := a.getByHeightBytes(heightBytes) if err != nil && err != database.ErrNotFound { return err diff --git a/plugin/evm/atomic_tx_repository_test.go b/plugin/evm/atomic_tx_repository_test.go index b52860d57d..091bcd8f56 100644 --- a/plugin/evm/atomic_tx_repository_test.go +++ b/plugin/evm/atomic_tx_repository_test.go @@ -7,11 +7,12 @@ import ( "encoding/binary" "testing" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/utils" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ethereum/go-ethereum/common" "github.com/ava-labs/avalanchego/codec" @@ -27,13 +28,13 @@ import ( // addTxs writes [txsPerHeight] txs for heights ranging in [fromHeight, toHeight) directly to [acceptedAtomicTxDB], // storing the resulting transactions in [txMap] if non-nil and the resulting atomic operations in [operationsMap] // if non-nil. -func addTxs(t testing.TB, codec codec.Manager, acceptedAtomicTxDB database.Database, fromHeight uint64, toHeight uint64, txsPerHeight int, txMap map[uint64][]*Tx, operationsMap map[uint64]map[ids.ID]*atomic.Requests) { +func addTxs(t testing.TB, codec codec.Manager, acceptedAtomicTxDB database.Database, fromHeight uint64, toHeight uint64, txsPerHeight int, txMap map[uint64][]*atomic.Tx, operationsMap map[uint64]map[ids.ID]*avalancheatomic.Requests) { for height := fromHeight; height < toHeight; height++ { - txs := make([]*Tx, 0, txsPerHeight) + txs := make([]*atomic.Tx, 0, txsPerHeight) for i := 0; i < txsPerHeight; i++ { tx := newTestTx() txs = append(txs, tx) - txBytes, err := codec.Marshal(codecVersion, tx) + txBytes, err := codec.Marshal(atomic.CodecVersion, tx) assert.NoError(t, err) // Write atomic transactions to the [acceptedAtomicTxDB] @@ -70,7 +71,7 @@ func constTxsPerHeight(txCount int) func(uint64) int { // storing the resulting transactions in [txMap] if non-nil and the resulting atomic operations in [operationsMap] // if non-nil. func writeTxs(t testing.TB, repo AtomicTxRepository, fromHeight uint64, toHeight uint64, - txsPerHeight func(height uint64) int, txMap map[uint64][]*Tx, operationsMap map[uint64]map[ids.ID]*atomic.Requests, + txsPerHeight func(height uint64) int, txMap map[uint64][]*atomic.Tx, operationsMap map[uint64]map[ids.ID]*avalancheatomic.Requests, ) { for height := fromHeight; height < toHeight; height++ { txs := newTestTxs(txsPerHeight(height)) @@ -95,7 +96,7 @@ func writeTxs(t testing.TB, repo AtomicTxRepository, fromHeight uint64, toHeight } // verifyTxs asserts [repo] can find all txs in [txMap] by height and txID -func verifyTxs(t testing.TB, repo AtomicTxRepository, txMap map[uint64][]*Tx) { +func verifyTxs(t testing.TB, repo AtomicTxRepository, txMap map[uint64][]*atomic.Tx) { // We should be able to fetch indexed txs by height: for height, expectedTxs := range txMap { txs, err := repo.GetByHeight(height) @@ -115,7 +116,7 @@ func verifyTxs(t testing.TB, repo AtomicTxRepository, txMap map[uint64][]*Tx) { // verifyOperations creates an iterator over the atomicTrie at [rootHash] and verifies that the all of the operations in the trie in the interval [from, to] are identical to // the atomic operations contained in [operationsMap] on the same interval. -func verifyOperations(t testing.TB, atomicTrie AtomicTrie, codec codec.Manager, rootHash common.Hash, from, to uint64, operationsMap map[uint64]map[ids.ID]*atomic.Requests) { +func verifyOperations(t testing.TB, atomicTrie AtomicTrie, codec codec.Manager, rootHash common.Hash, from, to uint64, operationsMap map[uint64]map[ids.ID]*avalancheatomic.Requests) { t.Helper() // Start the iterator at [from] @@ -187,7 +188,7 @@ func TestAtomicRepositoryReadWriteSingleTx(t *testing.T) { if err != nil { t.Fatal(err) } - txMap := make(map[uint64][]*Tx) + txMap := make(map[uint64][]*atomic.Tx) writeTxs(t, repo, 1, 100, constTxsPerHeight(1), txMap, nil) verifyTxs(t, repo, txMap) @@ -200,7 +201,7 @@ func TestAtomicRepositoryReadWriteMultipleTxs(t *testing.T) { if err != nil { t.Fatal(err) } - txMap := make(map[uint64][]*Tx) + txMap := make(map[uint64][]*atomic.Tx) writeTxs(t, repo, 1, 100, constTxsPerHeight(10), txMap, nil) verifyTxs(t, repo, txMap) @@ -211,7 +212,7 @@ func TestAtomicRepositoryPreAP5Migration(t *testing.T) { codec := testTxCodec() acceptedAtomicTxDB := prefixdb.New(atomicTxIDDBPrefix, db) - txMap := make(map[uint64][]*Tx) + txMap := make(map[uint64][]*atomic.Tx) addTxs(t, codec, acceptedAtomicTxDB, 1, 100, 1, txMap, nil) if err := db.Commit(); err != nil { t.Fatal(err) @@ -236,7 +237,7 @@ func TestAtomicRepositoryPostAP5Migration(t *testing.T) { codec := testTxCodec() acceptedAtomicTxDB := prefixdb.New(atomicTxIDDBPrefix, db) - txMap := make(map[uint64][]*Tx) + txMap := make(map[uint64][]*atomic.Tx) addTxs(t, codec, acceptedAtomicTxDB, 1, 100, 1, txMap, nil) addTxs(t, codec, acceptedAtomicTxDB, 100, 200, 10, txMap, nil) if err := db.Commit(); err != nil { @@ -261,7 +262,7 @@ func benchAtomicRepositoryIndex10_000(b *testing.B, maxHeight uint64, txsPerHeig codec := testTxCodec() acceptedAtomicTxDB := prefixdb.New(atomicTxIDDBPrefix, db) - txMap := make(map[uint64][]*Tx) + txMap := make(map[uint64][]*atomic.Tx) addTxs(b, codec, acceptedAtomicTxDB, 0, maxHeight, txsPerHeight, txMap, nil) if err := db.Commit(); err != nil { diff --git a/plugin/evm/block.go b/plugin/evm/block.go index a8d9084464..99451cb071 100644 --- a/plugin/evm/block.go +++ b/plugin/evm/block.go @@ -18,6 +18,7 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/predicate" @@ -31,9 +32,7 @@ var ( _ block.WithVerifyContext = (*Block)(nil) ) -var ( - errMissingUTXOs = errors.New("missing UTXOs") -) +var errMissingUTXOs = errors.New("missing UTXOs") // readMainnetBonusBlocks returns maps of bonus block numbers to block IDs. // Note bonus blocks are indexed in the atomic trie. @@ -114,13 +113,13 @@ type Block struct { id ids.ID ethBlock *types.Block vm *VM - atomicTxs []*Tx + atomicTxs []*atomic.Tx } // newBlock returns a new Block wrapping the ethBlock type and implementing the snowman.Block interface func (vm *VM) newBlock(ethBlock *types.Block) (*Block, error) { isApricotPhase5 := vm.chainConfig.IsApricotPhase5(ethBlock.Time()) - atomicTxs, err := ExtractAtomicTxs(ethBlock.ExtData(), isApricotPhase5, vm.codec) + atomicTxs, err := atomic.ExtractAtomicTxs(ethBlock.ExtData(), isApricotPhase5, atomic.Codec) if err != nil { return nil, err } @@ -136,6 +135,8 @@ func (vm *VM) newBlock(ethBlock *types.Block) (*Block, error) { // ID implements the snowman.Block interface func (b *Block) ID() ids.ID { return b.id } +func (b *Block) AtomicTxs() []*atomic.Tx { return b.atomicTxs } + // Accept implements the snowman.Block interface func (b *Block) Accept(context.Context) error { vm := b.vm diff --git a/plugin/evm/client.go b/plugin/evm/client/client.go similarity index 78% rename from plugin/evm/client.go rename to plugin/evm/client/client.go index 4701c22b9c..ddf05184d7 100644 --- a/plugin/evm/client.go +++ b/plugin/evm/client/client.go @@ -1,13 +1,15 @@ // (c) 2019-2020, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package client import ( "context" + "errors" "fmt" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" "golang.org/x/exp/slog" "github.com/ava-labs/avalanchego/api" @@ -17,15 +19,18 @@ import ( "github.com/ava-labs/avalanchego/utils/formatting/address" "github.com/ava-labs/avalanchego/utils/json" "github.com/ava-labs/avalanchego/utils/rpc" + "github.com/ava-labs/coreth/plugin/evm/atomic" ) // Interface compliance var _ Client = (*client)(nil) +var errInvalidAddr = errors.New("invalid hex address") + // Client interface for interacting with EVM [chain] type Client interface { IssueTx(ctx context.Context, txBytes []byte, options ...rpc.Option) (ids.ID, error) - GetAtomicTxStatus(ctx context.Context, txID ids.ID, options ...rpc.Option) (Status, error) + GetAtomicTxStatus(ctx context.Context, txID ids.ID, options ...rpc.Option) (atomic.Status, error) GetAtomicTx(ctx context.Context, txID ids.ID, options ...rpc.Option) ([]byte, error) GetAtomicUTXOs(ctx context.Context, addrs []ids.ShortID, sourceChain string, limit uint32, startAddress ids.ShortID, startUTXOID ids.ID, options ...rpc.Option) ([][]byte, ids.ShortID, ids.ID, error) ExportKey(ctx context.Context, userPass api.UserPass, addr common.Address, options ...rpc.Option) (*secp256k1.PrivateKey, string, error) @@ -38,7 +43,7 @@ type Client interface { MemoryProfile(ctx context.Context, options ...rpc.Option) error LockProfile(ctx context.Context, options ...rpc.Option) error SetLogLevel(ctx context.Context, level slog.Level, options ...rpc.Option) error - GetVMConfig(ctx context.Context, options ...rpc.Option) (*Config, error) + // GetVMConfig(ctx context.Context, options ...rpc.Option) (*Config, error) } // Client implementation for interacting with EVM [chain] @@ -74,8 +79,14 @@ func (c *client) IssueTx(ctx context.Context, txBytes []byte, options ...rpc.Opt return res.TxID, err } +// GetAtomicTxStatusReply defines the GetAtomicTxStatus replies returned from the API +type GetAtomicTxStatusReply struct { + Status atomic.Status `json:"status"` + BlockHeight *json.Uint64 `json:"blockHeight,omitempty"` +} + // GetAtomicTxStatus returns the status of [txID] -func (c *client) GetAtomicTxStatus(ctx context.Context, txID ids.ID, options ...rpc.Option) (Status, error) { +func (c *client) GetAtomicTxStatus(ctx context.Context, txID ids.ID, options ...rpc.Option) (atomic.Status, error) { res := &GetAtomicTxStatusReply{} err := c.requester.SendRequest(ctx, "avax.getAtomicTxStatus", &api.JSONTxID{ TxID: txID, @@ -131,6 +142,19 @@ func (c *client) GetAtomicUTXOs(ctx context.Context, addrs []ids.ShortID, source return utxos, endAddr, endUTXOID, err } +// ExportKeyArgs are arguments for ExportKey +type ExportKeyArgs struct { + api.UserPass + Address string `json:"address"` +} + +// ExportKeyReply is the response for ExportKey +type ExportKeyReply struct { + // The decrypted PrivateKey for the Address provided in the arguments + PrivateKey *secp256k1.PrivateKey `json:"privateKey"` + PrivateKeyHex string `json:"privateKeyHex"` +} + // ExportKey returns the private key corresponding to [addr] controlled by [user] // in both Avalanche standard format and hex format func (c *client) ExportKey(ctx context.Context, user api.UserPass, addr common.Address, options ...rpc.Option) (*secp256k1.PrivateKey, string, error) { @@ -142,6 +166,12 @@ func (c *client) ExportKey(ctx context.Context, user api.UserPass, addr common.A return res.PrivateKey, res.PrivateKeyHex, err } +// ImportKeyArgs are arguments for ImportKey +type ImportKeyArgs struct { + api.UserPass + PrivateKey *secp256k1.PrivateKey `json:"privateKey"` +} + // ImportKey imports [privateKey] to [user] func (c *client) ImportKey(ctx context.Context, user api.UserPass, privateKey *secp256k1.PrivateKey, options ...rpc.Option) (common.Address, error) { res := &api.JSONAddress{} @@ -155,6 +185,20 @@ func (c *client) ImportKey(ctx context.Context, user api.UserPass, privateKey *s return ParseEthAddress(res.Address) } +// ImportArgs are arguments for passing into Import requests +type ImportArgs struct { + api.UserPass + + // Fee that should be used when creating the tx + BaseFee *hexutil.Big `json:"baseFee"` + + // Chain the funds are coming from + SourceChain string `json:"sourceChain"` + + // The address that will receive the imported funds + To common.Address `json:"to"` +} + // Import sends an import transaction to import funds from [sourceChain] and // returns the ID of the newly created transaction func (c *client) Import(ctx context.Context, user api.UserPass, to common.Address, sourceChain string, options ...rpc.Option) (ids.ID, error) { @@ -180,6 +224,32 @@ func (c *client) ExportAVAX( return c.Export(ctx, user, amount, to, targetChain, "AVAX", options...) } +// ExportAVAXArgs are the arguments to ExportAVAX +type ExportAVAXArgs struct { + api.UserPass + + // Fee that should be used when creating the tx + BaseFee *hexutil.Big `json:"baseFee"` + + // Amount of asset to send + Amount json.Uint64 `json:"amount"` + + // Chain the funds are going to. Optional. Used if To address does not + // include the chainID. + TargetChain string `json:"targetChain"` + + // ID of the address that will receive the AVAX. This address may include + // the chainID, which is used to determine what the destination chain is. + To string `json:"to"` +} + +// ExportArgs are the arguments to Export +type ExportArgs struct { + ExportAVAXArgs + // AssetID of the tokens + AssetID string `json:"assetID"` +} + // Export sends an asset from this chain to the P/C-Chain. // After this tx is accepted, the AVAX must be imported to the P/C-chain with an importTx. // Returns the ID of the newly created atomic transaction @@ -221,6 +291,10 @@ func (c *client) LockProfile(ctx context.Context, options ...rpc.Option) error { return c.adminRequester.SendRequest(ctx, "admin.lockProfile", struct{}{}, &api.EmptyReply{}, options...) } +type SetLogLevelArgs struct { + Level string `json:"level"` +} + // SetLogLevel dynamically sets the log level for the C Chain func (c *client) SetLogLevel(ctx context.Context, level slog.Level, options ...rpc.Option) error { return c.adminRequester.SendRequest(ctx, "admin.setLogLevel", &SetLogLevelArgs{ @@ -229,8 +303,8 @@ func (c *client) SetLogLevel(ctx context.Context, level slog.Level, options ...r } // GetVMConfig returns the current config of the VM -func (c *client) GetVMConfig(ctx context.Context, options ...rpc.Option) (*Config, error) { - res := &ConfigReply{} - err := c.adminRequester.SendRequest(ctx, "admin.getVMConfig", struct{}{}, res, options...) - return res.Config, err -} +// func (c *client) GetVMConfig(ctx context.Context, options ...rpc.Option) (*Config, error) { +// res := &ConfigReply{} +// err := c.adminRequester.SendRequest(ctx, "admin.getVMConfig", struct{}{}, res, options...) +// return res.Config, err +// } diff --git a/plugin/evm/client_interface_test.go b/plugin/evm/client/client_interface_test.go similarity index 97% rename from plugin/evm/client_interface_test.go rename to plugin/evm/client/client_interface_test.go index d88c4926b4..332bb8bcf4 100644 --- a/plugin/evm/client_interface_test.go +++ b/plugin/evm/client/client_interface_test.go @@ -1,4 +1,4 @@ -package evm +package client import ( "reflect" diff --git a/plugin/evm/client/utils.go b/plugin/evm/client/utils.go new file mode 100644 index 0000000000..5ea43f4a20 --- /dev/null +++ b/plugin/evm/client/utils.go @@ -0,0 +1,13 @@ +// (c) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package client + +import "github.com/ethereum/go-ethereum/common" + +func ParseEthAddress(addrStr string) (common.Address, error) { + if !common.IsHexAddress(addrStr) { + return common.Address{}, errInvalidAddr + } + return common.HexToAddress(addrStr), nil +} diff --git a/plugin/evm/export_tx_test.go b/plugin/evm/export_tx_test.go index d8a7fed80f..eabbb05ede 100644 --- a/plugin/evm/export_tx_test.go +++ b/plugin/evm/export_tx_test.go @@ -9,7 +9,7 @@ import ( "math/big" "testing" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/ids" engCommon "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/utils/constants" @@ -18,13 +18,14 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ethereum/go-ethereum/common" "github.com/holiman/uint256" ) // createExportTxOptions adds funds to shared memory, imports them, and returns a list of export transactions // that attempt to send the funds to each of the test keys (list of length 3). -func createExportTxOptions(t *testing.T, vm *VM, issuer chan engCommon.Message, sharedMemory *atomic.Memory) []*Tx { +func createExportTxOptions(t *testing.T, vm *VM, issuer chan engCommon.Message, sharedMemory *avalancheatomic.Memory) []*atomic.Tx { // Add a UTXO to shared memory utxo := &avax.UTXO{ UTXOID: avax.UTXOID{TxID: ids.GenerateTestID()}, @@ -33,22 +34,22 @@ func createExportTxOptions(t *testing.T, vm *VM, issuer chan engCommon.Message, Amt: uint64(50000000), OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{testKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{testKeys[0].Address()}, }, }, } - utxoBytes, err := vm.codec.Marshal(codecVersion, utxo) + utxoBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, utxo) if err != nil { t.Fatal(err) } xChainSharedMemory := sharedMemory.NewSharedMemory(vm.ctx.XChainID) inputID := utxo.InputID() - if err := xChainSharedMemory.Apply(map[ids.ID]*atomic.Requests{vm.ctx.ChainID: {PutRequests: []*atomic.Element{{ + if err := xChainSharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{vm.ctx.ChainID: {PutRequests: []*avalancheatomic.Element{{ Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ - testKeys[0].PublicKey().Address().Bytes(), + testKeys[0].Address().Bytes(), }, }}}}); err != nil { t.Fatal(err) @@ -84,9 +85,13 @@ func createExportTxOptions(t *testing.T, vm *VM, issuer chan engCommon.Message, } // Use the funds to create 3 conflicting export transactions sending the funds to each of the test addresses - exportTxs := make([]*Tx, 0, 3) + exportTxs := make([]*atomic.Tx, 0, 3) + state, err := vm.blockChain.State() + if err != nil { + t.Fatal(err) + } for _, addr := range testShortIDAddrs { - exportTx, err := vm.newExportTx(vm.ctx.AVAXAssetID, uint64(5000000), vm.ctx.XChainID, addr, initialBaseFee, []*secp256k1.PrivateKey{testKeys[0]}) + exportTx, err := atomic.NewExportTx(vm.ctx, vm.currentRules(), state, vm.ctx.AVAXAssetID, uint64(5000000), vm.ctx.XChainID, addr, initialBaseFee, []*secp256k1.PrivateKey{testKeys[0]}) if err != nil { t.Fatal(err) } @@ -98,8 +103,8 @@ func createExportTxOptions(t *testing.T, vm *VM, issuer chan engCommon.Message, func TestExportTxEVMStateTransfer(t *testing.T) { key := testKeys[0] - addr := key.PublicKey().Address() - ethAddr := GetEthAddress(key) + addr := key.Address() + ethAddr := key.EthAddress() avaxAmount := 50 * units.MilliAvax avaxUTXOID := avax.UTXOID{ @@ -128,7 +133,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { tests := []struct { name string - tx []EVMInput + tx []atomic.EVMInput avaxBalance *uint256.Int balances map[ids.ID]*big.Int expectedNonce uint64 @@ -137,7 +142,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { { name: "no transfers", tx: nil, - avaxBalance: uint256.NewInt(avaxAmount * x2cRateUint64), + avaxBalance: uint256.NewInt(avaxAmount * atomic.X2CRateUint64), balances: map[ids.ID]*big.Int{ customAssetID: big.NewInt(int64(customAmount)), }, @@ -146,7 +151,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { }, { name: "spend half AVAX", - tx: []EVMInput{ + tx: []atomic.EVMInput{ { Address: ethAddr, Amount: avaxAmount / 2, @@ -154,7 +159,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { Nonce: 0, }, }, - avaxBalance: uint256.NewInt(avaxAmount / 2 * x2cRateUint64), + avaxBalance: uint256.NewInt(avaxAmount / 2 * atomic.X2CRateUint64), balances: map[ids.ID]*big.Int{ customAssetID: big.NewInt(int64(customAmount)), }, @@ -163,7 +168,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { }, { name: "spend all AVAX", - tx: []EVMInput{ + tx: []atomic.EVMInput{ { Address: ethAddr, Amount: avaxAmount, @@ -180,7 +185,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { }, { name: "spend too much AVAX", - tx: []EVMInput{ + tx: []atomic.EVMInput{ { Address: ethAddr, Amount: avaxAmount + 1, @@ -197,7 +202,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { }, { name: "spend half custom", - tx: []EVMInput{ + tx: []atomic.EVMInput{ { Address: ethAddr, Amount: customAmount / 2, @@ -205,7 +210,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { Nonce: 0, }, }, - avaxBalance: uint256.NewInt(avaxAmount * x2cRateUint64), + avaxBalance: uint256.NewInt(avaxAmount * atomic.X2CRateUint64), balances: map[ids.ID]*big.Int{ customAssetID: big.NewInt(int64(customAmount / 2)), }, @@ -214,7 +219,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { }, { name: "spend all custom", - tx: []EVMInput{ + tx: []atomic.EVMInput{ { Address: ethAddr, Amount: customAmount, @@ -222,7 +227,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { Nonce: 0, }, }, - avaxBalance: uint256.NewInt(avaxAmount * x2cRateUint64), + avaxBalance: uint256.NewInt(avaxAmount * atomic.X2CRateUint64), balances: map[ids.ID]*big.Int{ customAssetID: big.NewInt(0), }, @@ -231,7 +236,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { }, { name: "spend too much custom", - tx: []EVMInput{ + tx: []atomic.EVMInput{ { Address: ethAddr, Amount: customAmount + 1, @@ -239,7 +244,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { Nonce: 0, }, }, - avaxBalance: uint256.NewInt(avaxAmount * x2cRateUint64), + avaxBalance: uint256.NewInt(avaxAmount * atomic.X2CRateUint64), balances: map[ids.ID]*big.Int{ customAssetID: big.NewInt(0), }, @@ -248,7 +253,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { }, { name: "spend everything", - tx: []EVMInput{ + tx: []atomic.EVMInput{ { Address: ethAddr, Amount: customAmount, @@ -271,7 +276,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { }, { name: "spend everything wrong nonce", - tx: []EVMInput{ + tx: []atomic.EVMInput{ { Address: ethAddr, Amount: customAmount, @@ -294,7 +299,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { }, { name: "spend everything changing nonces", - tx: []EVMInput{ + tx: []atomic.EVMInput{ { Address: ethAddr, Amount: customAmount, @@ -337,18 +342,18 @@ func TestExportTxEVMStateTransfer(t *testing.T) { }, } - avaxUTXOBytes, err := vm.codec.Marshal(codecVersion, avaxUTXO) + avaxUTXOBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, avaxUTXO) if err != nil { t.Fatal(err) } - customUTXOBytes, err := vm.codec.Marshal(codecVersion, customUTXO) + customUTXOBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, customUTXO) if err != nil { t.Fatal(err) } xChainSharedMemory := sharedMemory.NewSharedMemory(vm.ctx.XChainID) - if err := xChainSharedMemory.Apply(map[ids.ID]*atomic.Requests{vm.ctx.ChainID: {PutRequests: []*atomic.Element{ + if err := xChainSharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{vm.ctx.ChainID: {PutRequests: []*avalancheatomic.Element{ { Key: avaxInputID[:], Value: avaxUTXOBytes, @@ -395,7 +400,7 @@ func TestExportTxEVMStateTransfer(t *testing.T) { t.Fatal(err) } - newTx := UnsignedExportTx{ + newTx := atomic.UnsignedExportTx{ Ins: test.tx, } @@ -446,7 +451,7 @@ func TestExportTxSemanticVerify(t *testing.T) { parent := vm.LastAcceptedBlockInternal().(*Block) key := testKeys[0] - addr := key.PublicKey().Address() + addr := key.Address() ethAddr := testEthAddrs[0] var ( @@ -457,11 +462,11 @@ func TestExportTxSemanticVerify(t *testing.T) { custom1AssetID = ids.ID{1, 2, 3, 4, 5, 6} ) - validExportTx := &UnsignedExportTx{ + validExportTx := &atomic.UnsignedExportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, DestinationChain: vm.ctx.XChainID, - Ins: []EVMInput{ + Ins: []atomic.EVMInput{ { Address: ethAddr, Amount: avaxBalance, @@ -495,11 +500,11 @@ func TestExportTxSemanticVerify(t *testing.T) { }, } - validAVAXExportTx := &UnsignedExportTx{ + validAVAXExportTx := &atomic.UnsignedExportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, DestinationChain: vm.ctx.XChainID, - Ins: []EVMInput{ + Ins: []atomic.EVMInput{ { Address: ethAddr, Amount: avaxBalance, @@ -523,7 +528,7 @@ func TestExportTxSemanticVerify(t *testing.T) { tests := []struct { name string - tx *Tx + tx *atomic.Tx signers [][]*secp256k1.PrivateKey baseFee *big.Int rules params.Rules @@ -531,7 +536,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }{ { name: "valid", - tx: &Tx{UnsignedAtomicTx: validExportTx}, + tx: &atomic.Tx{UnsignedAtomicTx: validExportTx}, signers: [][]*secp256k1.PrivateKey{ {key}, {key}, @@ -543,10 +548,10 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "P-chain before AP5", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validAVAXExportTx validExportTx.DestinationChain = constants.PlatformChainID - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -557,10 +562,10 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "P-chain after AP5", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validAVAXExportTx validExportTx.DestinationChain = constants.PlatformChainID - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -571,10 +576,10 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "random chain after AP5", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validAVAXExportTx validExportTx.DestinationChain = ids.GenerateTestID() - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -585,10 +590,10 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "P-chain multi-coin before AP5", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validExportTx validExportTx.DestinationChain = constants.PlatformChainID - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -601,10 +606,10 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "P-chain multi-coin after AP5", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validExportTx validExportTx.DestinationChain = constants.PlatformChainID - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -617,10 +622,10 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "random chain multi-coin after AP5", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validExportTx validExportTx.DestinationChain = ids.GenerateTestID() - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -633,10 +638,10 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "no outputs", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validExportTx validExportTx.ExportedOutputs = nil - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -649,10 +654,10 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "wrong networkID", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validExportTx validExportTx.NetworkID++ - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -665,10 +670,10 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "wrong chainID", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validExportTx validExportTx.BlockchainID = ids.GenerateTestID() - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -681,11 +686,11 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "invalid input", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validExportTx - validExportTx.Ins = append([]EVMInput{}, validExportTx.Ins...) + validExportTx.Ins = append([]atomic.EVMInput{}, validExportTx.Ins...) validExportTx.Ins[2].Amount = 0 - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -698,7 +703,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "invalid output", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validExportTx validExportTx.ExportedOutputs = []*avax.TransferableOutput{{ Asset: avax.Asset{ID: custom0AssetID}, @@ -710,7 +715,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, }, }} - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -723,7 +728,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "unsorted outputs", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validExportTx exportOutputs := []*avax.TransferableOutput{ { @@ -748,10 +753,10 @@ func TestExportTxSemanticVerify(t *testing.T) { }, } // Sort the outputs and then swap the ordering to ensure that they are ordered incorrectly - avax.SortTransferableOutputs(exportOutputs, Codec) + avax.SortTransferableOutputs(exportOutputs, atomic.Codec) exportOutputs[0], exportOutputs[1] = exportOutputs[1], exportOutputs[0] validExportTx.ExportedOutputs = exportOutputs - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -764,11 +769,11 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "not unique inputs", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validExportTx - validExportTx.Ins = append([]EVMInput{}, validExportTx.Ins...) + validExportTx.Ins = append([]atomic.EVMInput{}, validExportTx.Ins...) validExportTx.Ins[2] = validExportTx.Ins[1] - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -781,7 +786,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "custom asset insufficient funds", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validExportTx validExportTx.ExportedOutputs = []*avax.TransferableOutput{ { @@ -795,7 +800,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, }, } - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -808,7 +813,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "avax insufficient funds", - tx: func() *Tx { + tx: func() *atomic.Tx { validExportTx := *validExportTx validExportTx.ExportedOutputs = []*avax.TransferableOutput{ { @@ -822,7 +827,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, }, } - return &Tx{UnsignedAtomicTx: &validExportTx} + return &atomic.Tx{UnsignedAtomicTx: &validExportTx} }(), signers: [][]*secp256k1.PrivateKey{ {key}, @@ -835,7 +840,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "too many signatures", - tx: &Tx{UnsignedAtomicTx: validExportTx}, + tx: &atomic.Tx{UnsignedAtomicTx: validExportTx}, signers: [][]*secp256k1.PrivateKey{ {key}, {key}, @@ -848,7 +853,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "too few signatures", - tx: &Tx{UnsignedAtomicTx: validExportTx}, + tx: &atomic.Tx{UnsignedAtomicTx: validExportTx}, signers: [][]*secp256k1.PrivateKey{ {key}, {key}, @@ -859,7 +864,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "too many signatures on credential", - tx: &Tx{UnsignedAtomicTx: validExportTx}, + tx: &atomic.Tx{UnsignedAtomicTx: validExportTx}, signers: [][]*secp256k1.PrivateKey{ {key, testKeys[1]}, {key}, @@ -871,7 +876,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "too few signatures on credential", - tx: &Tx{UnsignedAtomicTx: validExportTx}, + tx: &atomic.Tx{UnsignedAtomicTx: validExportTx}, signers: [][]*secp256k1.PrivateKey{ {}, {key}, @@ -883,7 +888,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "wrong signature on credential", - tx: &Tx{UnsignedAtomicTx: validExportTx}, + tx: &atomic.Tx{UnsignedAtomicTx: validExportTx}, signers: [][]*secp256k1.PrivateKey{ {testKeys[1]}, {key}, @@ -895,7 +900,7 @@ func TestExportTxSemanticVerify(t *testing.T) { }, { name: "no signatures", - tx: &Tx{UnsignedAtomicTx: validExportTx}, + tx: &atomic.Tx{UnsignedAtomicTx: validExportTx}, signers: [][]*secp256k1.PrivateKey{}, baseFee: initialBaseFee, rules: apricotRulesPhase3, @@ -903,15 +908,24 @@ func TestExportTxSemanticVerify(t *testing.T) { }, } for _, test := range tests { - if err := test.tx.Sign(vm.codec, test.signers); err != nil { + if err := test.tx.Sign(atomic.Codec, test.signers); err != nil { t.Fatal(err) } + backend := &atomic.Backend{ + Ctx: vm.ctx, + Fx: &vm.fx, + Rules: test.rules, + Bootstrapped: vm.bootstrapped.Get(), + BlockFetcher: vm, + SecpCache: &vm.secpCache, + } + t.Run(test.name, func(t *testing.T) { tx := test.tx exportTx := tx.UnsignedAtomicTx - err := exportTx.SemanticVerify(vm, tx, parent, test.baseFee, test.rules) + err := exportTx.SemanticVerify(backend, tx, parent, test.baseFee) if test.shouldErr && err == nil { t.Fatalf("should have errored but returned valid") } @@ -934,7 +948,7 @@ func TestExportTxAccept(t *testing.T) { }() key := testKeys[0] - addr := key.PublicKey().Address() + addr := key.Address() ethAddr := testEthAddrs[0] var ( @@ -943,11 +957,11 @@ func TestExportTxAccept(t *testing.T) { custom0AssetID = ids.ID{1, 2, 3, 4, 5} ) - exportTx := &UnsignedExportTx{ + exportTx := &atomic.UnsignedExportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, DestinationChain: vm.ctx.XChainID, - Ins: []EVMInput{ + Ins: []atomic.EVMInput{ { Address: ethAddr, Amount: avaxBalance, @@ -985,7 +999,7 @@ func TestExportTxAccept(t *testing.T) { }, } - tx := &Tx{UnsignedAtomicTx: exportTx} + tx := &atomic.Tx{UnsignedAtomicTx: exportTx} signers := [][]*secp256k1.PrivateKey{ {key}, @@ -993,7 +1007,7 @@ func TestExportTxAccept(t *testing.T) { {key}, } - if err := tx.Sign(vm.codec, signers); err != nil { + if err := tx.Sign(atomic.Codec, signers); err != nil { t.Fatal(err) } @@ -1006,7 +1020,7 @@ func TestExportTxAccept(t *testing.T) { t.Fatalf("Failed to accept export transaction due to: %s", err) } - if err := vm.ctx.SharedMemory.Apply(map[ids.ID]*atomic.Requests{chainID: {PutRequests: atomicRequests.PutRequests}}, commitBatch); err != nil { + if err := vm.ctx.SharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{chainID: {PutRequests: atomicRequests.PutRequests}}, commitBatch); err != nil { t.Fatal(err) } indexedValues, _, _, err := xChainSharedMemory.Indexed(vm.ctx.ChainID, [][]byte{addr.Bytes()}, nil, nil, 3) @@ -1045,7 +1059,7 @@ func TestExportTxAccept(t *testing.T) { t.Fatalf("inconsistent values returned fetched %x indexed %x", fetchedValues[1], indexedValues[1]) } - customUTXOBytes, err := Codec.Marshal(codecVersion, &avax.UTXO{ + customUTXOBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, &avax.UTXO{ UTXOID: customUTXOID, Asset: avax.Asset{ID: custom0AssetID}, Out: exportTx.ExportedOutputs[1].Out, @@ -1054,7 +1068,7 @@ func TestExportTxAccept(t *testing.T) { t.Fatal(err) } - avaxUTXOBytes, err := Codec.Marshal(codecVersion, &avax.UTXO{ + avaxUTXOBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, &avax.UTXO{ UTXOID: avaxUTXOID, Asset: avax.Asset{ID: vm.ctx.AVAXAssetID}, Out: exportTx.ExportedOutputs[0].Out, @@ -1073,11 +1087,11 @@ func TestExportTxAccept(t *testing.T) { func TestExportTxVerify(t *testing.T) { var exportAmount uint64 = 10000000 - exportTx := &UnsignedExportTx{ + exportTx := &atomic.UnsignedExportTx{ NetworkID: testNetworkID, BlockchainID: testCChainID, DestinationChain: testXChainID, - Ins: []EVMInput{ + Ins: []atomic.EVMInput{ { Address: testEthAddrs[0], Amount: exportAmount, @@ -1118,25 +1132,25 @@ func TestExportTxVerify(t *testing.T) { } // Sort the inputs and outputs to ensure the transaction is canonical - avax.SortTransferableOutputs(exportTx.ExportedOutputs, Codec) + avax.SortTransferableOutputs(exportTx.ExportedOutputs, atomic.Codec) // Pass in a list of signers here with the appropriate length // to avoid causing a nil-pointer error in the helper method emptySigners := make([][]*secp256k1.PrivateKey, 2) - SortEVMInputsAndSigners(exportTx.Ins, emptySigners) + atomic.SortEVMInputsAndSigners(exportTx.Ins, emptySigners) ctx := NewContext() tests := map[string]atomicTxVerifyTest{ "nil tx": { - generate: func(t *testing.T) UnsignedAtomicTx { - return (*UnsignedExportTx)(nil) + generate: func(t *testing.T) atomic.UnsignedAtomicTx { + return (*atomic.UnsignedExportTx)(nil) }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errNilTx.Error(), + expectedErr: atomic.ErrNilTx.Error(), }, "valid export tx": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { return exportTx }, ctx: ctx, @@ -1144,7 +1158,7 @@ func TestExportTxVerify(t *testing.T) { expectedErr: "", }, "valid export tx banff": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { return exportTx }, ctx: ctx, @@ -1152,47 +1166,47 @@ func TestExportTxVerify(t *testing.T) { expectedErr: "", }, "incorrect networkID": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx tx.NetworkID++ return &tx }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errWrongNetworkID.Error(), + expectedErr: atomic.ErrWrongNetworkID.Error(), }, "incorrect blockchainID": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx tx.BlockchainID = nonExistentID return &tx }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errWrongBlockchainID.Error(), + expectedErr: atomic.ErrWrongChainID.Error(), }, "incorrect destination chain": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx tx.DestinationChain = nonExistentID return &tx }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errWrongChainID.Error(), // TODO make this error more specific to destination not just chainID + expectedErr: atomic.ErrWrongChainID.Error(), // TODO make this error more specific to destination not just chainID }, "no exported outputs": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx tx.ExportedOutputs = nil return &tx }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errNoExportOutputs.Error(), + expectedErr: atomic.ErrNoExportOutputs.Error(), }, "unsorted outputs": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx tx.ExportedOutputs = []*avax.TransferableOutput{ tx.ExportedOutputs[1], @@ -1202,10 +1216,10 @@ func TestExportTxVerify(t *testing.T) { }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errOutputsNotSorted.Error(), + expectedErr: atomic.ErrOutputsNotSorted.Error(), }, "invalid exported output": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx tx.ExportedOutputs = []*avax.TransferableOutput{tx.ExportedOutputs[0], nil} return &tx @@ -1215,9 +1229,9 @@ func TestExportTxVerify(t *testing.T) { expectedErr: "nil transferable output is not valid", }, "unsorted EVM inputs before AP1": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx - tx.Ins = []EVMInput{ + tx.Ins = []atomic.EVMInput{ tx.Ins[1], tx.Ins[0], } @@ -1228,9 +1242,9 @@ func TestExportTxVerify(t *testing.T) { expectedErr: "", }, "unsorted EVM inputs after AP1": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx - tx.Ins = []EVMInput{ + tx.Ins = []atomic.EVMInput{ tx.Ins[1], tx.Ins[0], } @@ -1238,12 +1252,12 @@ func TestExportTxVerify(t *testing.T) { }, ctx: ctx, rules: apricotRulesPhase1, - expectedErr: errInputsNotSortedUnique.Error(), + expectedErr: atomic.ErrInputsNotSortedUnique.Error(), }, "EVM input with amount 0": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx - tx.Ins = []EVMInput{ + tx.Ins = []atomic.EVMInput{ { Address: testEthAddrs[0], Amount: 0, @@ -1255,12 +1269,12 @@ func TestExportTxVerify(t *testing.T) { }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errNoValueInput.Error(), + expectedErr: atomic.ErrNoValueInput.Error(), }, "non-unique EVM input before AP1": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx - tx.Ins = []EVMInput{tx.Ins[0], tx.Ins[0]} + tx.Ins = []atomic.EVMInput{tx.Ins[0], tx.Ins[0]} return &tx }, ctx: ctx, @@ -1268,19 +1282,19 @@ func TestExportTxVerify(t *testing.T) { expectedErr: "", }, "non-unique EVM input after AP1": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx - tx.Ins = []EVMInput{tx.Ins[0], tx.Ins[0]} + tx.Ins = []atomic.EVMInput{tx.Ins[0], tx.Ins[0]} return &tx }, ctx: ctx, rules: apricotRulesPhase1, - expectedErr: errInputsNotSortedUnique.Error(), + expectedErr: atomic.ErrInputsNotSortedUnique.Error(), }, "non-AVAX input Apricot Phase 6": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx - tx.Ins = []EVMInput{ + tx.Ins = []atomic.EVMInput{ { Address: testEthAddrs[0], Amount: 1, @@ -1295,7 +1309,7 @@ func TestExportTxVerify(t *testing.T) { expectedErr: "", }, "non-AVAX output Apricot Phase 6": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx tx.ExportedOutputs = []*avax.TransferableOutput{ { @@ -1317,9 +1331,9 @@ func TestExportTxVerify(t *testing.T) { expectedErr: "", }, "non-AVAX input Banff": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx - tx.Ins = []EVMInput{ + tx.Ins = []atomic.EVMInput{ { Address: testEthAddrs[0], Amount: 1, @@ -1331,10 +1345,10 @@ func TestExportTxVerify(t *testing.T) { }, ctx: ctx, rules: banffRules, - expectedErr: errExportNonAVAXInputBanff.Error(), + expectedErr: atomic.ErrExportNonAVAXInputBanff.Error(), }, "non-AVAX output Banff": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *exportTx tx.ExportedOutputs = []*avax.TransferableOutput{ { @@ -1353,7 +1367,7 @@ func TestExportTxVerify(t *testing.T) { }, ctx: ctx, rules: banffRules, - expectedErr: errExportNonAVAXOutputBanff.Error(), + expectedErr: atomic.ErrExportNonAVAXOutputBanff.Error(), }, } @@ -1374,7 +1388,7 @@ func TestExportTxGasCost(t *testing.T) { exportAmount := uint64(5000000) tests := map[string]struct { - UnsignedExportTx *UnsignedExportTx + UnsignedExportTx *atomic.UnsignedExportTx Keys [][]*secp256k1.PrivateKey BaseFee *big.Int @@ -1383,11 +1397,11 @@ func TestExportTxGasCost(t *testing.T) { FixedFee bool }{ "simple export 1wei BaseFee": { - UnsignedExportTx: &UnsignedExportTx{ + UnsignedExportTx: &atomic.UnsignedExportTx{ NetworkID: networkID, BlockchainID: chainID, DestinationChain: xChainID, - Ins: []EVMInput{ + Ins: []atomic.EVMInput{ { Address: testEthAddrs[0], Amount: exportAmount, @@ -1415,11 +1429,11 @@ func TestExportTxGasCost(t *testing.T) { BaseFee: big.NewInt(1), }, "simple export 1wei BaseFee + fixed fee": { - UnsignedExportTx: &UnsignedExportTx{ + UnsignedExportTx: &atomic.UnsignedExportTx{ NetworkID: networkID, BlockchainID: chainID, DestinationChain: xChainID, - Ins: []EVMInput{ + Ins: []atomic.EVMInput{ { Address: testEthAddrs[0], Amount: exportAmount, @@ -1448,11 +1462,11 @@ func TestExportTxGasCost(t *testing.T) { FixedFee: true, }, "simple export 25Gwei BaseFee": { - UnsignedExportTx: &UnsignedExportTx{ + UnsignedExportTx: &atomic.UnsignedExportTx{ NetworkID: networkID, BlockchainID: chainID, DestinationChain: xChainID, - Ins: []EVMInput{ + Ins: []atomic.EVMInput{ { Address: testEthAddrs[0], Amount: exportAmount, @@ -1480,11 +1494,11 @@ func TestExportTxGasCost(t *testing.T) { BaseFee: big.NewInt(25 * params.GWei), }, "simple export 225Gwei BaseFee": { - UnsignedExportTx: &UnsignedExportTx{ + UnsignedExportTx: &atomic.UnsignedExportTx{ NetworkID: networkID, BlockchainID: chainID, DestinationChain: xChainID, - Ins: []EVMInput{ + Ins: []atomic.EVMInput{ { Address: testEthAddrs[0], Amount: exportAmount, @@ -1512,11 +1526,11 @@ func TestExportTxGasCost(t *testing.T) { BaseFee: big.NewInt(225 * params.GWei), }, "complex export 25Gwei BaseFee": { - UnsignedExportTx: &UnsignedExportTx{ + UnsignedExportTx: &atomic.UnsignedExportTx{ NetworkID: networkID, BlockchainID: chainID, DestinationChain: xChainID, - Ins: []EVMInput{ + Ins: []atomic.EVMInput{ { Address: testEthAddrs[0], Amount: exportAmount, @@ -1556,11 +1570,11 @@ func TestExportTxGasCost(t *testing.T) { BaseFee: big.NewInt(25 * params.GWei), }, "complex export 225Gwei BaseFee": { - UnsignedExportTx: &UnsignedExportTx{ + UnsignedExportTx: &atomic.UnsignedExportTx{ NetworkID: networkID, BlockchainID: chainID, DestinationChain: xChainID, - Ins: []EVMInput{ + Ins: []atomic.EVMInput{ { Address: testEthAddrs[0], Amount: exportAmount, @@ -1603,10 +1617,10 @@ func TestExportTxGasCost(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { - tx := &Tx{UnsignedAtomicTx: test.UnsignedExportTx} + tx := &atomic.Tx{UnsignedAtomicTx: test.UnsignedExportTx} // Sign with the correct key - if err := tx.Sign(Codec, test.Keys); err != nil { + if err := tx.Sign(atomic.Codec, test.Keys); err != nil { t.Fatal(err) } @@ -1618,7 +1632,7 @@ func TestExportTxGasCost(t *testing.T) { t.Fatalf("Expected gasUsed to be %d, but found %d", test.ExpectedGasUsed, gasUsed) } - fee, err := CalculateDynamicFee(gasUsed, test.BaseFee) + fee, err := atomic.CalculateDynamicFee(gasUsed, test.BaseFee) if err != nil { t.Fatal(err) } @@ -1701,22 +1715,22 @@ func TestNewExportTx(t *testing.T) { Amt: importAmount, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{testKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{testKeys[0].Address()}, }, }, } - utxoBytes, err := vm.codec.Marshal(codecVersion, utxo) + utxoBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, utxo) if err != nil { t.Fatal(err) } xChainSharedMemory := sharedMemory.NewSharedMemory(vm.ctx.XChainID) inputID := utxo.InputID() - if err := xChainSharedMemory.Apply(map[ids.ID]*atomic.Requests{vm.ctx.ChainID: {PutRequests: []*atomic.Element{{ + if err := xChainSharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{vm.ctx.ChainID: {PutRequests: []*avalancheatomic.Element{{ Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ - testKeys[0].PublicKey().Address().Bytes(), + testKeys[0].Address().Bytes(), }, }}}}); err != nil { t.Fatal(err) @@ -1753,14 +1767,28 @@ func TestNewExportTx(t *testing.T) { parent = vm.LastAcceptedBlockInternal().(*Block) exportAmount := uint64(5000000) - tx, err = vm.newExportTx(vm.ctx.AVAXAssetID, exportAmount, vm.ctx.XChainID, testShortIDAddrs[0], initialBaseFee, []*secp256k1.PrivateKey{testKeys[0]}) + state, err := vm.blockChain.State() + if err != nil { + t.Fatal(err) + } + + tx, err = atomic.NewExportTx(vm.ctx, test.rules, state, vm.ctx.AVAXAssetID, exportAmount, vm.ctx.XChainID, testShortIDAddrs[0], initialBaseFee, []*secp256k1.PrivateKey{testKeys[0]}) if err != nil { t.Fatal(err) } exportTx := tx.UnsignedAtomicTx - if err := exportTx.SemanticVerify(vm, tx, parent, parent.ethBlock.BaseFee(), test.rules); err != nil { + backend := &atomic.Backend{ + Ctx: vm.ctx, + Fx: &vm.fx, + Rules: vm.currentRules(), + Bootstrapped: vm.bootstrapped.Get(), + BlockFetcher: vm, + SecpCache: &vm.secpCache, + } + + if err := exportTx.SemanticVerify(backend, tx, parent, parent.ethBlock.BaseFee()); err != nil { t.Fatal("newExportTx created an invalid transaction", err) } @@ -1781,7 +1809,7 @@ func TestNewExportTx(t *testing.T) { t.Fatalf("Failed to accept export transaction due to: %s", err) } - if err := vm.ctx.SharedMemory.Apply(map[ids.ID]*atomic.Requests{chainID: {PutRequests: atomicRequests.PutRequests}}, commitBatch); err != nil { + if err := vm.ctx.SharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{chainID: {PutRequests: atomicRequests.PutRequests}}, commitBatch); err != nil { t.Fatal(err) } @@ -1794,7 +1822,7 @@ func TestNewExportTx(t *testing.T) { t.Fatal(err) } - addr := GetEthAddress(testKeys[0]) + addr := testKeys[0].EthAddress() if sdb.GetBalance(addr).Cmp(uint256.NewInt(test.bal*units.Avax)) != 0 { t.Fatalf("address balance %s equal %s not %s", addr.String(), sdb.GetBalance(addr), new(big.Int).SetUint64(test.bal*units.Avax)) } @@ -1860,11 +1888,11 @@ func TestNewExportTxMulticoin(t *testing.T) { Amt: importAmount, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{testKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{testKeys[0].Address()}, }, }, } - utxoBytes, err := vm.codec.Marshal(codecVersion, utxo) + utxoBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, utxo) if err != nil { t.Fatal(err) } @@ -1881,30 +1909,30 @@ func TestNewExportTxMulticoin(t *testing.T) { Amt: importAmount2, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{testKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{testKeys[0].Address()}, }, }, } - utxoBytes2, err := vm.codec.Marshal(codecVersion, utxo2) + utxoBytes2, err := atomic.Codec.Marshal(atomic.CodecVersion, utxo2) if err != nil { t.Fatal(err) } xChainSharedMemory := sharedMemory.NewSharedMemory(vm.ctx.XChainID) inputID2 := utxo2.InputID() - if err := xChainSharedMemory.Apply(map[ids.ID]*atomic.Requests{vm.ctx.ChainID: {PutRequests: []*atomic.Element{ + if err := xChainSharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{vm.ctx.ChainID: {PutRequests: []*avalancheatomic.Element{ { Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ - testKeys[0].PublicKey().Address().Bytes(), + testKeys[0].Address().Bytes(), }, }, { Key: inputID2[:], Value: utxoBytes2, Traits: [][]byte{ - testKeys[0].PublicKey().Address().Bytes(), + testKeys[0].Address().Bytes(), }, }, }}}); err != nil { @@ -1942,20 +1970,33 @@ func TestNewExportTxMulticoin(t *testing.T) { parent = vm.LastAcceptedBlockInternal().(*Block) exportAmount := uint64(5000000) - testKeys0Addr := GetEthAddress(testKeys[0]) + testKeys0Addr := testKeys[0].EthAddress() exportId, err := ids.ToShortID(testKeys0Addr[:]) if err != nil { t.Fatal(err) } - tx, err = vm.newExportTx(tid, exportAmount, vm.ctx.XChainID, exportId, initialBaseFee, []*secp256k1.PrivateKey{testKeys[0]}) + state, err := vm.blockChain.State() + if err != nil { + t.Fatal(err) + } + + tx, err = atomic.NewExportTx(vm.ctx, vm.currentRules(), state, tid, exportAmount, vm.ctx.XChainID, exportId, initialBaseFee, []*secp256k1.PrivateKey{testKeys[0]}) if err != nil { t.Fatal(err) } exportTx := tx.UnsignedAtomicTx + backend := &atomic.Backend{ + Ctx: vm.ctx, + Fx: &vm.fx, + Rules: vm.currentRules(), + Bootstrapped: vm.bootstrapped.Get(), + BlockFetcher: vm, + SecpCache: &vm.secpCache, + } - if err := exportTx.SemanticVerify(vm, tx, parent, parent.ethBlock.BaseFee(), test.rules); err != nil { + if err := exportTx.SemanticVerify(backend, tx, parent, parent.ethBlock.BaseFee()); err != nil { t.Fatal("newExportTx created an invalid transaction", err) } @@ -1968,7 +2009,7 @@ func TestNewExportTxMulticoin(t *testing.T) { t.Fatalf("Failed to accept export transaction due to: %s", err) } - if err := vm.ctx.SharedMemory.Apply(map[ids.ID]*atomic.Requests{chainID: {PutRequests: atomicRequests.PutRequests}}, commitBatch); err != nil { + if err := vm.ctx.SharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{chainID: {PutRequests: atomicRequests.PutRequests}}, commitBatch); err != nil { t.Fatal(err) } @@ -1981,7 +2022,7 @@ func TestNewExportTxMulticoin(t *testing.T) { t.Fatal(err) } - addr := GetEthAddress(testKeys[0]) + addr := testKeys[0].EthAddress() if stdb.GetBalance(addr).Cmp(uint256.NewInt(test.bal*units.Avax)) != 0 { t.Fatalf("address balance %s equal %s not %s", addr.String(), stdb.GetBalance(addr), new(big.Int).SetUint64(test.bal*units.Avax)) } diff --git a/plugin/evm/formatting.go b/plugin/evm/formatting.go index ba9cea589f..feeab134b7 100644 --- a/plugin/evm/formatting.go +++ b/plugin/evm/formatting.go @@ -8,10 +8,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/formatting/address" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" ) // ParseServiceAddress get address ID from address string, being it either localized (using address manager, @@ -53,21 +50,3 @@ func (vm *VM) FormatAddress(chainID ids.ID, addr ids.ShortID) (string, error) { hrp := constants.GetHRP(vm.ctx.NetworkID) return address.Format(chainIDAlias, hrp, addr.Bytes()) } - -// ParseEthAddress parses [addrStr] and returns an Ethereum address -func ParseEthAddress(addrStr string) (common.Address, error) { - if !common.IsHexAddress(addrStr) { - return common.Address{}, errInvalidAddr - } - return common.HexToAddress(addrStr), nil -} - -// GetEthAddress returns the ethereum address derived from [privKey] -func GetEthAddress(privKey *secp256k1.PrivateKey) common.Address { - return PublicKeyToEthAddress(privKey.PublicKey()) -} - -// PublicKeyToEthAddress returns the ethereum address derived from [pubKey] -func PublicKeyToEthAddress(pubKey *secp256k1.PublicKey) common.Address { - return crypto.PubkeyToAddress(*(pubKey.ToECDSA())) -} diff --git a/plugin/evm/gossip.go b/plugin/evm/gossip.go index a760936021..d6b377d13a 100644 --- a/plugin/evm/gossip.go +++ b/plugin/evm/gossip.go @@ -7,7 +7,7 @@ import ( "context" "fmt" "sync" - "sync/atomic" + syncatomic "sync/atomic" "time" ethcommon "github.com/ethereum/go-ethereum/common" @@ -24,6 +24,7 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/eth" + "github.com/ava-labs/coreth/plugin/evm/atomic" ) const pendingTxsBuffer = 10 @@ -97,14 +98,14 @@ func (g GossipAtomicTxMarshaller) MarshalGossip(tx *GossipAtomicTx) ([]byte, err } func (g GossipAtomicTxMarshaller) UnmarshalGossip(bytes []byte) (*GossipAtomicTx, error) { - tx, err := ExtractAtomicTx(bytes, Codec) + tx, err := atomic.ExtractAtomicTx(bytes, atomic.Codec) return &GossipAtomicTx{ Tx: tx, }, err } type GossipAtomicTx struct { - Tx *Tx + Tx *atomic.Tx } func (tx *GossipAtomicTx) GossipID() ids.ID { @@ -133,7 +134,7 @@ type GossipEthTxPool struct { // subscribed is set to true when the gossip subscription is active // mostly used for testing - subscribed atomic.Bool + subscribed syncatomic.Bool } // IsSubscribed returns whether or not the gossip subscription is active. diff --git a/plugin/evm/gossip_test.go b/plugin/evm/gossip_test.go index 8ed7aee3cf..15ebd15871 100644 --- a/plugin/evm/gossip_test.go +++ b/plugin/evm/gossip_test.go @@ -22,6 +22,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/core/vm" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/prometheus/client_golang/prometheus" @@ -33,15 +34,15 @@ func TestGossipAtomicTxMarshaller(t *testing.T) { require := require.New(t) want := &GossipAtomicTx{ - Tx: &Tx{ - UnsignedAtomicTx: &UnsignedImportTx{}, + Tx: &atomic.Tx{ + UnsignedAtomicTx: &atomic.UnsignedImportTx{}, Creds: []verify.Verifiable{}, }, } marshaller := GossipAtomicTxMarshaller{} key0 := testKeys[0] - require.NoError(want.Tx.Sign(Codec, [][]*secp256k1.PrivateKey{{key0}})) + require.NoError(want.Tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{key0}})) bytes, err := marshaller.MarshalGossip(want) require.NoError(err) @@ -54,14 +55,14 @@ func TestGossipAtomicTxMarshaller(t *testing.T) { func TestAtomicMempoolIterate(t *testing.T) { txs := []*GossipAtomicTx{ { - Tx: &Tx{ + Tx: &atomic.Tx{ UnsignedAtomicTx: &TestUnsignedTx{ IDV: ids.GenerateTestID(), }, }, }, { - Tx: &Tx{ + Tx: &atomic.Tx{ UnsignedAtomicTx: &TestUnsignedTx{ IDV: ids.GenerateTestID(), }, diff --git a/plugin/evm/handler.go b/plugin/evm/handler.go index ce970c822f..c4b41a85e7 100644 --- a/plugin/evm/handler.go +++ b/plugin/evm/handler.go @@ -11,6 +11,7 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/plugin/evm/message" ) @@ -47,15 +48,15 @@ func (h *GossipHandler) HandleAtomicTx(nodeID ids.NodeID, msg message.AtomicTxGo // In the case that the gossip message contains a transaction, // attempt to parse it and add it as a remote. - tx := Tx{} - if _, err := Codec.Unmarshal(msg.Tx, &tx); err != nil { + tx := atomic.Tx{} + if _, err := atomic.Codec.Unmarshal(msg.Tx, &tx); err != nil { log.Trace( "AppGossip provided invalid tx", "err", err, ) return nil } - unsignedBytes, err := Codec.Marshal(codecVersion, &tx.UnsignedAtomicTx) + unsignedBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, &tx.UnsignedAtomicTx) if err != nil { log.Trace( "AppGossip failed to marshal unsigned tx", diff --git a/plugin/evm/import_tx_test.go b/plugin/evm/import_tx_test.go index ec8b2b2fb4..3195fd7dae 100644 --- a/plugin/evm/import_tx_test.go +++ b/plugin/evm/import_tx_test.go @@ -8,12 +8,13 @@ import ( "testing" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ethereum/go-ethereum/common" "github.com/holiman/uint256" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/utils" + avalancheutils "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/set" @@ -23,7 +24,7 @@ import ( // createImportTxOptions adds a UTXO to shared memory and generates a list of import transactions sending this UTXO // to each of the three test keys (conflicting transactions) -func createImportTxOptions(t *testing.T, vm *VM, sharedMemory *atomic.Memory) []*Tx { +func createImportTxOptions(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) []*atomic.Tx { utxo := &avax.UTXO{ UTXOID: avax.UTXOID{TxID: ids.GenerateTestID()}, Asset: avax.Asset{ID: vm.ctx.AVAXAssetID}, @@ -31,28 +32,28 @@ func createImportTxOptions(t *testing.T, vm *VM, sharedMemory *atomic.Memory) [] Amt: uint64(50000000), OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{testKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{testKeys[0].Address()}, }, }, } - utxoBytes, err := vm.codec.Marshal(codecVersion, utxo) + utxoBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, utxo) if err != nil { t.Fatal(err) } xChainSharedMemory := sharedMemory.NewSharedMemory(vm.ctx.XChainID) inputID := utxo.InputID() - if err := xChainSharedMemory.Apply(map[ids.ID]*atomic.Requests{vm.ctx.ChainID: {PutRequests: []*atomic.Element{{ + if err := xChainSharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{vm.ctx.ChainID: {PutRequests: []*avalancheatomic.Element{{ Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ - testKeys[0].PublicKey().Address().Bytes(), + testKeys[0].Address().Bytes(), }, }}}}); err != nil { t.Fatal(err) } - importTxs := make([]*Tx, 0, 3) + importTxs := make([]*atomic.Tx, 0, 3) for _, ethAddr := range testEthAddrs { importTx, err := vm.newImportTx(vm.ctx.XChainID, ethAddr, initialBaseFee, []*secp256k1.PrivateKey{testKeys[0]}) if err != nil { @@ -69,7 +70,7 @@ func TestImportTxVerify(t *testing.T) { var importAmount uint64 = 10000000 txID := ids.GenerateTestID() - importTx := &UnsignedImportTx{ + importTx := &atomic.UnsignedImportTx{ NetworkID: ctx.NetworkID, BlockchainID: ctx.ChainID, SourceChain: ctx.XChainID, @@ -101,7 +102,7 @@ func TestImportTxVerify(t *testing.T) { }, }, }, - Outs: []EVMOutput{ + Outs: []atomic.EVMOutput{ { Address: testEthAddrs[0], Amount: importAmount - params.AvalancheAtomicTxFee, @@ -116,21 +117,21 @@ func TestImportTxVerify(t *testing.T) { } // Sort the inputs and outputs to ensure the transaction is canonical - utils.Sort(importTx.ImportedInputs) - utils.Sort(importTx.Outs) + avalancheutils.Sort(importTx.ImportedInputs) + avalancheutils.Sort(importTx.Outs) tests := map[string]atomicTxVerifyTest{ "nil tx": { - generate: func(t *testing.T) UnsignedAtomicTx { - var importTx *UnsignedImportTx + generate: func(t *testing.T) atomic.UnsignedAtomicTx { + var importTx *atomic.UnsignedImportTx return importTx }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errNilTx.Error(), + expectedErr: atomic.ErrNilTx.Error(), }, "valid import tx": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { return importTx }, ctx: ctx, @@ -138,7 +139,7 @@ func TestImportTxVerify(t *testing.T) { expectedErr: "", // Expect this transaction to be valid in Apricot Phase 0 }, "valid import tx banff": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { return importTx }, ctx: ctx, @@ -146,37 +147,37 @@ func TestImportTxVerify(t *testing.T) { expectedErr: "", // Expect this transaction to be valid in Banff }, "invalid network ID": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx tx.NetworkID++ return &tx }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errWrongNetworkID.Error(), + expectedErr: atomic.ErrWrongNetworkID.Error(), }, "invalid blockchain ID": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx tx.BlockchainID = ids.GenerateTestID() return &tx }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errWrongBlockchainID.Error(), + expectedErr: atomic.ErrWrongChainID.Error(), }, "P-chain source before AP5": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx tx.SourceChain = constants.PlatformChainID return &tx }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errWrongChainID.Error(), + expectedErr: atomic.ErrWrongChainID.Error(), }, "P-chain source after AP5": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx tx.SourceChain = constants.PlatformChainID return &tx @@ -185,27 +186,27 @@ func TestImportTxVerify(t *testing.T) { rules: apricotRulesPhase5, }, "invalid source chain ID": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx tx.SourceChain = ids.GenerateTestID() return &tx }, ctx: ctx, rules: apricotRulesPhase5, - expectedErr: errWrongChainID.Error(), + expectedErr: atomic.ErrWrongChainID.Error(), }, "no inputs": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx tx.ImportedInputs = nil return &tx }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errNoImportInputs.Error(), + expectedErr: atomic.ErrNoImportInputs.Error(), }, "inputs sorted incorrectly": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx tx.ImportedInputs = []*avax.TransferableInput{ tx.ImportedInputs[1], @@ -215,10 +216,10 @@ func TestImportTxVerify(t *testing.T) { }, ctx: ctx, rules: apricotRulesPhase0, - expectedErr: errInputsNotSortedUnique.Error(), + expectedErr: atomic.ErrInputsNotSortedUnique.Error(), }, "invalid input": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx tx.ImportedInputs = []*avax.TransferableInput{ tx.ImportedInputs[0], @@ -231,9 +232,9 @@ func TestImportTxVerify(t *testing.T) { expectedErr: "atomic input failed verification", }, "unsorted outputs phase 0 passes verification": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx - tx.Outs = []EVMOutput{ + tx.Outs = []atomic.EVMOutput{ tx.Outs[1], tx.Outs[0], } @@ -244,9 +245,9 @@ func TestImportTxVerify(t *testing.T) { expectedErr: "", }, "non-unique outputs phase 0 passes verification": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx - tx.Outs = []EVMOutput{ + tx.Outs = []atomic.EVMOutput{ tx.Outs[0], tx.Outs[0], } @@ -257,9 +258,9 @@ func TestImportTxVerify(t *testing.T) { expectedErr: "", }, "unsorted outputs phase 1 fails verification": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx - tx.Outs = []EVMOutput{ + tx.Outs = []atomic.EVMOutput{ tx.Outs[1], tx.Outs[0], } @@ -267,12 +268,12 @@ func TestImportTxVerify(t *testing.T) { }, ctx: ctx, rules: apricotRulesPhase1, - expectedErr: errOutputsNotSorted.Error(), + expectedErr: atomic.ErrOutputsNotSorted.Error(), }, "non-unique outputs phase 1 passes verification": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx - tx.Outs = []EVMOutput{ + tx.Outs = []atomic.EVMOutput{ tx.Outs[0], tx.Outs[0], } @@ -283,9 +284,9 @@ func TestImportTxVerify(t *testing.T) { expectedErr: "", }, "outputs not sorted and unique phase 2 fails verification": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx - tx.Outs = []EVMOutput{ + tx.Outs = []atomic.EVMOutput{ tx.Outs[0], tx.Outs[0], } @@ -293,12 +294,12 @@ func TestImportTxVerify(t *testing.T) { }, ctx: ctx, rules: apricotRulesPhase2, - expectedErr: errOutputsNotSortedUnique.Error(), + expectedErr: atomic.ErrOutputsNotSortedUnique.Error(), }, "outputs not sorted phase 2 fails verification": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx - tx.Outs = []EVMOutput{ + tx.Outs = []atomic.EVMOutput{ tx.Outs[1], tx.Outs[0], } @@ -306,12 +307,12 @@ func TestImportTxVerify(t *testing.T) { }, ctx: ctx, rules: apricotRulesPhase2, - expectedErr: errOutputsNotSortedUnique.Error(), + expectedErr: atomic.ErrOutputsNotSortedUnique.Error(), }, "invalid EVMOutput fails verification": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx - tx.Outs = []EVMOutput{ + tx.Outs = []atomic.EVMOutput{ { Address: testEthAddrs[0], Amount: 0, @@ -325,17 +326,17 @@ func TestImportTxVerify(t *testing.T) { expectedErr: "EVM Output failed verification", }, "no outputs apricot phase 3": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx tx.Outs = nil return &tx }, ctx: ctx, rules: apricotRulesPhase3, - expectedErr: errNoEVMOutputs.Error(), + expectedErr: atomic.ErrNoEVMOutputs.Error(), }, "non-AVAX input Apricot Phase 6": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx tx.ImportedInputs = []*avax.TransferableInput{ { @@ -359,9 +360,9 @@ func TestImportTxVerify(t *testing.T) { expectedErr: "", }, "non-AVAX output Apricot Phase 6": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx - tx.Outs = []EVMOutput{ + tx.Outs = []atomic.EVMOutput{ { Address: importTx.Outs[0].Address, Amount: importTx.Outs[0].Amount, @@ -375,7 +376,7 @@ func TestImportTxVerify(t *testing.T) { expectedErr: "", }, "non-AVAX input Banff": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx tx.ImportedInputs = []*avax.TransferableInput{ { @@ -396,12 +397,12 @@ func TestImportTxVerify(t *testing.T) { }, ctx: ctx, rules: banffRules, - expectedErr: errImportNonAVAXInputBanff.Error(), + expectedErr: atomic.ErrImportNonAVAXInputBanff.Error(), }, "non-AVAX output Banff": { - generate: func(t *testing.T) UnsignedAtomicTx { + generate: func(t *testing.T) atomic.UnsignedAtomicTx { tx := *importTx - tx.Outs = []EVMOutput{ + tx.Outs = []atomic.EVMOutput{ { Address: importTx.Outs[0].Address, Amount: importTx.Outs[0].Amount, @@ -412,7 +413,7 @@ func TestImportTxVerify(t *testing.T) { }, ctx: ctx, rules: banffRules, - expectedErr: errImportNonAVAXOutputBanff.Error(), + expectedErr: atomic.ErrImportNonAVAXOutputBanff.Error(), }, } for name, test := range tests { @@ -426,7 +427,7 @@ func TestNewImportTx(t *testing.T) { importAmount := uint64(5000000) // createNewImportAVAXTx adds a UTXO to shared memory and then constructs a new import transaction // and checks that it has the correct fee for the base fee that has been used - createNewImportAVAXTx := func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx { + createNewImportAVAXTx := func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx { txID := ids.GenerateTestID() _, err := addUTXO(sharedMemory, vm.ctx, txID, 0, vm.ctx.AVAXAssetID, importAmount, testShortIDAddrs[0]) if err != nil { @@ -450,7 +451,7 @@ func TestNewImportTx(t *testing.T) { if err != nil { t.Fatal(err) } - actualFee, err = CalculateDynamicFee(actualCost, initialBaseFee) + actualFee, err = atomic.CalculateDynamicFee(actualCost, initialBaseFee) if err != nil { t.Fatal(err) } @@ -496,8 +497,8 @@ func TestNewImportTx(t *testing.T) { } expectedRemainingBalance := new(uint256.Int).Mul( - uint256.NewInt(importAmount-actualAVAXBurned), x2cRate) - addr := GetEthAddress(testKeys[0]) + uint256.NewInt(importAmount-actualAVAXBurned), atomic.X2CRate) + addr := testKeys[0].EthAddress() if actualBalance := sdb.GetBalance(addr); actualBalance.Cmp(expectedRemainingBalance) != 0 { t.Fatalf("address remaining balance %s equal %s not %s", addr.String(), actualBalance, expectedRemainingBalance) } @@ -543,7 +544,7 @@ func TestImportTxGasCost(t *testing.T) { importAmount := uint64(5000000) tests := map[string]struct { - UnsignedImportTx *UnsignedImportTx + UnsignedImportTx *atomic.UnsignedImportTx Keys [][]*secp256k1.PrivateKey ExpectedGasUsed uint64 @@ -552,7 +553,7 @@ func TestImportTxGasCost(t *testing.T) { FixedFee bool }{ "simple import": { - UnsignedImportTx: &UnsignedImportTx{ + UnsignedImportTx: &atomic.UnsignedImportTx{ NetworkID: networkID, BlockchainID: chainID, SourceChain: xChainID, @@ -564,7 +565,7 @@ func TestImportTxGasCost(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: importAmount, AssetID: avaxAssetID, @@ -576,7 +577,7 @@ func TestImportTxGasCost(t *testing.T) { BaseFee: big.NewInt(25 * params.GWei), }, "simple import 1wei": { - UnsignedImportTx: &UnsignedImportTx{ + UnsignedImportTx: &atomic.UnsignedImportTx{ NetworkID: networkID, BlockchainID: chainID, SourceChain: xChainID, @@ -588,7 +589,7 @@ func TestImportTxGasCost(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: importAmount, AssetID: avaxAssetID, @@ -600,7 +601,7 @@ func TestImportTxGasCost(t *testing.T) { BaseFee: big.NewInt(1), }, "simple import 1wei + fixed fee": { - UnsignedImportTx: &UnsignedImportTx{ + UnsignedImportTx: &atomic.UnsignedImportTx{ NetworkID: networkID, BlockchainID: chainID, SourceChain: xChainID, @@ -612,7 +613,7 @@ func TestImportTxGasCost(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: importAmount, AssetID: avaxAssetID, @@ -625,7 +626,7 @@ func TestImportTxGasCost(t *testing.T) { FixedFee: true, }, "simple ANT import": { - UnsignedImportTx: &UnsignedImportTx{ + UnsignedImportTx: &atomic.UnsignedImportTx{ NetworkID: networkID, BlockchainID: chainID, SourceChain: xChainID, @@ -647,7 +648,7 @@ func TestImportTxGasCost(t *testing.T) { }, }, }, - Outs: []EVMOutput{ + Outs: []atomic.EVMOutput{ { Address: testEthAddrs[0], Amount: importAmount, @@ -661,7 +662,7 @@ func TestImportTxGasCost(t *testing.T) { BaseFee: big.NewInt(25 * params.GWei), }, "complex ANT import": { - UnsignedImportTx: &UnsignedImportTx{ + UnsignedImportTx: &atomic.UnsignedImportTx{ NetworkID: networkID, BlockchainID: chainID, SourceChain: xChainID, @@ -683,7 +684,7 @@ func TestImportTxGasCost(t *testing.T) { }, }, }, - Outs: []EVMOutput{ + Outs: []atomic.EVMOutput{ { Address: testEthAddrs[0], Amount: importAmount, @@ -702,7 +703,7 @@ func TestImportTxGasCost(t *testing.T) { BaseFee: big.NewInt(25 * params.GWei), }, "multisig import": { - UnsignedImportTx: &UnsignedImportTx{ + UnsignedImportTx: &atomic.UnsignedImportTx{ NetworkID: networkID, BlockchainID: chainID, SourceChain: xChainID, @@ -714,7 +715,7 @@ func TestImportTxGasCost(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0, 1}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: importAmount, AssetID: avaxAssetID, @@ -726,7 +727,7 @@ func TestImportTxGasCost(t *testing.T) { BaseFee: big.NewInt(25 * params.GWei), }, "large import": { - UnsignedImportTx: &UnsignedImportTx{ + UnsignedImportTx: &atomic.UnsignedImportTx{ NetworkID: networkID, BlockchainID: chainID, SourceChain: xChainID, @@ -812,7 +813,7 @@ func TestImportTxGasCost(t *testing.T) { }, }, }, - Outs: []EVMOutput{ + Outs: []atomic.EVMOutput{ { Address: testEthAddrs[0], Amount: importAmount * 10, @@ -840,10 +841,10 @@ func TestImportTxGasCost(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { - tx := &Tx{UnsignedAtomicTx: test.UnsignedImportTx} + tx := &atomic.Tx{UnsignedAtomicTx: test.UnsignedImportTx} // Sign with the correct key - if err := tx.Sign(Codec, test.Keys); err != nil { + if err := tx.Sign(atomic.Codec, test.Keys); err != nil { t.Fatal(err) } @@ -855,7 +856,7 @@ func TestImportTxGasCost(t *testing.T) { t.Fatalf("Expected gasUsed to be %d, but found %d", test.ExpectedGasUsed, gasUsed) } - fee, err := CalculateDynamicFee(gasUsed, test.BaseFee) + fee, err := atomic.CalculateDynamicFee(gasUsed, test.BaseFee) if err != nil { t.Fatal(err) } @@ -869,8 +870,8 @@ func TestImportTxGasCost(t *testing.T) { func TestImportTxSemanticVerify(t *testing.T) { tests := map[string]atomicTxTest{ "UTXO not present during bootstrapping": { - setup: func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx { - tx := &Tx{UnsignedAtomicTx: &UnsignedImportTx{ + setup: func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx { + tx := &atomic.Tx{UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, SourceChain: vm.ctx.XChainID, @@ -884,13 +885,13 @@ func TestImportTxSemanticVerify(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: 1, AssetID: vm.ctx.AVAXAssetID, }}, }} - if err := tx.Sign(vm.codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { + if err := tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { t.Fatal(err) } return tx @@ -898,8 +899,8 @@ func TestImportTxSemanticVerify(t *testing.T) { bootstrapping: true, }, "UTXO not present": { - setup: func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx { - tx := &Tx{UnsignedAtomicTx: &UnsignedImportTx{ + setup: func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx { + tx := &atomic.Tx{UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, SourceChain: vm.ctx.XChainID, @@ -913,13 +914,13 @@ func TestImportTxSemanticVerify(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: 1, AssetID: vm.ctx.AVAXAssetID, }}, }} - if err := tx.Sign(vm.codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { + if err := tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { t.Fatal(err) } return tx @@ -927,11 +928,11 @@ func TestImportTxSemanticVerify(t *testing.T) { semanticVerifyErr: "failed to fetch import UTXOs from", }, "garbage UTXO": { - setup: func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx { + setup: func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx { utxoID := avax.UTXOID{TxID: ids.GenerateTestID()} xChainSharedMemory := sharedMemory.NewSharedMemory(vm.ctx.XChainID) inputID := utxoID.InputID() - if err := xChainSharedMemory.Apply(map[ids.ID]*atomic.Requests{vm.ctx.ChainID: {PutRequests: []*atomic.Element{{ + if err := xChainSharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{vm.ctx.ChainID: {PutRequests: []*avalancheatomic.Element{{ Key: inputID[:], Value: []byte("hey there"), Traits: [][]byte{ @@ -941,7 +942,7 @@ func TestImportTxSemanticVerify(t *testing.T) { t.Fatal(err) } - tx := &Tx{UnsignedAtomicTx: &UnsignedImportTx{ + tx := &atomic.Tx{UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, SourceChain: vm.ctx.XChainID, @@ -953,13 +954,13 @@ func TestImportTxSemanticVerify(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: 1, AssetID: vm.ctx.AVAXAssetID, }}, }} - if err := tx.Sign(vm.codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { + if err := tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { t.Fatal(err) } return tx @@ -967,7 +968,7 @@ func TestImportTxSemanticVerify(t *testing.T) { semanticVerifyErr: "failed to unmarshal UTXO", }, "UTXO AssetID mismatch": { - setup: func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx { + setup: func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx { txID := ids.GenerateTestID() expectedAssetID := ids.GenerateTestID() utxo, err := addUTXO(sharedMemory, vm.ctx, txID, 0, expectedAssetID, 1, testShortIDAddrs[0]) @@ -975,7 +976,7 @@ func TestImportTxSemanticVerify(t *testing.T) { t.Fatal(err) } - tx := &Tx{UnsignedAtomicTx: &UnsignedImportTx{ + tx := &atomic.Tx{UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, SourceChain: vm.ctx.XChainID, @@ -987,28 +988,28 @@ func TestImportTxSemanticVerify(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: 1, AssetID: vm.ctx.AVAXAssetID, }}, }} - if err := tx.Sign(vm.codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { + if err := tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { t.Fatal(err) } return tx }, - semanticVerifyErr: errAssetIDMismatch.Error(), + semanticVerifyErr: atomic.ErrAssetIDMismatch.Error(), }, "insufficient AVAX funds": { - setup: func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx { + setup: func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx { txID := ids.GenerateTestID() utxo, err := addUTXO(sharedMemory, vm.ctx, txID, 0, vm.ctx.AVAXAssetID, 1, testShortIDAddrs[0]) if err != nil { t.Fatal(err) } - tx := &Tx{UnsignedAtomicTx: &UnsignedImportTx{ + tx := &atomic.Tx{UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, SourceChain: vm.ctx.XChainID, @@ -1020,13 +1021,13 @@ func TestImportTxSemanticVerify(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: 2, // Produce more output than is consumed by the transaction AssetID: vm.ctx.AVAXAssetID, }}, }} - if err := tx.Sign(vm.codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { + if err := tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { t.Fatal(err) } return tx @@ -1034,7 +1035,7 @@ func TestImportTxSemanticVerify(t *testing.T) { semanticVerifyErr: "import tx flow check failed due to", }, "insufficient non-AVAX funds": { - setup: func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx { + setup: func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx { txID := ids.GenerateTestID() assetID := ids.GenerateTestID() utxo, err := addUTXO(sharedMemory, vm.ctx, txID, 0, assetID, 1, testShortIDAddrs[0]) @@ -1042,7 +1043,7 @@ func TestImportTxSemanticVerify(t *testing.T) { t.Fatal(err) } - tx := &Tx{UnsignedAtomicTx: &UnsignedImportTx{ + tx := &atomic.Tx{UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, SourceChain: vm.ctx.XChainID, @@ -1054,13 +1055,13 @@ func TestImportTxSemanticVerify(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: 2, // Produce more output than is consumed by the transaction AssetID: assetID, }}, }} - if err := tx.Sign(vm.codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { + if err := tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { t.Fatal(err) } return tx @@ -1068,14 +1069,14 @@ func TestImportTxSemanticVerify(t *testing.T) { semanticVerifyErr: "import tx flow check failed due to", }, "no signatures": { - setup: func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx { + setup: func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx { txID := ids.GenerateTestID() utxo, err := addUTXO(sharedMemory, vm.ctx, txID, 0, vm.ctx.AVAXAssetID, 1, testShortIDAddrs[0]) if err != nil { t.Fatal(err) } - tx := &Tx{UnsignedAtomicTx: &UnsignedImportTx{ + tx := &atomic.Tx{UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, SourceChain: vm.ctx.XChainID, @@ -1087,13 +1088,13 @@ func TestImportTxSemanticVerify(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: 1, AssetID: vm.ctx.AVAXAssetID, }}, }} - if err := tx.Sign(vm.codec, nil); err != nil { + if err := tx.Sign(atomic.Codec, nil); err != nil { t.Fatal(err) } return tx @@ -1101,14 +1102,14 @@ func TestImportTxSemanticVerify(t *testing.T) { semanticVerifyErr: "import tx contained mismatched number of inputs/credentials", }, "incorrect signature": { - setup: func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx { + setup: func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx { txID := ids.GenerateTestID() utxo, err := addUTXO(sharedMemory, vm.ctx, txID, 0, vm.ctx.AVAXAssetID, 1, testShortIDAddrs[0]) if err != nil { t.Fatal(err) } - tx := &Tx{UnsignedAtomicTx: &UnsignedImportTx{ + tx := &atomic.Tx{UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, SourceChain: vm.ctx.XChainID, @@ -1120,14 +1121,14 @@ func TestImportTxSemanticVerify(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: 1, AssetID: vm.ctx.AVAXAssetID, }}, }} // Sign the transaction with the incorrect key - if err := tx.Sign(vm.codec, [][]*secp256k1.PrivateKey{{testKeys[1]}}); err != nil { + if err := tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{testKeys[1]}}); err != nil { t.Fatal(err) } return tx @@ -1135,14 +1136,14 @@ func TestImportTxSemanticVerify(t *testing.T) { semanticVerifyErr: "import tx transfer failed verification", }, "non-unique EVM Outputs": { - setup: func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx { + setup: func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx { txID := ids.GenerateTestID() utxo, err := addUTXO(sharedMemory, vm.ctx, txID, 0, vm.ctx.AVAXAssetID, 2, testShortIDAddrs[0]) if err != nil { t.Fatal(err) } - tx := &Tx{UnsignedAtomicTx: &UnsignedImportTx{ + tx := &atomic.Tx{UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, SourceChain: vm.ctx.XChainID, @@ -1154,7 +1155,7 @@ func TestImportTxSemanticVerify(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{ + Outs: []atomic.EVMOutput{ { Address: testEthAddrs[0], Amount: 1, @@ -1167,13 +1168,13 @@ func TestImportTxSemanticVerify(t *testing.T) { }, }, }} - if err := tx.Sign(vm.codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { + if err := tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { t.Fatal(err) } return tx }, genesisJSON: genesisJSONApricotPhase3, - semanticVerifyErr: errOutputsNotSortedUnique.Error(), + semanticVerifyErr: atomic.ErrOutputsNotSortedUnique.Error(), }, } @@ -1188,14 +1189,14 @@ func TestImportTxEVMStateTransfer(t *testing.T) { assetID := ids.GenerateTestID() tests := map[string]atomicTxTest{ "AVAX UTXO": { - setup: func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx { + setup: func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx { txID := ids.GenerateTestID() utxo, err := addUTXO(sharedMemory, vm.ctx, txID, 0, vm.ctx.AVAXAssetID, 1, testShortIDAddrs[0]) if err != nil { t.Fatal(err) } - tx := &Tx{UnsignedAtomicTx: &UnsignedImportTx{ + tx := &atomic.Tx{UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, SourceChain: vm.ctx.XChainID, @@ -1207,13 +1208,13 @@ func TestImportTxEVMStateTransfer(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: 1, AssetID: vm.ctx.AVAXAssetID, }}, }} - if err := tx.Sign(vm.codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { + if err := tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { t.Fatal(err) } return tx @@ -1227,20 +1228,20 @@ func TestImportTxEVMStateTransfer(t *testing.T) { } avaxBalance := sdb.GetBalance(testEthAddrs[0]) - if avaxBalance.Cmp(x2cRate) != 0 { - t.Fatalf("Expected AVAX balance to be %d, found balance: %d", x2cRate, avaxBalance) + if avaxBalance.Cmp(atomic.X2CRate) != 0 { + t.Fatalf("Expected AVAX balance to be %d, found balance: %d", *atomic.X2CRate, avaxBalance) } }, }, "non-AVAX UTXO": { - setup: func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx { + setup: func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx { txID := ids.GenerateTestID() utxo, err := addUTXO(sharedMemory, vm.ctx, txID, 0, assetID, 1, testShortIDAddrs[0]) if err != nil { t.Fatal(err) } - tx := &Tx{UnsignedAtomicTx: &UnsignedImportTx{ + tx := &atomic.Tx{UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, SourceChain: vm.ctx.XChainID, @@ -1252,13 +1253,13 @@ func TestImportTxEVMStateTransfer(t *testing.T) { Input: secp256k1fx.Input{SigIndices: []uint32{0}}, }, }}, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: testEthAddrs[0], Amount: 1, AssetID: assetID, }}, }} - if err := tx.Sign(vm.codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { + if err := tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{testKeys[0]}}); err != nil { t.Fatal(err) } return tx diff --git a/plugin/evm/mempool.go b/plugin/evm/mempool.go index 69a832cd2e..acb8db4e3f 100644 --- a/plugin/evm/mempool.go +++ b/plugin/evm/mempool.go @@ -15,6 +15,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/ava-labs/coreth/metrics" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ethereum/go-ethereum/log" ) @@ -58,12 +59,12 @@ type Mempool struct { // maxSize is the maximum number of transactions allowed to be kept in mempool maxSize int // currentTxs is the set of transactions about to be added to a block. - currentTxs map[ids.ID]*Tx + currentTxs map[ids.ID]*atomic.Tx // issuedTxs is the set of transactions that have been issued into a new block - issuedTxs map[ids.ID]*Tx + issuedTxs map[ids.ID]*atomic.Tx // discardedTxs is an LRU Cache of transactions that have been discarded after failing // verification. - discardedTxs *cache.LRU[ids.ID, *Tx] + discardedTxs *cache.LRU[ids.ID, *atomic.Tx] // Pending is a channel of length one, which the mempool ensures has an item on // it as long as there is an unissued transaction remaining in [txs] Pending chan struct{} @@ -71,17 +72,17 @@ type Mempool struct { // NOTE: [txHeap] ONLY contains pending txs txHeap *txHeap // utxoSpenders maps utxoIDs to the transaction consuming them in the mempool - utxoSpenders map[ids.ID]*Tx + utxoSpenders map[ids.ID]*atomic.Tx // bloom is a bloom filter containing the txs in the mempool bloom *gossip.BloomFilter metrics *mempoolMetrics - verify func(tx *Tx) error + verify func(tx *atomic.Tx) error } // NewMempool returns a Mempool with [maxSize] -func NewMempool(ctx *snow.Context, registerer prometheus.Registerer, maxSize int, verify func(tx *Tx) error) (*Mempool, error) { +func NewMempool(ctx *snow.Context, registerer prometheus.Registerer, maxSize int, verify func(tx *atomic.Tx) error) (*Mempool, error) { bloom, err := gossip.NewBloomFilter(registerer, "atomic_mempool_bloom_filter", txGossipBloomMinTargetElements, txGossipBloomTargetFalsePositiveRate, txGossipBloomResetFalsePositiveRate) if err != nil { return nil, fmt.Errorf("failed to initialize bloom filter: %w", err) @@ -89,13 +90,13 @@ func NewMempool(ctx *snow.Context, registerer prometheus.Registerer, maxSize int return &Mempool{ ctx: ctx, - issuedTxs: make(map[ids.ID]*Tx), - discardedTxs: &cache.LRU[ids.ID, *Tx]{Size: discardedTxsCacheSize}, - currentTxs: make(map[ids.ID]*Tx), + issuedTxs: make(map[ids.ID]*atomic.Tx), + discardedTxs: &cache.LRU[ids.ID, *atomic.Tx]{Size: discardedTxsCacheSize}, + currentTxs: make(map[ids.ID]*atomic.Tx), Pending: make(chan struct{}, 1), txHeap: newTxHeap(maxSize), maxSize: maxSize, - utxoSpenders: make(map[ids.ID]*Tx), + utxoSpenders: make(map[ids.ID]*atomic.Tx), bloom: bloom, metrics: newMempoolMetrics(), verify: verify, @@ -117,7 +118,7 @@ func (m *Mempool) length() int { // atomicTxGasPrice is the [gasPrice] paid by a transaction to burn a given // amount of [AVAXAssetID] given the value of [gasUsed]. -func (m *Mempool) atomicTxGasPrice(tx *Tx) (uint64, error) { +func (m *Mempool) atomicTxGasPrice(tx *atomic.Tx) (uint64, error) { gasUsed, err := tx.GasUsed(true) if err != nil { return 0, err @@ -158,7 +159,7 @@ func (m *Mempool) Add(tx *GossipAtomicTx) error { // AddTx attempts to add [tx] to the mempool and returns an error if // it could not be added to the mempool. -func (m *Mempool) AddTx(tx *Tx) error { +func (m *Mempool) AddTx(tx *atomic.Tx) error { m.lock.Lock() defer m.lock.Unlock() @@ -180,7 +181,7 @@ func (m *Mempool) AddTx(tx *Tx) error { return err } -func (m *Mempool) AddLocalTx(tx *Tx) error { +func (m *Mempool) AddLocalTx(tx *atomic.Tx) error { m.lock.Lock() defer m.lock.Unlock() @@ -192,8 +193,8 @@ func (m *Mempool) AddLocalTx(tx *Tx) error { return err } -// forceAddTx forcibly adds a *Tx to the mempool and bypasses all verification. -func (m *Mempool) ForceAddTx(tx *Tx) error { +// forceAddTx forcibly adds a *atomic.Tx to the mempool and bypasses all verification. +func (m *Mempool) ForceAddTx(tx *atomic.Tx) error { m.lock.Lock() defer m.lock.Unlock() @@ -208,13 +209,13 @@ func (m *Mempool) ForceAddTx(tx *Tx) error { // checkConflictTx checks for any transactions in the mempool that spend the same input UTXOs as [tx]. // If any conflicts are present, it returns the highest gas price of any conflicting transaction, the // txID of the corresponding tx and the full list of transactions that conflict with [tx]. -func (m *Mempool) checkConflictTx(tx *Tx) (uint64, ids.ID, []*Tx, error) { +func (m *Mempool) checkConflictTx(tx *atomic.Tx) (uint64, ids.ID, []*atomic.Tx, error) { utxoSet := tx.InputUTXOs() var ( - highestGasPrice uint64 = 0 - conflictingTxs []*Tx = make([]*Tx, 0) - highestGasPriceConflictTxID ids.ID = ids.ID{} + highestGasPrice uint64 = 0 + conflictingTxs []*atomic.Tx = make([]*atomic.Tx, 0) + highestGasPriceConflictTxID ids.ID = ids.ID{} ) for utxoID := range utxoSet { // Get current gas price of the existing tx in the mempool @@ -239,7 +240,7 @@ func (m *Mempool) checkConflictTx(tx *Tx) (uint64, ids.ID, []*Tx, error) { // addTx adds [tx] to the mempool. Assumes [m.lock] is held. // If [force], skips conflict checks within the mempool. -func (m *Mempool) addTx(tx *Tx, force bool) error { +func (m *Mempool) addTx(tx *atomic.Tx, force bool) error { txID := tx.ID() // If [txID] has already been issued or is in the currentTxs map // there's no need to add it. @@ -371,7 +372,7 @@ func (m *Mempool) GetFilter() ([]byte, []byte) { } // NextTx returns a transaction to be issued from the mempool. -func (m *Mempool) NextTx() (*Tx, bool) { +func (m *Mempool) NextTx() (*atomic.Tx, bool) { m.lock.Lock() defer m.lock.Unlock() @@ -391,7 +392,7 @@ func (m *Mempool) NextTx() (*Tx, bool) { // GetPendingTx returns the transaction [txID] and true if it is // currently in the [txHeap] waiting to be issued into a block. // Returns nil, false otherwise. -func (m *Mempool) GetPendingTx(txID ids.ID) (*Tx, bool) { +func (m *Mempool) GetPendingTx(txID ids.ID) (*atomic.Tx, bool) { m.lock.RLock() defer m.lock.RUnlock() @@ -401,7 +402,7 @@ func (m *Mempool) GetPendingTx(txID ids.ID) (*Tx, bool) { // GetTx returns the transaction [txID] if it was issued // by this node and returns whether it was dropped and whether // it exists. -func (m *Mempool) GetTx(txID ids.ID) (*Tx, bool, bool) { +func (m *Mempool) GetTx(txID ids.ID) (*atomic.Tx, bool, bool) { m.lock.RLock() defer m.lock.RUnlock() @@ -484,7 +485,7 @@ func (m *Mempool) CancelCurrentTxs() { // cancelTx removes [tx] from current transactions and moves it back into the // tx heap. // assumes the lock is held. -func (m *Mempool) cancelTx(tx *Tx) { +func (m *Mempool) cancelTx(tx *atomic.Tx) { // Add tx to heap sorted by gasPrice gasPrice, err := m.atomicTxGasPrice(tx) if err == nil { @@ -526,7 +527,7 @@ func (m *Mempool) DiscardCurrentTxs() { // discardCurrentTx discards [tx] from the set of current transactions. // Assumes the lock is held. -func (m *Mempool) discardCurrentTx(tx *Tx) { +func (m *Mempool) discardCurrentTx(tx *atomic.Tx) { m.removeSpenders(tx) m.discardedTxs.Put(tx.ID(), tx) delete(m.currentTxs, tx.ID()) @@ -540,7 +541,7 @@ func (m *Mempool) discardCurrentTx(tx *Tx) { // removeTx must be called for all conflicts before overwriting the utxoSpenders // map. // Assumes lock is held. -func (m *Mempool) removeTx(tx *Tx, discard bool) { +func (m *Mempool) removeTx(tx *atomic.Tx, discard bool) { txID := tx.ID() // Remove from [currentTxs], [txHeap], and [issuedTxs]. @@ -565,7 +566,7 @@ func (m *Mempool) removeTx(tx *Tx, discard bool) { // removeSpenders deletes the entries for all input UTXOs of [tx] from the // [utxoSpenders] map. // Assumes the lock is held. -func (m *Mempool) removeSpenders(tx *Tx) { +func (m *Mempool) removeSpenders(tx *atomic.Tx) { for utxoID := range tx.InputUTXOs() { delete(m.utxoSpenders, utxoID) } @@ -573,7 +574,7 @@ func (m *Mempool) removeSpenders(tx *Tx) { // RemoveTx removes [txID] from the mempool completely. // Evicts [tx] from the discarded cache if present. -func (m *Mempool) RemoveTx(tx *Tx) { +func (m *Mempool) RemoveTx(tx *atomic.Tx) { m.lock.Lock() defer m.lock.Unlock() diff --git a/plugin/evm/mempool_atomic_gossiping_test.go b/plugin/evm/mempool_atomic_gossiping_test.go index b44f2097b4..3e22fef486 100644 --- a/plugin/evm/mempool_atomic_gossiping_test.go +++ b/plugin/evm/mempool_atomic_gossiping_test.go @@ -11,6 +11,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/components/chain" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/stretchr/testify/assert" ) @@ -32,7 +33,7 @@ func TestMempoolAddLocallyCreateAtomicTx(t *testing.T) { // generate a valid and conflicting tx var ( - tx, conflictingTx *Tx + tx, conflictingTx *atomic.Tx ) if name == "import" { importTxs := createImportTxOptions(t, vm, sharedMemory) diff --git a/plugin/evm/mempool_test.go b/plugin/evm/mempool_test.go index a56c43bbee..8129edc577 100644 --- a/plugin/evm/mempool_test.go +++ b/plugin/evm/mempool_test.go @@ -8,6 +8,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" ) @@ -20,7 +21,7 @@ func TestMempoolAddTx(t *testing.T) { txs := make([]*GossipAtomicTx, 0) for i := 0; i < 3_000; i++ { tx := &GossipAtomicTx{ - Tx: &Tx{ + Tx: &atomic.Tx{ UnsignedAtomicTx: &TestUnsignedTx{ IDV: ids.GenerateTestID(), }, @@ -43,7 +44,7 @@ func TestMempoolAdd(t *testing.T) { require.NoError(err) tx := &GossipAtomicTx{ - Tx: &Tx{ + Tx: &atomic.Tx{ UnsignedAtomicTx: &TestUnsignedTx{ IDV: ids.GenerateTestID(), }, diff --git a/plugin/evm/service.go b/plugin/evm/service.go index 7f57be5520..40f09314f4 100644 --- a/plugin/evm/service.go +++ b/plugin/evm/service.go @@ -12,11 +12,12 @@ import ( "github.com/ava-labs/avalanchego/api" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/formatting" "github.com/ava-labs/avalanchego/utils/json" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/atomic" + "github.com/ava-labs/coreth/plugin/evm/client" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/log" @@ -91,24 +92,11 @@ func (service *AvaxAPI) Version(r *http.Request, _ *struct{}, reply *VersionRepl return nil } -// ExportKeyArgs are arguments for ExportKey -type ExportKeyArgs struct { - api.UserPass - Address string `json:"address"` -} - -// ExportKeyReply is the response for ExportKey -type ExportKeyReply struct { - // The decrypted PrivateKey for the Address provided in the arguments - PrivateKey *secp256k1.PrivateKey `json:"privateKey"` - PrivateKeyHex string `json:"privateKeyHex"` -} - // ExportKey returns a private key from the provided user -func (service *AvaxAPI) ExportKey(r *http.Request, args *ExportKeyArgs, reply *ExportKeyReply) error { +func (service *AvaxAPI) ExportKey(r *http.Request, args *client.ExportKeyArgs, reply *client.ExportKeyReply) error { log.Info("EVM: ExportKey called") - address, err := ParseEthAddress(args.Address) + address, err := client.ParseEthAddress(args.Address) if err != nil { return fmt.Errorf("couldn't parse %s to address: %s", args.Address, err) } @@ -131,21 +119,15 @@ func (service *AvaxAPI) ExportKey(r *http.Request, args *ExportKeyArgs, reply *E return nil } -// ImportKeyArgs are arguments for ImportKey -type ImportKeyArgs struct { - api.UserPass - PrivateKey *secp256k1.PrivateKey `json:"privateKey"` -} - // ImportKey adds a private key to the provided user -func (service *AvaxAPI) ImportKey(r *http.Request, args *ImportKeyArgs, reply *api.JSONAddress) error { +func (service *AvaxAPI) ImportKey(r *http.Request, args *client.ImportKeyArgs, reply *api.JSONAddress) error { log.Info("EVM: ImportKey called", "username", args.Username) if args.PrivateKey == nil { return errMissingPrivateKey } - reply.Address = GetEthAddress(args.PrivateKey).Hex() + reply.Address = args.PrivateKey.EthAddress().Hex() service.vm.ctx.Lock.Lock() defer service.vm.ctx.Lock.Unlock() @@ -163,28 +145,14 @@ func (service *AvaxAPI) ImportKey(r *http.Request, args *ImportKeyArgs, reply *a return nil } -// ImportArgs are arguments for passing into Import requests -type ImportArgs struct { - api.UserPass - - // Fee that should be used when creating the tx - BaseFee *hexutil.Big `json:"baseFee"` - - // Chain the funds are coming from - SourceChain string `json:"sourceChain"` - - // The address that will receive the imported funds - To common.Address `json:"to"` -} - // ImportAVAX is a deprecated name for Import. -func (service *AvaxAPI) ImportAVAX(_ *http.Request, args *ImportArgs, response *api.JSONTxID) error { +func (service *AvaxAPI) ImportAVAX(_ *http.Request, args *client.ImportArgs, response *api.JSONTxID) error { return service.Import(nil, args, response) } // Import issues a transaction to import AVAX from the X-chain. The AVAX // must have already been exported from the X-Chain. -func (service *AvaxAPI) Import(_ *http.Request, args *ImportArgs, response *api.JSONTxID) error { +func (service *AvaxAPI) Import(_ *http.Request, args *client.ImportArgs, response *api.JSONTxID) error { log.Info("EVM: ImportAVAX called") chainID, err := service.vm.ctx.BCLookup.Lookup(args.SourceChain) @@ -232,44 +200,18 @@ func (service *AvaxAPI) Import(_ *http.Request, args *ImportArgs, response *api. return nil } -// ExportAVAXArgs are the arguments to ExportAVAX -type ExportAVAXArgs struct { - api.UserPass - - // Fee that should be used when creating the tx - BaseFee *hexutil.Big `json:"baseFee"` - - // Amount of asset to send - Amount json.Uint64 `json:"amount"` - - // Chain the funds are going to. Optional. Used if To address does not - // include the chainID. - TargetChain string `json:"targetChain"` - - // ID of the address that will receive the AVAX. This address may include - // the chainID, which is used to determine what the destination chain is. - To string `json:"to"` -} - // ExportAVAX exports AVAX from the C-Chain to the X-Chain // It must be imported on the X-Chain to complete the transfer -func (service *AvaxAPI) ExportAVAX(_ *http.Request, args *ExportAVAXArgs, response *api.JSONTxID) error { - return service.Export(nil, &ExportArgs{ +func (service *AvaxAPI) ExportAVAX(_ *http.Request, args *client.ExportAVAXArgs, response *api.JSONTxID) error { + return service.Export(nil, &client.ExportArgs{ ExportAVAXArgs: *args, AssetID: service.vm.ctx.AVAXAssetID.String(), }, response) } -// ExportArgs are the arguments to Export -type ExportArgs struct { - ExportAVAXArgs - // AssetID of the tokens - AssetID string `json:"assetID"` -} - // Export exports an asset from the C-Chain to the X-Chain // It must be imported on the X-Chain to complete the transfer -func (service *AvaxAPI) Export(_ *http.Request, args *ExportArgs, response *api.JSONTxID) error { +func (service *AvaxAPI) Export(_ *http.Request, args *client.ExportArgs, response *api.JSONTxID) error { log.Info("EVM: Export called") assetID, err := service.parseAssetID(args.AssetID) @@ -401,7 +343,7 @@ func (service *AvaxAPI) GetUTXOs(r *http.Request, args *api.GetUTXOsArgs, reply reply.UTXOs = make([]string, len(utxos)) for i, utxo := range utxos { - b, err := service.vm.codec.Marshal(codecVersion, utxo) + b, err := atomic.Codec.Marshal(atomic.CodecVersion, utxo) if err != nil { return fmt.Errorf("problem marshalling UTXO: %w", err) } @@ -432,11 +374,11 @@ func (service *AvaxAPI) IssueTx(r *http.Request, args *api.FormattedTx, response return fmt.Errorf("problem decoding transaction: %w", err) } - tx := &Tx{} - if _, err := service.vm.codec.Unmarshal(txBytes, tx); err != nil { + tx := &atomic.Tx{} + if _, err := atomic.Codec.Unmarshal(txBytes, tx); err != nil { return fmt.Errorf("problem parsing transaction: %w", err) } - if err := tx.Sign(service.vm.codec, nil); err != nil { + if err := tx.Sign(atomic.Codec, nil); err != nil { return fmt.Errorf("problem initializing transaction: %w", err) } @@ -452,14 +394,8 @@ func (service *AvaxAPI) IssueTx(r *http.Request, args *api.FormattedTx, response return nil } -// GetAtomicTxStatusReply defines the GetAtomicTxStatus replies returned from the API -type GetAtomicTxStatusReply struct { - Status Status `json:"status"` - BlockHeight *json.Uint64 `json:"blockHeight,omitempty"` -} - // GetAtomicTxStatus returns the status of the specified transaction -func (service *AvaxAPI) GetAtomicTxStatus(r *http.Request, args *api.JSONTxID, reply *GetAtomicTxStatusReply) error { +func (service *AvaxAPI) GetAtomicTxStatus(r *http.Request, args *api.JSONTxID, reply *client.GetAtomicTxStatusReply) error { log.Info("EVM: GetAtomicTxStatus called", "txID", args.TxID) if args.TxID == ids.Empty { @@ -472,13 +408,13 @@ func (service *AvaxAPI) GetAtomicTxStatus(r *http.Request, args *api.JSONTxID, r _, status, height, _ := service.vm.getAtomicTx(args.TxID) reply.Status = status - if status == Accepted { + if status == atomic.Accepted { // Since chain state updates run asynchronously with VM block acceptance, // avoid returning [Accepted] until the chain state reaches the block // containing the atomic tx. lastAccepted := service.vm.blockChain.LastAcceptedBlock() if height > lastAccepted.NumberU64() { - reply.Status = Processing + reply.Status = atomic.Processing return nil } @@ -509,7 +445,7 @@ func (service *AvaxAPI) GetAtomicTx(r *http.Request, args *api.GetTxArgs, reply return err } - if status == Unknown { + if status == atomic.Unknown { return fmt.Errorf("could not find tx %s", args.TxID) } @@ -519,7 +455,7 @@ func (service *AvaxAPI) GetAtomicTx(r *http.Request, args *api.GetTxArgs, reply } reply.Tx = txBytes reply.Encoding = args.Encoding - if status == Accepted { + if status == atomic.Accepted { // Since chain state updates run asynchronously with VM block acceptance, // avoid returning [Accepted] until the chain state reaches the block // containing the atomic tx. diff --git a/plugin/evm/syncervm_test.go b/plugin/evm/syncervm_test.go index bba4663153..bd7f993cb5 100644 --- a/plugin/evm/syncervm_test.go +++ b/plugin/evm/syncervm_test.go @@ -15,7 +15,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/ids" @@ -35,6 +35,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/predicate" statesyncclient "github.com/ava-labs/coreth/sync/client" "github.com/ava-labs/coreth/sync/statesync" @@ -291,7 +292,7 @@ func createSyncServerAndClientVMs(t *testing.T, test syncTest, numBlocks int) *s require.NoError(serverVM.Shutdown(context.Background())) }) var ( - importTx, exportTx *Tx + importTx, exportTx *atomic.Tx err error ) generateAndAcceptBlocks(t, serverVM, numBlocks, func(i int, gen *core.BlockGen) { @@ -336,8 +337,8 @@ func createSyncServerAndClientVMs(t *testing.T, test syncTest, numBlocks int) *s require.NoError(serverVM.db.Commit()) serverSharedMemories := newSharedMemories(serverAtomicMemory, serverVM.ctx.ChainID, serverVM.ctx.XChainID) - serverSharedMemories.assertOpsApplied(t, importTx.mustAtomicOps()) - serverSharedMemories.assertOpsApplied(t, exportTx.mustAtomicOps()) + serverSharedMemories.assertOpsApplied(t, mustAtomicOps(importTx)) + serverSharedMemories.assertOpsApplied(t, mustAtomicOps(exportTx)) // make some accounts trieDB := triedb.NewDatabase(serverVM.chaindb, nil) @@ -406,7 +407,7 @@ func createSyncServerAndClientVMs(t *testing.T, test syncTest, numBlocks int) *s return &syncVMSetup{ serverVM: serverVM, serverAppSender: serverAppSender, - includedAtomicTxs: []*Tx{ + includedAtomicTxs: []*atomic.Tx{ importTx, exportTx, }, @@ -425,13 +426,13 @@ type syncVMSetup struct { serverVM *VM serverAppSender *enginetest.Sender - includedAtomicTxs []*Tx + includedAtomicTxs []*atomic.Tx fundedAccounts map[*keystore.Key]*types.StateAccount syncerVM *VM syncerDB database.Database syncerEngineChan <-chan commonEng.Message - syncerAtomicMemory *atomic.Memory + syncerAtomicMemory *avalancheatomic.Memory shutdownOnceSyncerVM *shutdownOnceVM } @@ -560,7 +561,7 @@ func testSyncerVM(t *testing.T, vmSetup *syncVMSetup, test syncTest) { syncerSharedMemories := newSharedMemories(syncerAtomicMemory, syncerVM.ctx.ChainID, syncerVM.ctx.XChainID) for _, tx := range includedAtomicTxs { - syncerSharedMemories.assertOpsApplied(t, tx.mustAtomicOps()) + syncerSharedMemories.assertOpsApplied(t, mustAtomicOps(tx)) } // Generate blocks after we have entered normal consensus as well diff --git a/plugin/evm/test_tx.go b/plugin/evm/test_tx.go index c057c874ad..e001cb4dda 100644 --- a/plugin/evm/test_tx.go +++ b/plugin/evm/test_tx.go @@ -9,21 +9,21 @@ import ( "github.com/ava-labs/avalanchego/utils" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/codec/linearcodec" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/atomic" ) type TestUnsignedTx struct { - GasUsedV uint64 `serialize:"true"` - AcceptRequestsBlockchainIDV ids.ID `serialize:"true"` - AcceptRequestsV *atomic.Requests `serialize:"true"` + GasUsedV uint64 `serialize:"true"` + AcceptRequestsBlockchainIDV ids.ID `serialize:"true"` + AcceptRequestsV *avalancheatomic.Requests `serialize:"true"` VerifyV error IDV ids.ID `serialize:"true" json:"id"` BurnedV uint64 `serialize:"true"` @@ -34,7 +34,7 @@ type TestUnsignedTx struct { EVMStateTransferV error } -var _ UnsignedAtomicTx = &TestUnsignedTx{} +var _ atomic.UnsignedAtomicTx = &TestUnsignedTx{} // GasUsed implements the UnsignedAtomicTx interface func (t *TestUnsignedTx) GasUsed(fixedFee bool) (uint64, error) { return t.GasUsedV, nil } @@ -43,7 +43,7 @@ func (t *TestUnsignedTx) GasUsed(fixedFee bool) (uint64, error) { return t.GasUs func (t *TestUnsignedTx) Verify(ctx *snow.Context, rules params.Rules) error { return t.VerifyV } // AtomicOps implements the UnsignedAtomicTx interface -func (t *TestUnsignedTx) AtomicOps() (ids.ID, *atomic.Requests, error) { +func (t *TestUnsignedTx) AtomicOps() (ids.ID, *avalancheatomic.Requests, error) { return t.AcceptRequestsBlockchainIDV, t.AcceptRequestsV, nil } @@ -66,12 +66,12 @@ func (t *TestUnsignedTx) SignedBytes() []byte { return t.SignedBytesV } func (t *TestUnsignedTx) InputUTXOs() set.Set[ids.ID] { return t.InputUTXOsV } // SemanticVerify implements the UnsignedAtomicTx interface -func (t *TestUnsignedTx) SemanticVerify(vm *VM, stx *Tx, parent *Block, baseFee *big.Int, rules params.Rules) error { +func (t *TestUnsignedTx) SemanticVerify(backend *atomic.Backend, stx *atomic.Tx, parent atomic.AtomicBlockContext, baseFee *big.Int) error { return t.SemanticVerifyV } // EVMStateTransfer implements the UnsignedAtomicTx interface -func (t *TestUnsignedTx) EVMStateTransfer(ctx *snow.Context, state *state.StateDB) error { +func (t *TestUnsignedTx) EVMStateTransfer(ctx *snow.Context, state atomic.StateDB) error { return t.EVMStateTransferV } @@ -82,9 +82,9 @@ func testTxCodec() codec.Manager { errs := wrappers.Errs{} errs.Add( c.RegisterType(&TestUnsignedTx{}), - c.RegisterType(&atomic.Element{}), - c.RegisterType(&atomic.Requests{}), - codec.RegisterCodec(codecVersion, c), + c.RegisterType(&avalancheatomic.Element{}), + c.RegisterType(&avalancheatomic.Requests{}), + codec.RegisterCodec(atomic.CodecVersion, c), ) if errs.Errored() { @@ -95,12 +95,12 @@ func testTxCodec() codec.Manager { var blockChainID = ids.GenerateTestID() -func testDataImportTx() *Tx { - return &Tx{ +func testDataImportTx() *atomic.Tx { + return &atomic.Tx{ UnsignedAtomicTx: &TestUnsignedTx{ IDV: ids.GenerateTestID(), AcceptRequestsBlockchainIDV: blockChainID, - AcceptRequestsV: &atomic.Requests{ + AcceptRequestsV: &avalancheatomic.Requests{ RemoveRequests: [][]byte{ utils.RandomBytes(32), utils.RandomBytes(32), @@ -110,13 +110,13 @@ func testDataImportTx() *Tx { } } -func testDataExportTx() *Tx { - return &Tx{ +func testDataExportTx() *atomic.Tx { + return &atomic.Tx{ UnsignedAtomicTx: &TestUnsignedTx{ IDV: ids.GenerateTestID(), AcceptRequestsBlockchainIDV: blockChainID, - AcceptRequestsV: &atomic.Requests{ - PutRequests: []*atomic.Element{ + AcceptRequestsV: &avalancheatomic.Requests{ + PutRequests: []*avalancheatomic.Element{ { Key: utils.RandomBytes(16), Value: utils.RandomBytes(24), @@ -131,7 +131,7 @@ func testDataExportTx() *Tx { } } -func newTestTx() *Tx { +func newTestTx() *atomic.Tx { txType := rand.Intn(2) switch txType { case 0: @@ -143,8 +143,8 @@ func newTestTx() *Tx { } } -func newTestTxs(numTxs int) []*Tx { - txs := make([]*Tx, 0, numTxs) +func newTestTxs(numTxs int) []*atomic.Tx { + txs := make([]*atomic.Tx, 0, numTxs) for i := 0; i < numTxs; i++ { txs = append(txs, newTestTx()) } diff --git a/plugin/evm/tx_gossip_test.go b/plugin/evm/tx_gossip_test.go index af544e9415..514b7fadbd 100644 --- a/plugin/evm/tx_gossip_test.go +++ b/plugin/evm/tx_gossip_test.go @@ -11,7 +11,7 @@ import ( "testing" "time" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/network/p2p" @@ -35,6 +35,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/utils" ) @@ -47,7 +48,7 @@ func TestEthTxGossip(t *testing.T) { pk, err := secp256k1.NewPrivateKey() require.NoError(err) - address := GetEthAddress(pk) + address := pk.EthAddress() genesis := newPrefundedGenesis(100_000_000_000_000_000, address) genesisBytes, err := genesis.MarshalJSON() require.NoError(err) @@ -170,12 +171,12 @@ func TestAtomicTxGossip(t *testing.T) { snowCtx.AVAXAssetID = ids.GenerateTestID() validatorState := utils.NewTestValidatorState() snowCtx.ValidatorState = validatorState - memory := atomic.NewMemory(memdb.New()) + memory := avalancheatomic.NewMemory(memdb.New()) snowCtx.SharedMemory = memory.NewSharedMemory(snowCtx.ChainID) pk, err := secp256k1.NewPrivateKey() require.NoError(err) - address := GetEthAddress(pk) + address := pk.EthAddress() genesis := newPrefundedGenesis(100_000_000_000_000_000, address) genesisBytes, err := genesis.MarshalJSON() require.NoError(err) @@ -264,10 +265,10 @@ func TestAtomicTxGossip(t *testing.T) { 0, snowCtx.AVAXAssetID, 100_000_000_000, - pk.PublicKey().Address(), + pk.Address(), ) require.NoError(err) - tx, err := vm.newImportTxWithUTXOs(vm.ctx.XChainID, address, initialBaseFee, secp256k1fx.NewKeychain(pk), []*avax.UTXO{utxo}) + tx, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, address, initialBaseFee, secp256k1fx.NewKeychain(pk), []*avax.UTXO{utxo}) require.NoError(err) require.NoError(vm.mempool.AddLocalTx(tx)) @@ -314,7 +315,7 @@ func TestEthTxPushGossipOutbound(t *testing.T) { pk, err := secp256k1.NewPrivateKey() require.NoError(err) - address := GetEthAddress(pk) + address := pk.EthAddress() genesis := newPrefundedGenesis(100_000_000_000_000_000, address) genesisBytes, err := genesis.MarshalJSON() require.NoError(err) @@ -374,7 +375,7 @@ func TestEthTxPushGossipInbound(t *testing.T) { pk, err := secp256k1.NewPrivateKey() require.NoError(err) - address := GetEthAddress(pk) + address := pk.EthAddress() genesis := newPrefundedGenesis(100_000_000_000_000_000, address) genesisBytes, err := genesis.MarshalJSON() require.NoError(err) @@ -428,12 +429,12 @@ func TestAtomicTxPushGossipOutbound(t *testing.T) { snowCtx.AVAXAssetID = ids.GenerateTestID() validatorState := utils.NewTestValidatorState() snowCtx.ValidatorState = validatorState - memory := atomic.NewMemory(memdb.New()) + memory := avalancheatomic.NewMemory(memdb.New()) snowCtx.SharedMemory = memory.NewSharedMemory(snowCtx.ChainID) pk, err := secp256k1.NewPrivateKey() require.NoError(err) - address := GetEthAddress(pk) + address := pk.EthAddress() genesis := newPrefundedGenesis(100_000_000_000_000_000, address) genesisBytes, err := genesis.MarshalJSON() require.NoError(err) @@ -472,10 +473,10 @@ func TestAtomicTxPushGossipOutbound(t *testing.T) { 0, snowCtx.AVAXAssetID, 100_000_000_000, - pk.PublicKey().Address(), + pk.Address(), ) require.NoError(err) - tx, err := vm.newImportTxWithUTXOs(vm.ctx.XChainID, address, initialBaseFee, secp256k1fx.NewKeychain(pk), []*avax.UTXO{utxo}) + tx, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, address, initialBaseFee, secp256k1fx.NewKeychain(pk), []*avax.UTXO{utxo}) require.NoError(err) require.NoError(vm.mempool.AddLocalTx(tx)) vm.atomicTxPushGossiper.Add(&GossipAtomicTx{tx}) @@ -501,12 +502,12 @@ func TestAtomicTxPushGossipInbound(t *testing.T) { snowCtx.AVAXAssetID = ids.GenerateTestID() validatorState := utils.NewTestValidatorState() snowCtx.ValidatorState = validatorState - memory := atomic.NewMemory(memdb.New()) + memory := avalancheatomic.NewMemory(memdb.New()) snowCtx.SharedMemory = memory.NewSharedMemory(snowCtx.ChainID) pk, err := secp256k1.NewPrivateKey() require.NoError(err) - address := GetEthAddress(pk) + address := pk.EthAddress() genesis := newPrefundedGenesis(100_000_000_000_000_000, address) genesisBytes, err := genesis.MarshalJSON() require.NoError(err) @@ -543,10 +544,10 @@ func TestAtomicTxPushGossipInbound(t *testing.T) { 0, snowCtx.AVAXAssetID, 100_000_000_000, - pk.PublicKey().Address(), + pk.Address(), ) require.NoError(err) - tx, err := vm.newImportTxWithUTXOs(vm.ctx.XChainID, address, initialBaseFee, secp256k1fx.NewKeychain(pk), []*avax.UTXO{utxo}) + tx, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, address, initialBaseFee, secp256k1fx.NewKeychain(pk), []*avax.UTXO{utxo}) require.NoError(err) require.NoError(vm.mempool.AddLocalTx(tx)) diff --git a/plugin/evm/tx_heap.go b/plugin/evm/tx_heap.go index d44020039e..c6562fd9b0 100644 --- a/plugin/evm/tx_heap.go +++ b/plugin/evm/tx_heap.go @@ -7,6 +7,7 @@ import ( "container/heap" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/coreth/plugin/evm/atomic" ) // txEntry is used to track the [gasPrice] transactions pay to be included in @@ -14,7 +15,7 @@ import ( type txEntry struct { id ids.ID gasPrice uint64 - tx *Tx + tx *atomic.Tx index int } @@ -91,7 +92,7 @@ func newTxHeap(maxSize int) *txHeap { } } -func (th *txHeap) Push(tx *Tx, gasPrice uint64) { +func (th *txHeap) Push(tx *atomic.Tx, gasPrice uint64) { txID := tx.ID() oldLen := th.Len() heap.Push(th.maxHeap, &txEntry{ @@ -109,28 +110,28 @@ func (th *txHeap) Push(tx *Tx, gasPrice uint64) { } // Assumes there is non-zero items in [txHeap] -func (th *txHeap) PeekMax() (*Tx, uint64) { +func (th *txHeap) PeekMax() (*atomic.Tx, uint64) { txEntry := th.maxHeap.items[0] return txEntry.tx, txEntry.gasPrice } // Assumes there is non-zero items in [txHeap] -func (th *txHeap) PeekMin() (*Tx, uint64) { +func (th *txHeap) PeekMin() (*atomic.Tx, uint64) { txEntry := th.minHeap.items[0] return txEntry.tx, txEntry.gasPrice } // Assumes there is non-zero items in [txHeap] -func (th *txHeap) PopMax() *Tx { +func (th *txHeap) PopMax() *atomic.Tx { return th.Remove(th.maxHeap.items[0].id) } // Assumes there is non-zero items in [txHeap] -func (th *txHeap) PopMin() *Tx { +func (th *txHeap) PopMin() *atomic.Tx { return th.Remove(th.minHeap.items[0].id) } -func (th *txHeap) Remove(id ids.ID) *Tx { +func (th *txHeap) Remove(id ids.ID) *atomic.Tx { maxEntry, ok := th.maxHeap.Get(id) if !ok { return nil @@ -150,7 +151,7 @@ func (th *txHeap) Len() int { return th.maxHeap.Len() } -func (th *txHeap) Get(id ids.ID) (*Tx, bool) { +func (th *txHeap) Get(id ids.ID) (*atomic.Tx, bool) { txEntry, ok := th.maxHeap.Get(id) if !ok { return nil, false diff --git a/plugin/evm/tx_heap_test.go b/plugin/evm/tx_heap_test.go index 206b87bbdb..a054b7362e 100644 --- a/plugin/evm/tx_heap_test.go +++ b/plugin/evm/tx_heap_test.go @@ -6,27 +6,28 @@ package evm import ( "testing" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/stretchr/testify/assert" ) func TestTxHeap(t *testing.T) { var ( - tx0 = &Tx{ - UnsignedAtomicTx: &UnsignedImportTx{ + tx0 = &atomic.Tx{ + UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: 0, }, } tx0Bytes = []byte{0} - tx1 = &Tx{ - UnsignedAtomicTx: &UnsignedImportTx{ + tx1 = &atomic.Tx{ + UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: 1, }, } tx1Bytes = []byte{1} - tx2 = &Tx{ - UnsignedAtomicTx: &UnsignedImportTx{ + tx2 = &atomic.Tx{ + UnsignedAtomicTx: &atomic.UnsignedImportTx{ NetworkID: 2, }, } diff --git a/plugin/evm/tx_test.go b/plugin/evm/tx_test.go index d99ee70309..a710a3c9e1 100644 --- a/plugin/evm/tx_test.go +++ b/plugin/evm/tx_test.go @@ -14,8 +14,9 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" ) @@ -30,7 +31,7 @@ func TestCalculateDynamicFee(t *testing.T) { var tests []test = []test{ { gas: 1, - baseFee: new(big.Int).Set(x2cRate.ToBig()), + baseFee: new(big.Int).Set(atomic.X2CRate.ToBig()), expectedValue: 1, }, { @@ -41,7 +42,7 @@ func TestCalculateDynamicFee(t *testing.T) { } for _, test := range tests { - cost, err := CalculateDynamicFee(test.gas, test.baseFee) + cost, err := atomic.CalculateDynamicFee(test.gas, test.baseFee) if test.expectedErr == nil { if err != nil { t.Fatalf("Unexpectedly failed to calculate dynamic fee: %s", err) @@ -59,7 +60,7 @@ func TestCalculateDynamicFee(t *testing.T) { type atomicTxVerifyTest struct { ctx *snow.Context - generate func(t *testing.T) UnsignedAtomicTx + generate func(t *testing.T) atomic.UnsignedAtomicTx rules params.Rules expectedErr string } @@ -78,7 +79,7 @@ func executeTxVerifyTest(t *testing.T, test atomicTxVerifyTest) { type atomicTxTest struct { // setup returns the atomic transaction for the test - setup func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) *Tx + setup func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) *atomic.Tx // define a string that should be contained in the error message if the tx fails verification // at some point. If the strings are empty, then the tx should pass verification at the // respective step. @@ -115,7 +116,15 @@ func executeTxTest(t *testing.T, test atomicTxTest) { } lastAcceptedBlock := vm.LastAcceptedBlockInternal().(*Block) - if err := tx.UnsignedAtomicTx.SemanticVerify(vm, tx, lastAcceptedBlock, baseFee, rules); len(test.semanticVerifyErr) == 0 && err != nil { + backend := &atomic.Backend{ + Ctx: vm.ctx, + Fx: &vm.fx, + Rules: rules, + Bootstrapped: vm.bootstrapped.Get(), + BlockFetcher: vm, + SecpCache: &vm.secpCache, + } + if err := tx.UnsignedAtomicTx.SemanticVerify(backend, tx, lastAcceptedBlock, baseFee); len(test.semanticVerifyErr) == 0 && err != nil { t.Fatalf("SemanticVerify failed unexpectedly due to: %s", err) } else if len(test.semanticVerifyErr) != 0 { if err == nil { @@ -191,18 +200,18 @@ func executeTxTest(t *testing.T, test atomicTxTest) { func TestEVMOutputCompare(t *testing.T) { type test struct { name string - a, b EVMOutput + a, b atomic.EVMOutput expected int } tests := []test{ { name: "address less", - a: EVMOutput{ + a: atomic.EVMOutput{ Address: common.BytesToAddress([]byte{0x01}), AssetID: ids.ID{1}, }, - b: EVMOutput{ + b: atomic.EVMOutput{ Address: common.BytesToAddress([]byte{0x02}), AssetID: ids.ID{0}, }, @@ -210,11 +219,11 @@ func TestEVMOutputCompare(t *testing.T) { }, { name: "address greater; assetIDs equal", - a: EVMOutput{ + a: atomic.EVMOutput{ Address: common.BytesToAddress([]byte{0x02}), AssetID: ids.ID{}, }, - b: EVMOutput{ + b: atomic.EVMOutput{ Address: common.BytesToAddress([]byte{0x01}), AssetID: ids.ID{}, }, @@ -222,11 +231,11 @@ func TestEVMOutputCompare(t *testing.T) { }, { name: "addresses equal; assetID less", - a: EVMOutput{ + a: atomic.EVMOutput{ Address: common.BytesToAddress([]byte{0x01}), AssetID: ids.ID{0}, }, - b: EVMOutput{ + b: atomic.EVMOutput{ Address: common.BytesToAddress([]byte{0x01}), AssetID: ids.ID{1}, }, @@ -234,8 +243,8 @@ func TestEVMOutputCompare(t *testing.T) { }, { name: "equal", - a: EVMOutput{}, - b: EVMOutput{}, + a: atomic.EVMOutput{}, + b: atomic.EVMOutput{}, expected: 0, }, } @@ -253,18 +262,18 @@ func TestEVMOutputCompare(t *testing.T) { func TestEVMInputCompare(t *testing.T) { type test struct { name string - a, b EVMInput + a, b atomic.EVMInput expected int } tests := []test{ { name: "address less", - a: EVMInput{ + a: atomic.EVMInput{ Address: common.BytesToAddress([]byte{0x01}), AssetID: ids.ID{1}, }, - b: EVMInput{ + b: atomic.EVMInput{ Address: common.BytesToAddress([]byte{0x02}), AssetID: ids.ID{0}, }, @@ -272,11 +281,11 @@ func TestEVMInputCompare(t *testing.T) { }, { name: "address greater; assetIDs equal", - a: EVMInput{ + a: atomic.EVMInput{ Address: common.BytesToAddress([]byte{0x02}), AssetID: ids.ID{}, }, - b: EVMInput{ + b: atomic.EVMInput{ Address: common.BytesToAddress([]byte{0x01}), AssetID: ids.ID{}, }, @@ -284,11 +293,11 @@ func TestEVMInputCompare(t *testing.T) { }, { name: "addresses equal; assetID less", - a: EVMInput{ + a: atomic.EVMInput{ Address: common.BytesToAddress([]byte{0x01}), AssetID: ids.ID{0}, }, - b: EVMInput{ + b: atomic.EVMInput{ Address: common.BytesToAddress([]byte{0x01}), AssetID: ids.ID{1}, }, @@ -296,8 +305,8 @@ func TestEVMInputCompare(t *testing.T) { }, { name: "equal", - a: EVMInput{}, - b: EVMInput{}, + a: atomic.EVMInput{}, + b: atomic.EVMInput{}, expected: 0, }, } diff --git a/plugin/evm/user.go b/plugin/evm/user.go index 330d03b01d..8cb3f73f34 100644 --- a/plugin/evm/user.go +++ b/plugin/evm/user.go @@ -9,6 +9,7 @@ import ( "github.com/ava-labs/avalanchego/database/encdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ethereum/go-ethereum/common" ) @@ -47,7 +48,7 @@ func (u *user) getAddresses() ([]common.Address, error) { return nil, err } addresses := []common.Address{} - if _, err := Codec.Unmarshal(bytes, &addresses); err != nil { + if _, err := atomic.Codec.Unmarshal(bytes, &addresses); err != nil { return nil, err } return addresses, nil @@ -69,7 +70,7 @@ func (u *user) putAddress(privKey *secp256k1.PrivateKey) error { return errKeyNil } - address := GetEthAddress(privKey) // address the privKey controls + address := privKey.EthAddress() // address the privKey controls controlsAddress, err := u.controlsAddress(address) if err != nil { return err @@ -93,7 +94,7 @@ func (u *user) putAddress(privKey *secp256k1.PrivateKey) error { } } addresses = append(addresses, address) - bytes, err := Codec.Marshal(codecVersion, addresses) + bytes, err := atomic.Codec.Marshal(atomic.CodecVersion, addresses) if err != nil { return err } diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 60b6ab240b..d3221e8f34 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -23,7 +23,6 @@ import ( "github.com/ava-labs/avalanchego/network/p2p/gossip" "github.com/ava-labs/avalanchego/upgrade" avalanchegoConstants "github.com/ava-labs/avalanchego/utils/constants" - "github.com/holiman/uint256" "github.com/prometheus/client_golang/prometheus" "github.com/ava-labs/coreth/consensus/dummy" @@ -41,6 +40,7 @@ import ( "github.com/ava-labs/coreth/node" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/peer" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/triedb" "github.com/ava-labs/coreth/triedb/hashdb" @@ -84,7 +84,6 @@ import ( "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/formatting/address" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/perms" "github.com/ava-labs/avalanchego/utils/profiler" "github.com/ava-labs/avalanchego/utils/set" @@ -108,27 +107,12 @@ var ( _ secp256k1fx.VM = &VM{} ) -const ( - x2cRateUint64 uint64 = 1_000_000_000 - x2cRateMinus1Uint64 uint64 = x2cRateUint64 - 1 -) - -var ( - // x2cRate is the conversion rate between the smallest denomination on the X-Chain - // 1 nAVAX and the smallest denomination on the C-Chain 1 wei. Where 1 nAVAX = 1 gWei. - // This is only required for AVAX because the denomination of 1 AVAX is 9 decimal - // places on the X and P chains, but is 18 decimal places within the EVM. - x2cRate = uint256.NewInt(x2cRateUint64) - x2cRateMinus1 = uint256.NewInt(x2cRateMinus1Uint64) -) - const ( // Max time from current time allowed for blocks, before they're considered future blocks // and fail verification maxFutureBlockTime = 10 * time.Second maxUTXOsToFetch = 1024 defaultMempoolSize = 4096 - codecVersion = uint16(0) secpCacheSize = 1024 decidedCacheSize = 10 * units.MiB @@ -184,30 +168,15 @@ var ( errEmptyBlock = errors.New("empty block") errUnsupportedFXs = errors.New("unsupported feature extensions") errInvalidBlock = errors.New("invalid block") - errInvalidAddr = errors.New("invalid hex address") errInsufficientAtomicTxFee = errors.New("atomic tx fee too low for atomic mempool") - errAssetIDMismatch = errors.New("asset IDs in the input don't match the utxo") - errNoImportInputs = errors.New("tx has no imported inputs") - errInputsNotSortedUnique = errors.New("inputs not sorted and unique") - errPublicKeySignatureMismatch = errors.New("signature doesn't match public key") - errWrongChainID = errors.New("tx has wrong chain ID") - errInsufficientFunds = errors.New("insufficient funds") - errNoExportOutputs = errors.New("tx has no export outputs") - errOutputsNotSorted = errors.New("tx outputs not sorted") - errOutputsNotSortedUnique = errors.New("outputs not sorted and unique") - errOverflowExport = errors.New("overflow when computing export amount + txFee") errInvalidNonce = errors.New("invalid nonce") - errConflictingAtomicInputs = errors.New("invalid block due to conflicting atomic inputs") errUnclesUnsupported = errors.New("uncles unsupported") errRejectedParent = errors.New("rejected parent") - errInsufficientFundsForFee = errors.New("insufficient AVAX funds to pay transaction fee") - errNoEVMOutputs = errors.New("tx has no EVM outputs") errNilBaseFeeApricotPhase3 = errors.New("nil base fee is invalid after apricotPhase3") errNilExtDataGasUsedApricotPhase4 = errors.New("nil extDataGasUsed is invalid after apricotPhase4") errNilBlockGasCostApricotPhase4 = errors.New("nil blockGasCost is invalid after apricotPhase4") errConflictingAtomicTx = errors.New("conflicting atomic tx present") errTooManyAtomicTx = errors.New("too many atomic tx") - errMissingAtomicTxs = errors.New("cannot build a block with non-empty extra data and zero atomic transactions") errInvalidHeaderPredicateResults = errors.New("invalid header predicate results") ) @@ -295,7 +264,6 @@ type VM struct { builder *blockBuilder baseCodec codec.Registry - codec codec.Manager clock mockable.Clock mempool *Mempool @@ -574,8 +542,6 @@ func (vm *VM) Initialize( return fmt.Errorf("failed to verify chain config: %w", err) } - vm.codec = Codec - // TODO: read size from settings vm.mempool, err = NewMempool(chainCtx, vm.sdkMetrics, defaultMempoolSize, vm.verifyTxAtTip) if err != nil { @@ -641,7 +607,7 @@ func (vm *VM) Initialize( } // initialize atomic repository - vm.atomicTxRepository, err = NewAtomicTxRepository(vm.db, vm.codec, lastAcceptedHeight) + vm.atomicTxRepository, err = NewAtomicTxRepository(vm.db, atomic.Codec, lastAcceptedHeight) if err != nil { return fmt.Errorf("failed to create atomic repository: %w", err) } @@ -846,7 +812,7 @@ func (vm *VM) preBatchOnFinalizeAndAssemble(header *types.Header, state *state.S continue } - atomicTxBytes, err := vm.codec.Marshal(codecVersion, tx) + atomicTxBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, tx) if err != nil { // Discard the transaction from the mempool and error if the transaction // cannot be marshalled. This should never happen. @@ -875,7 +841,7 @@ func (vm *VM) preBatchOnFinalizeAndAssemble(header *types.Header, state *state.S // assumes that we are in at least Apricot Phase 5. func (vm *VM) postBatchOnFinalizeAndAssemble(header *types.Header, state *state.StateDB, txs []*types.Transaction) ([]byte, *big.Int, *big.Int, error) { var ( - batchAtomicTxs []*Tx + batchAtomicTxs []*atomic.Tx batchAtomicUTXOs set.Set[ids.ID] batchContribution *big.Int = new(big.Int).Set(common.Big0) batchGasUsed *big.Int = new(big.Int).Set(common.Big0) @@ -950,7 +916,7 @@ func (vm *VM) postBatchOnFinalizeAndAssemble(header *types.Header, state *state. // If there is a non-zero number of transactions, marshal them and return the byte slice // for the block's extra data along with the contribution and gas used. if len(batchAtomicTxs) > 0 { - atomicTxBytes, err := vm.codec.Marshal(codecVersion, batchAtomicTxs) + atomicTxBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, batchAtomicTxs) if err != nil { // If we fail to marshal the batch of atomic transactions for any reason, // discard the entire set of current transactions. @@ -988,7 +954,7 @@ func (vm *VM) onExtraStateChange(block *types.Block, state *state.StateDB) (*big rules = vm.chainConfig.Rules(header.Number, header.Time) ) - txs, err := ExtractAtomicTxs(block.ExtData(), rules.IsApricotPhase5, vm.codec) + txs, err := atomic.ExtractAtomicTxs(block.ExtData(), rules.IsApricotPhase5, atomic.Codec) if err != nil { return nil, nil, err } @@ -1573,61 +1539,22 @@ func (vm *VM) CreateStaticHandlers(context.Context) (map[string]http.Handler, er ****************************************************************************** */ -// conflicts returns an error if [inputs] conflicts with any of the atomic inputs contained in [ancestor] -// or any of its ancestor blocks going back to the last accepted block in its ancestry. If [ancestor] is -// accepted, then nil will be returned immediately. -// If the ancestry of [ancestor] cannot be fetched, then [errRejectedParent] may be returned. -func (vm *VM) conflicts(inputs set.Set[ids.ID], ancestor *Block) error { - lastAcceptedBlock := vm.LastAcceptedBlock() - lastAcceptedHeight := lastAcceptedBlock.Height() - for ancestor.Height() > lastAcceptedHeight { - // If any of the atomic transactions in the ancestor conflict with [inputs] - // return an error. - for _, atomicTx := range ancestor.atomicTxs { - if inputs.Overlaps(atomicTx.InputUTXOs()) { - return errConflictingAtomicInputs - } - } - - // Move up the chain. - nextAncestorID := ancestor.Parent() - // If the ancestor is unknown, then the parent failed - // verification when it was called. - // If the ancestor is rejected, then this block shouldn't be - // inserted into the canonical chain because the parent is - // will be missing. - // If the ancestor is processing, then the block may have - // been verified. - nextAncestorIntf, err := vm.GetBlockInternal(context.TODO(), nextAncestorID) - if err != nil { - return errRejectedParent - } - nextAncestor, ok := nextAncestorIntf.(*Block) - if !ok { - return fmt.Errorf("ancestor block %s had unexpected type %T", nextAncestor.ID(), nextAncestorIntf) - } - ancestor = nextAncestor - } - - return nil -} - // getAtomicTx returns the requested transaction, status, and height. // If the status is Unknown, then the returned transaction will be nil. -func (vm *VM) getAtomicTx(txID ids.ID) (*Tx, Status, uint64, error) { +func (vm *VM) getAtomicTx(txID ids.ID) (*atomic.Tx, atomic.Status, uint64, error) { if tx, height, err := vm.atomicTxRepository.GetByTxID(txID); err == nil { - return tx, Accepted, height, nil + return tx, atomic.Accepted, height, nil } else if err != database.ErrNotFound { - return nil, Unknown, 0, err + return nil, atomic.Unknown, 0, err } tx, dropped, found := vm.mempool.GetTx(txID) switch { case found && dropped: - return tx, Dropped, 0, nil + return tx, atomic.Dropped, 0, nil case found: - return tx, Processing, 0, nil + return tx, atomic.Processing, 0, nil default: - return nil, Unknown, 0, nil + return nil, atomic.Unknown, 0, nil } } @@ -1658,7 +1585,7 @@ func (vm *VM) ParseAddress(addrStr string) (ids.ID, ids.ShortID, error) { } // verifyTxAtTip verifies that [tx] is valid to be issued on top of the currently preferred block -func (vm *VM) verifyTxAtTip(tx *Tx) error { +func (vm *VM) verifyTxAtTip(tx *atomic.Tx) error { if txByteLen := len(tx.SignedBytes()); txByteLen > targetAtomicTxsSize { return fmt.Errorf("tx size (%d) exceeds total atomic txs size target (%d)", txByteLen, targetAtomicTxsSize) } @@ -1699,7 +1626,7 @@ func (vm *VM) verifyTxAtTip(tx *Tx) error { // Note: verifyTx may modify [state]. If [state] needs to be properly maintained, the caller is responsible // for reverting to the correct snapshot after calling this function. If this function is called with a // throwaway state, then this is not necessary. -func (vm *VM) verifyTx(tx *Tx, parentHash common.Hash, baseFee *big.Int, state *state.StateDB, rules params.Rules) error { +func (vm *VM) verifyTx(tx *atomic.Tx, parentHash common.Hash, baseFee *big.Int, state *state.StateDB, rules params.Rules) error { parentIntf, err := vm.GetBlockInternal(context.TODO(), ids.ID(parentHash)) if err != nil { return fmt.Errorf("failed to get parent block: %w", err) @@ -1708,7 +1635,15 @@ func (vm *VM) verifyTx(tx *Tx, parentHash common.Hash, baseFee *big.Int, state * if !ok { return fmt.Errorf("parent block %s had unexpected type %T", parentIntf.ID(), parentIntf) } - if err := tx.UnsignedAtomicTx.SemanticVerify(vm, tx, parent, baseFee, rules); err != nil { + atomicBackend := &atomic.Backend{ + Ctx: vm.ctx, + Fx: &vm.fx, + Rules: rules, + Bootstrapped: vm.bootstrapped.Get(), + BlockFetcher: vm, + SecpCache: &vm.secpCache, + } + if err := tx.UnsignedAtomicTx.SemanticVerify(atomicBackend, tx, parent, baseFee); err != nil { return err } return tx.UnsignedAtomicTx.EVMStateTransfer(vm.ctx, state) @@ -1716,7 +1651,7 @@ func (vm *VM) verifyTx(tx *Tx, parentHash common.Hash, baseFee *big.Int, state * // verifyTxs verifies that [txs] are valid to be issued into a block with parent block [parentHash] // using [rules] as the current rule set. -func (vm *VM) verifyTxs(txs []*Tx, parentHash common.Hash, baseFee *big.Int, height uint64, rules params.Rules) error { +func (vm *VM) verifyTxs(txs []*atomic.Tx, parentHash common.Hash, baseFee *big.Int, height uint64, rules params.Rules) error { // Ensure that the parent was verified and inserted correctly. if !vm.blockChain.HasBlock(parentHash, height-1) { return errRejectedParent @@ -1739,14 +1674,22 @@ func (vm *VM) verifyTxs(txs []*Tx, parentHash common.Hash, baseFee *big.Int, hei // Ensure each tx in [txs] doesn't conflict with any other atomic tx in // a processing ancestor block. inputs := set.Set[ids.ID]{} + atomicBackend := &atomic.Backend{ + Ctx: vm.ctx, + Fx: &vm.fx, + Rules: rules, + Bootstrapped: vm.bootstrapped.Get(), + BlockFetcher: vm, + SecpCache: &vm.secpCache, + } for _, atomicTx := range txs { utx := atomicTx.UnsignedAtomicTx - if err := utx.SemanticVerify(vm, atomicTx, ancestor, baseFee, rules); err != nil { + if err := utx.SemanticVerify(atomicBackend, atomicTx, ancestor, baseFee); err != nil { return fmt.Errorf("invalid block due to failed semanatic verify: %w at height %d", err, height) } txInputs := utx.InputUTXOs() if inputs.Overlaps(txInputs) { - return errConflictingAtomicInputs + return atomic.ErrConflictingAtomicInputs } inputs.Union(txInputs) } @@ -1768,7 +1711,7 @@ func (vm *VM) GetAtomicUTXOs( return avax.GetAtomicUTXOs( vm.ctx.SharedMemory, - vm.codec, + atomic.Codec, chainID, addrs, startAddr, @@ -1777,176 +1720,6 @@ func (vm *VM) GetAtomicUTXOs( ) } -// GetSpendableFunds returns a list of EVMInputs and keys (in corresponding -// order) to total [amount] of [assetID] owned by [keys]. -// Note: we return [][]*secp256k1.PrivateKey even though each input -// corresponds to a single key, so that the signers can be passed in to -// [tx.Sign] which supports multiple keys on a single input. -func (vm *VM) GetSpendableFunds( - keys []*secp256k1.PrivateKey, - assetID ids.ID, - amount uint64, -) ([]EVMInput, [][]*secp256k1.PrivateKey, error) { - // Note: current state uses the state of the preferred block. - state, err := vm.blockChain.State() - if err != nil { - return nil, nil, err - } - inputs := []EVMInput{} - signers := [][]*secp256k1.PrivateKey{} - // Note: we assume that each key in [keys] is unique, so that iterating over - // the keys will not produce duplicated nonces in the returned EVMInput slice. - for _, key := range keys { - if amount == 0 { - break - } - addr := GetEthAddress(key) - var balance uint64 - if assetID == vm.ctx.AVAXAssetID { - // If the asset is AVAX, we divide by the x2cRate to convert back to the correct - // denomination of AVAX that can be exported. - balance = new(uint256.Int).Div(state.GetBalance(addr), x2cRate).Uint64() - } else { - balance = state.GetBalanceMultiCoin(addr, common.Hash(assetID)).Uint64() - } - if balance == 0 { - continue - } - if amount < balance { - balance = amount - } - nonce, err := vm.GetCurrentNonce(addr) - if err != nil { - return nil, nil, err - } - inputs = append(inputs, EVMInput{ - Address: addr, - Amount: balance, - AssetID: assetID, - Nonce: nonce, - }) - signers = append(signers, []*secp256k1.PrivateKey{key}) - amount -= balance - } - - if amount > 0 { - return nil, nil, errInsufficientFunds - } - - return inputs, signers, nil -} - -// GetSpendableAVAXWithFee returns a list of EVMInputs and keys (in corresponding -// order) to total [amount] + [fee] of [AVAX] owned by [keys]. -// This function accounts for the added cost of the additional inputs needed to -// create the transaction and makes sure to skip any keys with a balance that is -// insufficient to cover the additional fee. -// Note: we return [][]*secp256k1.PrivateKey even though each input -// corresponds to a single key, so that the signers can be passed in to -// [tx.Sign] which supports multiple keys on a single input. -func (vm *VM) GetSpendableAVAXWithFee( - keys []*secp256k1.PrivateKey, - amount uint64, - cost uint64, - baseFee *big.Int, -) ([]EVMInput, [][]*secp256k1.PrivateKey, error) { - // Note: current state uses the state of the preferred block. - state, err := vm.blockChain.State() - if err != nil { - return nil, nil, err - } - - initialFee, err := CalculateDynamicFee(cost, baseFee) - if err != nil { - return nil, nil, err - } - - newAmount, err := math.Add64(amount, initialFee) - if err != nil { - return nil, nil, err - } - amount = newAmount - - inputs := []EVMInput{} - signers := [][]*secp256k1.PrivateKey{} - // Note: we assume that each key in [keys] is unique, so that iterating over - // the keys will not produce duplicated nonces in the returned EVMInput slice. - for _, key := range keys { - if amount == 0 { - break - } - - prevFee, err := CalculateDynamicFee(cost, baseFee) - if err != nil { - return nil, nil, err - } - - newCost := cost + EVMInputGas - newFee, err := CalculateDynamicFee(newCost, baseFee) - if err != nil { - return nil, nil, err - } - - additionalFee := newFee - prevFee - - addr := GetEthAddress(key) - // Since the asset is AVAX, we divide by the x2cRate to convert back to - // the correct denomination of AVAX that can be exported. - balance := new(uint256.Int).Div(state.GetBalance(addr), x2cRate).Uint64() - // If the balance for [addr] is insufficient to cover the additional cost - // of adding an input to the transaction, skip adding the input altogether - if balance <= additionalFee { - continue - } - - // Update the cost for the next iteration - cost = newCost - - newAmount, err := math.Add64(amount, additionalFee) - if err != nil { - return nil, nil, err - } - amount = newAmount - - // Use the entire [balance] as an input, but if the required [amount] - // is less than the balance, update the [inputAmount] to spend the - // minimum amount to finish the transaction. - inputAmount := balance - if amount < balance { - inputAmount = amount - } - nonce, err := vm.GetCurrentNonce(addr) - if err != nil { - return nil, nil, err - } - inputs = append(inputs, EVMInput{ - Address: addr, - Amount: inputAmount, - AssetID: vm.ctx.AVAXAssetID, - Nonce: nonce, - }) - signers = append(signers, []*secp256k1.PrivateKey{key}) - amount -= inputAmount - } - - if amount > 0 { - return nil, nil, errInsufficientFunds - } - - return inputs, signers, nil -} - -// GetCurrentNonce returns the nonce associated with the address at the -// preferred block -func (vm *VM) GetCurrentNonce(address common.Address) (uint64, error) { - // Note: current state uses the state of the preferred block. - state, err := vm.blockChain.State() - if err != nil { - return 0, err - } - return state.GetNonce(address), nil -} - // currentRules returns the chain rules for the current block. func (vm *VM) currentRules() params.Rules { header := vm.eth.APIBackend.CurrentHeader() @@ -2080,3 +1853,55 @@ func (vm *VM) stateSyncEnabled(lastAcceptedHeight uint64) bool { // enable state sync by default if the chain is empty. return lastAcceptedHeight == 0 } + +func (vm *VM) newImportTx( + chainID ids.ID, // chain to import from + to common.Address, // Address of recipient + baseFee *big.Int, // fee to use post-AP3 + keys []*secp256k1.PrivateKey, // Keys to import the funds +) (*atomic.Tx, error) { + kc := secp256k1fx.NewKeychain() + for _, key := range keys { + kc.Add(key) + } + + atomicUTXOs, _, _, err := vm.GetAtomicUTXOs(chainID, kc.Addresses(), ids.ShortEmpty, ids.Empty, -1) + if err != nil { + return nil, fmt.Errorf("problem retrieving atomic UTXOs: %w", err) + } + + return atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), chainID, to, baseFee, kc, atomicUTXOs) +} + +// newExportTx returns a new ExportTx +func (vm *VM) newExportTx( + assetID ids.ID, // AssetID of the tokens to export + amount uint64, // Amount of tokens to export + chainID ids.ID, // Chain to send the UTXOs to + to ids.ShortID, // Address of chain recipient + baseFee *big.Int, // fee to use post-AP3 + keys []*secp256k1.PrivateKey, // Pay the fee and provide the tokens +) (*atomic.Tx, error) { + state, err := vm.blockChain.State() + if err != nil { + return nil, err + } + + // Create the transaction + tx, err := atomic.NewExportTx( + vm.ctx, // Context + vm.currentRules(), // VM rules + state, + assetID, // AssetID + amount, // Amount + chainID, // ID of the chain to send the funds to + to, // Address + baseFee, + keys, // Private keys + ) + if err != nil { + return nil, err + } + + return tx, nil +} diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 8fcb1961cd..a9a5bbd6e3 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -24,6 +24,7 @@ import ( "github.com/ava-labs/coreth/constants" "github.com/ava-labs/coreth/eth/filters" "github.com/ava-labs/coreth/metrics" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/trie" "github.com/ava-labs/coreth/utils" @@ -31,7 +32,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/api/keystore" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/database/prefixdb" @@ -154,8 +155,8 @@ func init() { b, _ = cb58.Decode(key) pk, _ := secp256k1.ToPrivateKey(b) testKeys = append(testKeys, pk) - testEthAddrs = append(testEthAddrs, GetEthAddress(pk)) - testShortIDAddrs = append(testShortIDAddrs, pk.PublicKey().Address()) + testEthAddrs = append(testEthAddrs, pk.EthAddress()) + testShortIDAddrs = append(testShortIDAddrs, pk.Address()) } } @@ -240,7 +241,7 @@ func setupGenesis( database.Database, []byte, chan commonEng.Message, - *atomic.Memory, + *avalancheatomic.Memory, ) { if len(genesisJSON) == 0 { genesisJSON = genesisJSONLatest @@ -251,7 +252,7 @@ func setupGenesis( baseDB := memdb.New() // initialize the atomic memory - atomicMemory := atomic.NewMemory(prefixdb.New([]byte{0}, baseDB)) + atomicMemory := avalancheatomic.NewMemory(prefixdb.New([]byte{0}, baseDB)) ctx.SharedMemory = atomicMemory.NewSharedMemory(ctx.ChainID) // NB: this lock is intentionally left locked when this function returns. @@ -282,7 +283,7 @@ func GenesisVM(t *testing.T, chan commonEng.Message, *VM, database.Database, - *atomic.Memory, + *avalancheatomic.Memory, *enginetest.Sender, ) { return GenesisVMWithClock(t, finishBootstrapping, genesisJSON, configJSON, upgradeJSON, mockable.Clock{}) @@ -301,7 +302,7 @@ func GenesisVMWithClock( chan commonEng.Message, *VM, database.Database, - *atomic.Memory, + *avalancheatomic.Memory, *enginetest.Sender, ) { vm := &VM{clock: clock} @@ -330,7 +331,7 @@ func GenesisVMWithClock( return issuer, vm, dbManager, m, appSender } -func addUTXO(sharedMemory *atomic.Memory, ctx *snow.Context, txID ids.ID, index uint32, assetID ids.ID, amount uint64, addr ids.ShortID) (*avax.UTXO, error) { +func addUTXO(sharedMemory *avalancheatomic.Memory, ctx *snow.Context, txID ids.ID, index uint32, assetID ids.ID, amount uint64, addr ids.ShortID) (*avax.UTXO, error) { utxo := &avax.UTXO{ UTXOID: avax.UTXOID{ TxID: txID, @@ -345,14 +346,14 @@ func addUTXO(sharedMemory *atomic.Memory, ctx *snow.Context, txID ids.ID, index }, }, } - utxoBytes, err := Codec.Marshal(codecVersion, utxo) + utxoBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, utxo) if err != nil { return nil, err } xChainSharedMemory := sharedMemory.NewSharedMemory(ctx.XChainID) inputID := utxo.InputID() - if err := xChainSharedMemory.Apply(map[ids.ID]*atomic.Requests{ctx.ChainID: {PutRequests: []*atomic.Element{{ + if err := xChainSharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{ctx.ChainID: {PutRequests: []*avalancheatomic.Element{{ Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ @@ -368,7 +369,7 @@ func addUTXO(sharedMemory *atomic.Memory, ctx *snow.Context, txID ids.ID, index // GenesisVMWithUTXOs creates a GenesisVM and generates UTXOs in the X-Chain Shared Memory containing AVAX based on the [utxos] map // Generates UTXOIDs by using a hash of the address in the [utxos] map such that the UTXOs will be generated deterministically. // If [genesisJSON] is empty, defaults to using [genesisJSONLatest] -func GenesisVMWithUTXOs(t *testing.T, finishBootstrapping bool, genesisJSON string, configJSON string, upgradeJSON string, utxos map[ids.ShortID]uint64) (chan commonEng.Message, *VM, database.Database, *atomic.Memory, *enginetest.Sender) { +func GenesisVMWithUTXOs(t *testing.T, finishBootstrapping bool, genesisJSON string, configJSON string, upgradeJSON string, utxos map[ids.ShortID]uint64) (chan commonEng.Message, *VM, database.Database, *avalancheatomic.Memory, *enginetest.Sender) { issuer, vm, db, sharedMemory, sender := GenesisVM(t, finishBootstrapping, genesisJSON, configJSON, upgradeJSON) for addr, avaxAmount := range utxos { txID, err := ids.ToID(hashing.ComputeHash256(addr.Bytes())) @@ -677,13 +678,13 @@ func TestIssueAtomicTxs(t *testing.T) { // Check that both atomic transactions were indexed as expected. indexedImportTx, status, height, err := vm.getAtomicTx(importTx.ID()) assert.NoError(t, err) - assert.Equal(t, Accepted, status) + assert.Equal(t, atomic.Accepted, status) assert.Equal(t, uint64(1), height, "expected height of indexed import tx to be 1") assert.Equal(t, indexedImportTx.ID(), importTx.ID(), "expected ID of indexed import tx to match original txID") indexedExportTx, status, height, err := vm.getAtomicTx(exportTx.ID()) assert.NoError(t, err) - assert.Equal(t, Accepted, status) + assert.Equal(t, atomic.Accepted, status) assert.Equal(t, uint64(2), height, "expected height of indexed export tx to be 2") assert.Equal(t, indexedExportTx.ID(), exportTx.ID(), "expected ID of indexed import tx to match original txID") } @@ -843,8 +844,8 @@ func testConflictingImportTxs(t *testing.T, genesis string) { } }() - importTxs := make([]*Tx, 0, 3) - conflictTxs := make([]*Tx, 0, 3) + importTxs := make([]*atomic.Tx, 0, 3) + conflictTxs := make([]*atomic.Tx, 0, 3) for i, key := range testKeys { importTx, err := vm.newImportTx(vm.ctx.XChainID, testEthAddrs[i], initialBaseFee, []*secp256k1.PrivateKey{key}) if err != nil { @@ -938,9 +939,9 @@ func testConflictingImportTxs(t *testing.T, genesis string) { var extraData []byte switch { case rules.IsApricotPhase5: - extraData, err = vm.codec.Marshal(codecVersion, []*Tx{conflictTxs[1]}) + extraData, err = atomic.Codec.Marshal(atomic.CodecVersion, []*atomic.Tx{conflictTxs[1]}) default: - extraData, err = vm.codec.Marshal(codecVersion, conflictTxs[1]) + extraData, err = atomic.Codec.Marshal(atomic.CodecVersion, conflictTxs[1]) } if err != nil { t.Fatal(err) @@ -966,15 +967,15 @@ func testConflictingImportTxs(t *testing.T, genesis string) { t.Fatal(err) } - if err := parsedBlock.Verify(context.Background()); !errors.Is(err, errConflictingAtomicInputs) { - t.Fatalf("Expected to fail with err: %s, but found err: %s", errConflictingAtomicInputs, err) + if err := parsedBlock.Verify(context.Background()); !errors.Is(err, atomic.ErrConflictingAtomicInputs) { + t.Fatalf("Expected to fail with err: %s, but found err: %s", atomic.ErrConflictingAtomicInputs, err) } if !rules.IsApricotPhase5 { return } - extraData, err = vm.codec.Marshal(codecVersion, []*Tx{importTxs[2], conflictTxs[2]}) + extraData, err = atomic.Codec.Marshal(atomic.CodecVersion, []*atomic.Tx{importTxs[2], conflictTxs[2]}) if err != nil { t.Fatal(err) } @@ -1002,25 +1003,25 @@ func testConflictingImportTxs(t *testing.T, genesis string) { t.Fatal(err) } - if err := parsedBlock.Verify(context.Background()); !errors.Is(err, errConflictingAtomicInputs) { - t.Fatalf("Expected to fail with err: %s, but found err: %s", errConflictingAtomicInputs, err) + if err := parsedBlock.Verify(context.Background()); !errors.Is(err, atomic.ErrConflictingAtomicInputs) { + t.Fatalf("Expected to fail with err: %s, but found err: %s", atomic.ErrConflictingAtomicInputs, err) } } func TestReissueAtomicTxHigherGasPrice(t *testing.T) { kc := secp256k1fx.NewKeychain(testKeys...) - for name, issueTxs := range map[string]func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) (issued []*Tx, discarded []*Tx){ - "single UTXO override": func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) (issued []*Tx, evicted []*Tx) { + for name, issueTxs := range map[string]func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) (issued []*atomic.Tx, discarded []*atomic.Tx){ + "single UTXO override": func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) (issued []*atomic.Tx, evicted []*atomic.Tx) { utxo, err := addUTXO(sharedMemory, vm.ctx, ids.GenerateTestID(), 0, vm.ctx.AVAXAssetID, units.Avax, testShortIDAddrs[0]) if err != nil { t.Fatal(err) } - tx1, err := vm.newImportTxWithUTXOs(vm.ctx.XChainID, testEthAddrs[0], initialBaseFee, kc, []*avax.UTXO{utxo}) + tx1, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, testEthAddrs[0], initialBaseFee, kc, []*avax.UTXO{utxo}) if err != nil { t.Fatal(err) } - tx2, err := vm.newImportTxWithUTXOs(vm.ctx.XChainID, testEthAddrs[0], new(big.Int).Mul(common.Big2, initialBaseFee), kc, []*avax.UTXO{utxo}) + tx2, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, testEthAddrs[0], new(big.Int).Mul(common.Big2, initialBaseFee), kc, []*avax.UTXO{utxo}) if err != nil { t.Fatal(err) } @@ -1032,9 +1033,9 @@ func TestReissueAtomicTxHigherGasPrice(t *testing.T) { t.Fatal(err) } - return []*Tx{tx2}, []*Tx{tx1} + return []*atomic.Tx{tx2}, []*atomic.Tx{tx1} }, - "one of two UTXOs overrides": func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) (issued []*Tx, evicted []*Tx) { + "one of two UTXOs overrides": func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) (issued []*atomic.Tx, evicted []*atomic.Tx) { utxo1, err := addUTXO(sharedMemory, vm.ctx, ids.GenerateTestID(), 0, vm.ctx.AVAXAssetID, units.Avax, testShortIDAddrs[0]) if err != nil { t.Fatal(err) @@ -1043,11 +1044,11 @@ func TestReissueAtomicTxHigherGasPrice(t *testing.T) { if err != nil { t.Fatal(err) } - tx1, err := vm.newImportTxWithUTXOs(vm.ctx.XChainID, testEthAddrs[0], initialBaseFee, kc, []*avax.UTXO{utxo1, utxo2}) + tx1, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, testEthAddrs[0], initialBaseFee, kc, []*avax.UTXO{utxo1, utxo2}) if err != nil { t.Fatal(err) } - tx2, err := vm.newImportTxWithUTXOs(vm.ctx.XChainID, testEthAddrs[0], new(big.Int).Mul(common.Big2, initialBaseFee), kc, []*avax.UTXO{utxo1}) + tx2, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, testEthAddrs[0], new(big.Int).Mul(common.Big2, initialBaseFee), kc, []*avax.UTXO{utxo1}) if err != nil { t.Fatal(err) } @@ -1059,9 +1060,9 @@ func TestReissueAtomicTxHigherGasPrice(t *testing.T) { t.Fatal(err) } - return []*Tx{tx2}, []*Tx{tx1} + return []*atomic.Tx{tx2}, []*atomic.Tx{tx1} }, - "hola": func(t *testing.T, vm *VM, sharedMemory *atomic.Memory) (issued []*Tx, evicted []*Tx) { + "hola": func(t *testing.T, vm *VM, sharedMemory *avalancheatomic.Memory) (issued []*atomic.Tx, evicted []*atomic.Tx) { utxo1, err := addUTXO(sharedMemory, vm.ctx, ids.GenerateTestID(), 0, vm.ctx.AVAXAssetID, units.Avax, testShortIDAddrs[0]) if err != nil { t.Fatal(err) @@ -1071,17 +1072,17 @@ func TestReissueAtomicTxHigherGasPrice(t *testing.T) { t.Fatal(err) } - importTx1, err := vm.newImportTxWithUTXOs(vm.ctx.XChainID, testEthAddrs[0], initialBaseFee, kc, []*avax.UTXO{utxo1}) + importTx1, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, testEthAddrs[0], initialBaseFee, kc, []*avax.UTXO{utxo1}) if err != nil { t.Fatal(err) } - importTx2, err := vm.newImportTxWithUTXOs(vm.ctx.XChainID, testEthAddrs[0], new(big.Int).Mul(big.NewInt(3), initialBaseFee), kc, []*avax.UTXO{utxo2}) + importTx2, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, testEthAddrs[0], new(big.Int).Mul(big.NewInt(3), initialBaseFee), kc, []*avax.UTXO{utxo2}) if err != nil { t.Fatal(err) } - reissuanceTx1, err := vm.newImportTxWithUTXOs(vm.ctx.XChainID, testEthAddrs[0], new(big.Int).Mul(big.NewInt(2), initialBaseFee), kc, []*avax.UTXO{utxo1, utxo2}) + reissuanceTx1, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, testEthAddrs[0], new(big.Int).Mul(big.NewInt(2), initialBaseFee), kc, []*avax.UTXO{utxo1, utxo2}) if err != nil { t.Fatal(err) } @@ -1101,7 +1102,7 @@ func TestReissueAtomicTxHigherGasPrice(t *testing.T) { assert.True(t, vm.mempool.Has(importTx2.ID())) assert.False(t, vm.mempool.Has(reissuanceTx1.ID())) - reissuanceTx2, err := vm.newImportTxWithUTXOs(vm.ctx.XChainID, testEthAddrs[0], new(big.Int).Mul(big.NewInt(4), initialBaseFee), kc, []*avax.UTXO{utxo1, utxo2}) + reissuanceTx2, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, testEthAddrs[0], new(big.Int).Mul(big.NewInt(4), initialBaseFee), kc, []*avax.UTXO{utxo1, utxo2}) if err != nil { t.Fatal(err) } @@ -1109,7 +1110,7 @@ func TestReissueAtomicTxHigherGasPrice(t *testing.T) { t.Fatal(err) } - return []*Tx{reissuanceTx2}, []*Tx{importTx1, importTx2} + return []*atomic.Tx{reissuanceTx2}, []*atomic.Tx{importTx1, importTx2} }, } { t.Run(name, func(t *testing.T) { @@ -1383,10 +1384,10 @@ func TestConflictingTransitiveAncestryWithGap(t *testing.T) { } key0 := testKeys[0] - addr0 := key0.PublicKey().Address() + addr0 := key0.Address() key1 := testKeys[1] - addr1 := key1.PublicKey().Address() + addr1 := key1.Address() importAmount := uint64(1000000000) @@ -1526,22 +1527,22 @@ func TestBonusBlocksTxs(t *testing.T) { Amt: importAmount, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{testKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{testKeys[0].Address()}, }, }, } - utxoBytes, err := vm.codec.Marshal(codecVersion, utxo) + utxoBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, utxo) if err != nil { t.Fatal(err) } xChainSharedMemory := sharedMemory.NewSharedMemory(vm.ctx.XChainID) inputID := utxo.InputID() - if err := xChainSharedMemory.Apply(map[ids.ID]*atomic.Requests{vm.ctx.ChainID: {PutRequests: []*atomic.Element{{ + if err := xChainSharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{vm.ctx.ChainID: {PutRequests: []*avalancheatomic.Element{{ Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ - testKeys[0].PublicKey().Address().Bytes(), + testKeys[0].Address().Bytes(), }, }}}}); err != nil { t.Fatal(err) @@ -1567,7 +1568,7 @@ func TestBonusBlocksTxs(t *testing.T) { vm.atomicBackend.(*atomicBackend).bonusBlocks = map[uint64]ids.ID{blk.Height(): blk.ID()} // Remove the UTXOs from shared memory, so that non-bonus blocks will fail verification - if err := vm.ctx.SharedMemory.Apply(map[ids.ID]*atomic.Requests{vm.ctx.XChainID: {RemoveRequests: [][]byte{inputID[:]}}}); err != nil { + if err := vm.ctx.SharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{vm.ctx.XChainID: {RemoveRequests: [][]byte{inputID[:]}}}); err != nil { t.Fatal(err) } @@ -3064,13 +3065,13 @@ func TestBuildInvalidBlockHead(t *testing.T) { }() key0 := testKeys[0] - addr0 := key0.PublicKey().Address() + addr0 := key0.Address() // Create the transaction - utx := &UnsignedImportTx{ + utx := &atomic.UnsignedImportTx{ NetworkID: vm.ctx.NetworkID, BlockchainID: vm.ctx.ChainID, - Outs: []EVMOutput{{ + Outs: []atomic.EVMOutput{{ Address: common.Address(addr0), Amount: 1 * units.Avax, AssetID: vm.ctx.AVAXAssetID, @@ -3088,8 +3089,8 @@ func TestBuildInvalidBlockHead(t *testing.T) { }, SourceChain: vm.ctx.XChainID, } - tx := &Tx{UnsignedAtomicTx: utx} - if err := tx.Sign(vm.codec, [][]*secp256k1.PrivateKey{{key0}}); err != nil { + tx := &atomic.Tx{UnsignedAtomicTx: utx} + if err := tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{key0}}); err != nil { t.Fatal(err) } @@ -3221,22 +3222,22 @@ func TestBuildApricotPhase4Block(t *testing.T) { Amt: importAmount, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{testKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{testKeys[0].Address()}, }, }, } - utxoBytes, err := vm.codec.Marshal(codecVersion, utxo) + utxoBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, utxo) if err != nil { t.Fatal(err) } xChainSharedMemory := sharedMemory.NewSharedMemory(vm.ctx.XChainID) inputID := utxo.InputID() - if err := xChainSharedMemory.Apply(map[ids.ID]*atomic.Requests{vm.ctx.ChainID: {PutRequests: []*atomic.Element{{ + if err := xChainSharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{vm.ctx.ChainID: {PutRequests: []*avalancheatomic.Element{{ Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ - testKeys[0].PublicKey().Address().Bytes(), + testKeys[0].Address().Bytes(), }, }}}}); err != nil { t.Fatal(err) @@ -3391,22 +3392,22 @@ func TestBuildApricotPhase5Block(t *testing.T) { Amt: importAmount, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{testKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{testKeys[0].Address()}, }, }, } - utxoBytes, err := vm.codec.Marshal(codecVersion, utxo) + utxoBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, utxo) if err != nil { t.Fatal(err) } xChainSharedMemory := sharedMemory.NewSharedMemory(vm.ctx.XChainID) inputID := utxo.InputID() - if err := xChainSharedMemory.Apply(map[ids.ID]*atomic.Requests{vm.ctx.ChainID: {PutRequests: []*atomic.Element{{ + if err := xChainSharedMemory.Apply(map[ids.ID]*avalancheatomic.Requests{vm.ctx.ChainID: {PutRequests: []*avalancheatomic.Element{{ Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ - testKeys[0].PublicKey().Address().Bytes(), + testKeys[0].Address().Bytes(), }, }}}}); err != nil { t.Fatal(err) @@ -3672,7 +3673,7 @@ func TestBuildBlockDoesNotExceedAtomicGasLimit(t *testing.T) { utxo, err := addUTXO(sharedMemory, vm.ctx, txID, uint32(i), vm.ctx.AVAXAssetID, importAmount, testShortIDAddrs[0]) assert.NoError(t, err) - importTx, err := vm.newImportTxWithUTXOs(vm.ctx.XChainID, testEthAddrs[0], initialBaseFee, kc, []*avax.UTXO{utxo}) + importTx, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, testEthAddrs[0], initialBaseFee, kc, []*avax.UTXO{utxo}) if err != nil { t.Fatal(err) } @@ -3750,7 +3751,7 @@ func TestExtraStateChangeAtomicGasLimitExceeded(t *testing.T) { validEthBlock := blk1.(*chain.BlockWrapper).Block.(*Block).ethBlock - extraData, err := vm2.codec.Marshal(codecVersion, []*Tx{importTx}) + extraData, err := atomic.Codec.Marshal(atomic.CodecVersion, []*atomic.Tx{importTx}) if err != nil { t.Fatal(err) } diff --git a/scripts/versions.sh b/scripts/versions.sh index 33282d011a..2018ff1398 100644 --- a/scripts/versions.sh +++ b/scripts/versions.sh @@ -6,4 +6,4 @@ set -euo pipefail # Don't export them as they're used in the context of other calls -AVALANCHE_VERSION=${AVALANCHE_VERSION:-'1dc4192013aa'} +AVALANCHE_VERSION=${AVALANCHE_VERSION:-'fade5be3051d'} From c167754baf778738598b19abbc28eb8c18107ab2 Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Tue, 31 Dec 2024 11:39:12 +0300 Subject: [PATCH 14/69] move atomic gossip (#706) * new atomic pkg * bump avago * bump versions * move attomic gossip * lint * change newimport clk to time * move utils * bump avago * go mod tidy * update releases md * use address methods from avago * bump avago * bump e2e avago version * Update plugin/evm/atomic/gossip_test.go Co-authored-by: Quentin McGaw Signed-off-by: Ceyhun Onur * Update plugin/evm/atomic/mempool.go Co-authored-by: Quentin McGaw Signed-off-by: Ceyhun Onur * Update plugin/evm/config/config.go Co-authored-by: Quentin McGaw Signed-off-by: Ceyhun Onur * Update plugin/evm/atomic/tx_heap.go Co-authored-by: Quentin McGaw Signed-off-by: Ceyhun Onur * Update plugin/evm/config/config.go Co-authored-by: Quentin McGaw Signed-off-by: Ceyhun Onur * fix reviews --------- Signed-off-by: Ceyhun Onur Signed-off-by: Ceyhun Onur Co-authored-by: Quentin McGaw --- RELEASES.md | 1 + peer/network.go | 21 +-- peer/network_test.go | 59 +++---- plugin/evm/admin.go | 6 +- plugin/evm/atomic/gossip.go | 35 ++++ plugin/evm/atomic/gossip_test.go | 117 +++++++++++++ plugin/evm/{ => atomic}/mempool.go | 121 +++++++------- plugin/evm/{ => atomic}/mempool_test.go | 7 +- plugin/evm/{ => atomic}/test_tx.go | 85 ++++++---- plugin/evm/atomic/tx_heap.go | 163 +++++++++++++++++++ plugin/evm/atomic/tx_heap_test.go | 142 ++++++++++++++++ plugin/evm/atomic_syncer_test.go | 5 +- plugin/evm/atomic_trie_iterator_test.go | 15 +- plugin/evm/atomic_trie_test.go | 36 ++-- plugin/evm/atomic_tx_repository_test.go | 14 +- plugin/evm/block.go | 3 +- plugin/evm/block_builder.go | 3 +- plugin/evm/client/client.go | 17 +- plugin/evm/{ => config}/config.go | 19 ++- plugin/evm/{ => config}/config_test.go | 2 +- plugin/evm/config/constants.go | 8 + plugin/evm/export_tx_test.go | 2 +- plugin/evm/gossip.go | 47 ++---- plugin/evm/gossip_stats.go | 67 -------- plugin/evm/gossip_test.go | 109 ------------- plugin/evm/gossiper_atomic_gossiping_test.go | 54 ++++-- plugin/evm/handler.go | 140 ---------------- plugin/evm/mempool_atomic_gossiping_test.go | 45 +++-- plugin/evm/message/codec.go | 10 +- plugin/evm/message/handler.go | 25 +-- plugin/evm/message/handler_test.go | 62 ------- plugin/evm/message/message.go | 78 --------- plugin/evm/message/message_test.go | 78 --------- plugin/evm/service.go | 6 +- plugin/evm/tx_gossip_test.go | 27 ++- plugin/evm/vm.go | 55 +++---- plugin/evm/vm_test.go | 19 ++- 37 files changed, 800 insertions(+), 903 deletions(-) create mode 100644 plugin/evm/atomic/gossip.go create mode 100644 plugin/evm/atomic/gossip_test.go rename plugin/evm/{ => atomic}/mempool.go (86%) rename plugin/evm/{ => atomic}/mempool_test.go (92%) rename plugin/evm/{ => atomic}/test_tx.go (74%) create mode 100644 plugin/evm/atomic/tx_heap.go create mode 100644 plugin/evm/atomic/tx_heap_test.go rename plugin/evm/{ => config}/config.go (95%) rename plugin/evm/{ => config}/config_test.go (99%) create mode 100644 plugin/evm/config/constants.go delete mode 100644 plugin/evm/gossip_stats.go delete mode 100644 plugin/evm/handler.go delete mode 100644 plugin/evm/message/handler_test.go delete mode 100644 plugin/evm/message/message.go delete mode 100644 plugin/evm/message/message_test.go diff --git a/RELEASES.md b/RELEASES.md index b977d63812..7f8393b5de 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -2,6 +2,7 @@ ## [v0.14.1](https://github.com/ava-labs/coreth/releases/tag/v0.14.1) - Remove API eth_getAssetBalance that was used to query ANT balances (deprecated since v0.10.0) +- Remove legacy gossip handler and metrics (deprecated since v0.10.0) ## [v0.14.0](https://github.com/ava-labs/coreth/releases/tag/v0.14.0) - Minor version update to correspond to avalanchego v1.12.0 / Etna. diff --git a/peer/network.go b/peer/network.go index 7739e279bc..a4dfd015f6 100644 --- a/peer/network.go +++ b/peer/network.go @@ -56,9 +56,6 @@ type Network interface { // by calling OnPeerConnected for each peer Shutdown() - // SetGossipHandler sets the provided gossip handler as the gossip handler - SetGossipHandler(handler message.GossipHandler) - // SetRequestHandler sets the provided request handler as the request handler SetRequestHandler(handler message.RequestHandler) @@ -87,7 +84,6 @@ type network struct { appSender common.AppSender // avalanchego AppSender for sending messages codec codec.Manager // Codec used for parsing messages appRequestHandler message.RequestHandler // maps request type => handler - gossipHandler message.GossipHandler // maps gossip type => handler peers *peerTracker // tracking of peers & bandwidth appStats stats.RequestHandlerStats // Provide request handler metrics @@ -110,7 +106,6 @@ func NewNetwork(p2pNetwork *p2p.Network, appSender common.AppSender, codec codec outstandingRequestHandlers: make(map[uint32]message.ResponseHandler), activeAppRequests: semaphore.NewWeighted(maxActiveAppRequests), p2pNetwork: p2pNetwork, - gossipHandler: message.NoopMempoolGossipHandler{}, appRequestHandler: message.NoopRequestHandler{}, peers: NewPeerTracker(), appStats: stats.NewRequestHandlerStats(), @@ -345,14 +340,7 @@ func (n *network) markRequestFulfilled(requestID uint32) (message.ResponseHandle // from a peer. An error returned by this function is treated as fatal by the // engine. func (n *network) AppGossip(ctx context.Context, nodeID ids.NodeID, gossipBytes []byte) error { - var gossipMsg message.GossipMessage - if _, err := n.codec.Unmarshal(gossipBytes, &gossipMsg); err != nil { - log.Debug("forwarding AppGossip to SDK network", "nodeID", nodeID, "gossipLen", len(gossipBytes), "err", err) - return n.p2pNetwork.AppGossip(ctx, nodeID, gossipBytes) - } - - log.Debug("processing AppGossip from node", "nodeID", nodeID, "msg", gossipMsg) - return gossipMsg.Handle(n.gossipHandler, nodeID) + return n.p2pNetwork.AppGossip(ctx, nodeID, gossipBytes) } // Connected adds the given nodeID to the peer list so that it can receive messages @@ -407,13 +395,6 @@ func (n *network) Shutdown() { n.closed.Set(true) // mark network as closed } -func (n *network) SetGossipHandler(handler message.GossipHandler) { - n.lock.Lock() - defer n.lock.Unlock() - - n.gossipHandler = handler -} - func (n *network) SetRequestHandler(handler message.RequestHandler) { n.lock.Lock() defer n.lock.Unlock() diff --git a/peer/network_test.go b/peer/network_test.go index c792cf9064..6f357be874 100644 --- a/peer/network_test.go +++ b/peer/network_test.go @@ -30,6 +30,10 @@ import ( "github.com/ava-labs/avalanchego/version" ) +const ( + codecVersion uint16 = 0 +) + var ( defaultPeerVersion = &version.Application{ Major: 1, @@ -46,9 +50,7 @@ var ( _ message.RequestHandler = &HelloGreetingRequestHandler{} _ message.RequestHandler = &testRequestHandler{} - _ common.AppSender = testAppSender{} - _ message.GossipMessage = HelloGossip{} - _ message.GossipHandler = &testGossipHandler{} + _ common.AppSender = testAppSender{} _ p2p.Handler = &testSDKHandler{} ) @@ -393,7 +395,7 @@ func TestRequestMinVersion(t *testing.T) { go func() { time.Sleep(200 * time.Millisecond) atomic.AddUint32(&callNum, 1) - responseBytes, err := codecManager.Marshal(message.Version, TestMessage{Message: "this is a response"}) + responseBytes, err := codecManager.Marshal(codecVersion, TestMessage{Message: "this is a response"}) if err != nil { panic(err) } @@ -503,7 +505,6 @@ func TestHandleInvalidMessages(t *testing.T) { p2pNetwork, err := p2p.NewNetwork(logging.NoLog{}, sender, prometheus.NewRegistry(), "") require.NoError(t, err) clientNetwork := NewNetwork(p2pNetwork, sender, codecManager, ids.EmptyNodeID, 1) - clientNetwork.SetGossipHandler(message.NoopMempoolGossipHandler{}) clientNetwork.SetRequestHandler(&testRequestHandler{}) assert.NoError(t, clientNetwork.Connected(context.Background(), nodeID, defaultPeerVersion)) @@ -511,7 +512,8 @@ func TestHandleInvalidMessages(t *testing.T) { defer clientNetwork.Shutdown() // Ensure a valid gossip message sent as any App specific message type does not trigger a fatal error - gossipMsg, err := buildGossip(codecManager, HelloGossip{Msg: "hello there!"}) + marshaller := helloGossipMarshaller{codec: codecManager} + gossipMsg, err := marshaller.MarshalGossip(&HelloGossip{Msg: "hello there!"}) assert.NoError(t, err) // Ensure a valid request message sent as any App specific message type does not trigger a fatal error @@ -552,7 +554,6 @@ func TestNetworkPropagatesRequestHandlerError(t *testing.T) { p2pNetwork, err := p2p.NewNetwork(logging.NoLog{}, nil, prometheus.NewRegistry(), "") require.NoError(t, err) clientNetwork := NewNetwork(p2pNetwork, sender, codecManager, ids.EmptyNodeID, 1) - clientNetwork.SetGossipHandler(message.NoopMempoolGossipHandler{}) clientNetwork.SetRequestHandler(&testRequestHandler{err: errors.New("fail")}) // Return an error from the request handler assert.NoError(t, clientNetwork.Connected(context.Background(), nodeID, defaultPeerVersion)) @@ -615,18 +616,14 @@ func buildCodec(t *testing.T, types ...interface{}) codec.Manager { for _, typ := range types { assert.NoError(t, c.RegisterType(typ)) } - assert.NoError(t, codecManager.RegisterCodec(message.Version, c)) + assert.NoError(t, codecManager.RegisterCodec(codecVersion, c)) return codecManager } // marshalStruct is a helper method used to marshal an object as `interface{}` // so that the codec is able to include the TypeID in the resulting bytes func marshalStruct(codec codec.Manager, obj interface{}) ([]byte, error) { - return codec.Marshal(message.Version, &obj) -} - -func buildGossip(codec codec.Manager, msg message.GossipMessage) ([]byte, error) { - return codec.Marshal(message.Version, &msg) + return codec.Marshal(codecVersion, &obj) } type testAppSender struct { @@ -696,11 +693,11 @@ type HelloGreetingRequestHandler struct { } func (h *HelloGreetingRequestHandler) HandleHelloRequest(ctx context.Context, nodeID ids.NodeID, requestID uint32, request *HelloRequest) ([]byte, error) { - return h.codec.Marshal(message.Version, HelloResponse{Response: "Hi"}) + return h.codec.Marshal(codecVersion, HelloResponse{Response: "Hi"}) } func (h *HelloGreetingRequestHandler) HandleGreetingRequest(ctx context.Context, nodeID ids.NodeID, requestID uint32, request *GreetingRequest) ([]byte, error) { - return h.codec.Marshal(message.Version, GreetingResponse{Greet: "Hey there"}) + return h.codec.Marshal(codecVersion, GreetingResponse{Greet: "Hey there"}) } type TestMessage struct { @@ -719,34 +716,22 @@ type HelloGossip struct { Msg string `serialize:"true"` } -func (h HelloGossip) Handle(handler message.GossipHandler, nodeID ids.NodeID) error { - return handler.HandleEthTxs(nodeID, message.EthTxsGossip{}) +func (tx *HelloGossip) GossipID() ids.ID { + return ids.FromStringOrPanic(tx.Msg) } -func (h HelloGossip) String() string { - return fmt.Sprintf("HelloGossip(%s)", h.Msg) -} - -func (h HelloGossip) Bytes() []byte { - // no op - return nil -} - -type testGossipHandler struct { - received bool - nodeID ids.NodeID +type helloGossipMarshaller struct { + codec codec.Manager } -func (t *testGossipHandler) HandleAtomicTx(nodeID ids.NodeID, msg message.AtomicTxGossip) error { - t.received = true - t.nodeID = nodeID - return nil +func (g helloGossipMarshaller) MarshalGossip(tx *HelloGossip) ([]byte, error) { + return g.codec.Marshal(0, tx) } -func (t *testGossipHandler) HandleEthTxs(nodeID ids.NodeID, msg message.EthTxsGossip) error { - t.received = true - t.nodeID = nodeID - return nil +func (g helloGossipMarshaller) UnmarshalGossip(bytes []byte) (*HelloGossip, error) { + h := &HelloGossip{} + _, err := g.codec.Unmarshal(bytes, h) + return h, err } type testRequestHandler struct { diff --git a/plugin/evm/admin.go b/plugin/evm/admin.go index e90be473a7..34595a0b0e 100644 --- a/plugin/evm/admin.go +++ b/plugin/evm/admin.go @@ -78,11 +78,7 @@ func (p *Admin) SetLogLevel(_ *http.Request, args *client.SetLogLevelArgs, reply return nil } -type ConfigReply struct { - Config *Config `json:"config"` -} - -func (p *Admin) GetVMConfig(_ *http.Request, _ *struct{}, reply *ConfigReply) error { +func (p *Admin) GetVMConfig(_ *http.Request, _ *struct{}, reply *client.ConfigReply) error { reply.Config = &p.vm.config return nil } diff --git a/plugin/evm/atomic/gossip.go b/plugin/evm/atomic/gossip.go new file mode 100644 index 0000000000..2c6cb35da2 --- /dev/null +++ b/plugin/evm/atomic/gossip.go @@ -0,0 +1,35 @@ +// (c) 2019-2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package atomic + +import ( + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/network/p2p/gossip" +) + +var ( + _ gossip.Gossipable = (*GossipAtomicTx)(nil) + _ gossip.Marshaller[*GossipAtomicTx] = (*GossipAtomicTxMarshaller)(nil) +) + +type GossipAtomicTxMarshaller struct{} + +func (g GossipAtomicTxMarshaller) MarshalGossip(tx *GossipAtomicTx) ([]byte, error) { + return tx.Tx.SignedBytes(), nil +} + +func (g GossipAtomicTxMarshaller) UnmarshalGossip(bytes []byte) (*GossipAtomicTx, error) { + tx, err := ExtractAtomicTx(bytes, Codec) + return &GossipAtomicTx{ + Tx: tx, + }, err +} + +type GossipAtomicTx struct { + Tx *Tx +} + +func (tx *GossipAtomicTx) GossipID() ids.ID { + return tx.Tx.ID() +} diff --git a/plugin/evm/atomic/gossip_test.go b/plugin/evm/atomic/gossip_test.go new file mode 100644 index 0000000000..5140f6bc7e --- /dev/null +++ b/plugin/evm/atomic/gossip_test.go @@ -0,0 +1,117 @@ +// (c) 2019-2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package atomic + +import ( + "testing" + + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow" + "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" + "github.com/ava-labs/avalanchego/vms/components/verify" + "github.com/prometheus/client_golang/prometheus" + "github.com/stretchr/testify/require" +) + +func TestGossipAtomicTxMarshaller(t *testing.T) { + require := require.New(t) + + want := &GossipAtomicTx{ + Tx: &Tx{ + UnsignedAtomicTx: &UnsignedImportTx{}, + Creds: []verify.Verifiable{}, + }, + } + marshaller := GossipAtomicTxMarshaller{} + + key0, err := secp256k1.NewPrivateKey() + require.NoError(err) + err = want.Tx.Sign(Codec, [][]*secp256k1.PrivateKey{{key0}}) + require.NoError(err) + + bytes, err := marshaller.MarshalGossip(want) + require.NoError(err) + + got, err := marshaller.UnmarshalGossip(bytes) + require.NoError(err) + require.Equal(want.GossipID(), got.GossipID()) +} + +func TestAtomicMempoolIterate(t *testing.T) { + txs := []*GossipAtomicTx{ + { + Tx: &Tx{ + UnsignedAtomicTx: &TestUnsignedTx{ + IDV: ids.GenerateTestID(), + }, + }, + }, + { + Tx: &Tx{ + UnsignedAtomicTx: &TestUnsignedTx{ + IDV: ids.GenerateTestID(), + }, + }, + }, + } + + tests := []struct { + name string + add []*GossipAtomicTx + f func(tx *GossipAtomicTx) bool + expectedTxs []*GossipAtomicTx + }{ + { + name: "func matches nothing", + add: txs, + f: func(*GossipAtomicTx) bool { + return false + }, + expectedTxs: []*GossipAtomicTx{}, + }, + { + name: "func matches all", + add: txs, + f: func(*GossipAtomicTx) bool { + return true + }, + expectedTxs: txs, + }, + { + name: "func matches subset", + add: txs, + f: func(tx *GossipAtomicTx) bool { + return tx.Tx == txs[0].Tx + }, + expectedTxs: []*GossipAtomicTx{txs[0]}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require := require.New(t) + m, err := NewMempool(&snow.Context{}, prometheus.NewRegistry(), 10, nil) + require.NoError(err) + + for _, add := range tt.add { + require.NoError(m.Add(add)) + } + + matches := make([]*GossipAtomicTx, 0) + f := func(tx *GossipAtomicTx) bool { + match := tt.f(tx) + + if match { + matches = append(matches, tx) + } + + return match + } + + m.Iterate(f) + + require.ElementsMatch(tt.expectedTxs, matches) + }) + } +} diff --git a/plugin/evm/mempool.go b/plugin/evm/atomic/mempool.go similarity index 86% rename from plugin/evm/mempool.go rename to plugin/evm/atomic/mempool.go index acb8db4e3f..f74eacda7e 100644 --- a/plugin/evm/mempool.go +++ b/plugin/evm/atomic/mempool.go @@ -1,7 +1,7 @@ // (c) 2019-2020, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package atomic import ( "errors" @@ -15,7 +15,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/ava-labs/coreth/metrics" - "github.com/ava-labs/coreth/plugin/evm/atomic" + "github.com/ava-labs/coreth/plugin/evm/config" "github.com/ethereum/go-ethereum/log" ) @@ -24,8 +24,11 @@ const ( ) var ( - errTxAlreadyKnown = errors.New("tx already known") - errNoGasUsed = errors.New("no gas used") + errTxAlreadyKnown = errors.New("tx already known") + errNoGasUsed = errors.New("no gas used") + ErrConflictingAtomicTx = errors.New("conflicting atomic tx present") + ErrInsufficientAtomicTxFee = errors.New("atomic tx fee too low for atomic mempool") + ErrTooManyAtomicTx = errors.New("too many atomic tx") _ gossip.Set[*GossipAtomicTx] = (*Mempool)(nil) ) @@ -59,12 +62,12 @@ type Mempool struct { // maxSize is the maximum number of transactions allowed to be kept in mempool maxSize int // currentTxs is the set of transactions about to be added to a block. - currentTxs map[ids.ID]*atomic.Tx + currentTxs map[ids.ID]*Tx // issuedTxs is the set of transactions that have been issued into a new block - issuedTxs map[ids.ID]*atomic.Tx + issuedTxs map[ids.ID]*Tx // discardedTxs is an LRU Cache of transactions that have been discarded after failing // verification. - discardedTxs *cache.LRU[ids.ID, *atomic.Tx] + discardedTxs *cache.LRU[ids.ID, *Tx] // Pending is a channel of length one, which the mempool ensures has an item on // it as long as there is an unissued transaction remaining in [txs] Pending chan struct{} @@ -72,31 +75,35 @@ type Mempool struct { // NOTE: [txHeap] ONLY contains pending txs txHeap *txHeap // utxoSpenders maps utxoIDs to the transaction consuming them in the mempool - utxoSpenders map[ids.ID]*atomic.Tx + utxoSpenders map[ids.ID]*Tx // bloom is a bloom filter containing the txs in the mempool bloom *gossip.BloomFilter metrics *mempoolMetrics - verify func(tx *atomic.Tx) error + verify func(tx *Tx) error } // NewMempool returns a Mempool with [maxSize] -func NewMempool(ctx *snow.Context, registerer prometheus.Registerer, maxSize int, verify func(tx *atomic.Tx) error) (*Mempool, error) { - bloom, err := gossip.NewBloomFilter(registerer, "atomic_mempool_bloom_filter", txGossipBloomMinTargetElements, txGossipBloomTargetFalsePositiveRate, txGossipBloomResetFalsePositiveRate) +func NewMempool(ctx *snow.Context, registerer prometheus.Registerer, maxSize int, verify func(tx *Tx) error) (*Mempool, error) { + bloom, err := gossip.NewBloomFilter(registerer, "atomic_mempool_bloom_filter", + config.TxGossipBloomMinTargetElements, + config.TxGossipBloomTargetFalsePositiveRate, + config.TxGossipBloomResetFalsePositiveRate, + ) if err != nil { return nil, fmt.Errorf("failed to initialize bloom filter: %w", err) } return &Mempool{ ctx: ctx, - issuedTxs: make(map[ids.ID]*atomic.Tx), - discardedTxs: &cache.LRU[ids.ID, *atomic.Tx]{Size: discardedTxsCacheSize}, - currentTxs: make(map[ids.ID]*atomic.Tx), + issuedTxs: make(map[ids.ID]*Tx), + discardedTxs: &cache.LRU[ids.ID, *Tx]{Size: discardedTxsCacheSize}, + currentTxs: make(map[ids.ID]*Tx), Pending: make(chan struct{}, 1), txHeap: newTxHeap(maxSize), maxSize: maxSize, - utxoSpenders: make(map[ids.ID]*atomic.Tx), + utxoSpenders: make(map[ids.ID]*Tx), bloom: bloom, metrics: newMempoolMetrics(), verify: verify, @@ -118,7 +125,7 @@ func (m *Mempool) length() int { // atomicTxGasPrice is the [gasPrice] paid by a transaction to burn a given // amount of [AVAXAssetID] given the value of [gasUsed]. -func (m *Mempool) atomicTxGasPrice(tx *atomic.Tx) (uint64, error) { +func (m *Mempool) atomicTxGasPrice(tx *Tx) (uint64, error) { gasUsed, err := tx.GasUsed(true) if err != nil { return 0, err @@ -137,35 +144,19 @@ func (m *Mempool) Add(tx *GossipAtomicTx) error { m.ctx.Lock.RLock() defer m.ctx.Lock.RUnlock() - m.lock.Lock() - defer m.lock.Unlock() - - err := m.addTx(tx.Tx, false) - if errors.Is(err, errTxAlreadyKnown) { - return err - } - - if err != nil { - txID := tx.Tx.ID() - m.discardedTxs.Put(txID, tx.Tx) - log.Debug("failed to issue remote tx to mempool", - "txID", txID, - "err", err, - ) - } - - return err + return m.AddRemoteTx(tx.Tx) } -// AddTx attempts to add [tx] to the mempool and returns an error if +// AddRemoteTx attempts to add [tx] to the mempool and returns an error if // it could not be added to the mempool. -func (m *Mempool) AddTx(tx *atomic.Tx) error { +func (m *Mempool) AddRemoteTx(tx *Tx) error { m.lock.Lock() defer m.lock.Unlock() - err := m.addTx(tx, false) + err := m.addTx(tx, false, false) + // Do not attempt to discard the tx if it was already known if errors.Is(err, errTxAlreadyKnown) { - return nil + return err } if err != nil { @@ -181,11 +172,11 @@ func (m *Mempool) AddTx(tx *atomic.Tx) error { return err } -func (m *Mempool) AddLocalTx(tx *atomic.Tx) error { +func (m *Mempool) AddLocalTx(tx *Tx) error { m.lock.Lock() defer m.lock.Unlock() - err := m.addTx(tx, false) + err := m.addTx(tx, true, false) if errors.Is(err, errTxAlreadyKnown) { return nil } @@ -193,29 +184,24 @@ func (m *Mempool) AddLocalTx(tx *atomic.Tx) error { return err } -// forceAddTx forcibly adds a *atomic.Tx to the mempool and bypasses all verification. -func (m *Mempool) ForceAddTx(tx *atomic.Tx) error { +// ForceAddTx forcibly adds a *Tx to the mempool and bypasses all verification. +func (m *Mempool) ForceAddTx(tx *Tx) error { m.lock.Lock() defer m.lock.Unlock() - err := m.addTx(tx, true) - if errors.Is(err, errTxAlreadyKnown) { - return nil - } - - return nil + return m.addTx(tx, true, true) } // checkConflictTx checks for any transactions in the mempool that spend the same input UTXOs as [tx]. // If any conflicts are present, it returns the highest gas price of any conflicting transaction, the // txID of the corresponding tx and the full list of transactions that conflict with [tx]. -func (m *Mempool) checkConflictTx(tx *atomic.Tx) (uint64, ids.ID, []*atomic.Tx, error) { +func (m *Mempool) checkConflictTx(tx *Tx) (uint64, ids.ID, []*Tx, error) { utxoSet := tx.InputUTXOs() var ( - highestGasPrice uint64 = 0 - conflictingTxs []*atomic.Tx = make([]*atomic.Tx, 0) - highestGasPriceConflictTxID ids.ID = ids.ID{} + highestGasPrice uint64 = 0 + conflictingTxs []*Tx = make([]*Tx, 0) + highestGasPriceConflictTxID ids.ID = ids.ID{} ) for utxoID := range utxoSet { // Get current gas price of the existing tx in the mempool @@ -240,7 +226,7 @@ func (m *Mempool) checkConflictTx(tx *atomic.Tx) (uint64, ids.ID, []*atomic.Tx, // addTx adds [tx] to the mempool. Assumes [m.lock] is held. // If [force], skips conflict checks within the mempool. -func (m *Mempool) addTx(tx *atomic.Tx, force bool) error { +func (m *Mempool) addTx(tx *Tx, local bool, force bool) error { txID := tx.ID() // If [txID] has already been issued or is in the currentTxs map // there's no need to add it. @@ -253,6 +239,11 @@ func (m *Mempool) addTx(tx *atomic.Tx, force bool) error { if _, exists := m.txHeap.Get(txID); exists { return fmt.Errorf("%w: tx %s is pending", errTxAlreadyKnown, tx.ID()) } + if !local { + if _, exists := m.discardedTxs.Get(txID); exists { + return fmt.Errorf("%w: tx %s was discarded", errTxAlreadyKnown, tx.ID()) + } + } if !force && m.verify != nil { if err := m.verify(tx); err != nil { return err @@ -271,7 +262,7 @@ func (m *Mempool) addTx(tx *atomic.Tx, force bool) error { if highestGasPrice >= gasPrice { return fmt.Errorf( "%w: issued tx (%s) gas price %d <= conflict tx (%s) gas price %d (%d total conflicts in mempool)", - errConflictingAtomicTx, + ErrConflictingAtomicTx, txID, gasPrice, highestGasPriceConflictTxID, @@ -296,7 +287,7 @@ func (m *Mempool) addTx(tx *atomic.Tx, force bool) error { if minGasPrice >= gasPrice { return fmt.Errorf( "%w currentMin=%d provided=%d", - errInsufficientAtomicTxFee, + ErrInsufficientAtomicTxFee, minGasPrice, gasPrice, ) @@ -306,7 +297,7 @@ func (m *Mempool) addTx(tx *atomic.Tx, force bool) error { } else { // This could occur if we have used our entire size allowance on // transactions that are currently processing. - return errTooManyAtomicTx + return ErrTooManyAtomicTx } } @@ -330,7 +321,7 @@ func (m *Mempool) addTx(tx *atomic.Tx, force bool) error { } m.bloom.Add(&GossipAtomicTx{Tx: tx}) - reset, err := gossip.ResetBloomFilterIfNeeded(m.bloom, m.length()*txGossipBloomChurnMultiplier) + reset, err := gossip.ResetBloomFilterIfNeeded(m.bloom, m.length()*config.TxGossipBloomChurnMultiplier) if err != nil { return err } @@ -372,7 +363,7 @@ func (m *Mempool) GetFilter() ([]byte, []byte) { } // NextTx returns a transaction to be issued from the mempool. -func (m *Mempool) NextTx() (*atomic.Tx, bool) { +func (m *Mempool) NextTx() (*Tx, bool) { m.lock.Lock() defer m.lock.Unlock() @@ -392,7 +383,7 @@ func (m *Mempool) NextTx() (*atomic.Tx, bool) { // GetPendingTx returns the transaction [txID] and true if it is // currently in the [txHeap] waiting to be issued into a block. // Returns nil, false otherwise. -func (m *Mempool) GetPendingTx(txID ids.ID) (*atomic.Tx, bool) { +func (m *Mempool) GetPendingTx(txID ids.ID) (*Tx, bool) { m.lock.RLock() defer m.lock.RUnlock() @@ -402,7 +393,7 @@ func (m *Mempool) GetPendingTx(txID ids.ID) (*atomic.Tx, bool) { // GetTx returns the transaction [txID] if it was issued // by this node and returns whether it was dropped and whether // it exists. -func (m *Mempool) GetTx(txID ids.ID) (*atomic.Tx, bool, bool) { +func (m *Mempool) GetTx(txID ids.ID) (*Tx, bool, bool) { m.lock.RLock() defer m.lock.RUnlock() @@ -485,7 +476,7 @@ func (m *Mempool) CancelCurrentTxs() { // cancelTx removes [tx] from current transactions and moves it back into the // tx heap. // assumes the lock is held. -func (m *Mempool) cancelTx(tx *atomic.Tx) { +func (m *Mempool) cancelTx(tx *Tx) { // Add tx to heap sorted by gasPrice gasPrice, err := m.atomicTxGasPrice(tx) if err == nil { @@ -527,7 +518,7 @@ func (m *Mempool) DiscardCurrentTxs() { // discardCurrentTx discards [tx] from the set of current transactions. // Assumes the lock is held. -func (m *Mempool) discardCurrentTx(tx *atomic.Tx) { +func (m *Mempool) discardCurrentTx(tx *Tx) { m.removeSpenders(tx) m.discardedTxs.Put(tx.ID(), tx) delete(m.currentTxs, tx.ID()) @@ -541,7 +532,7 @@ func (m *Mempool) discardCurrentTx(tx *atomic.Tx) { // removeTx must be called for all conflicts before overwriting the utxoSpenders // map. // Assumes lock is held. -func (m *Mempool) removeTx(tx *atomic.Tx, discard bool) { +func (m *Mempool) removeTx(tx *Tx, discard bool) { txID := tx.ID() // Remove from [currentTxs], [txHeap], and [issuedTxs]. @@ -566,7 +557,7 @@ func (m *Mempool) removeTx(tx *atomic.Tx, discard bool) { // removeSpenders deletes the entries for all input UTXOs of [tx] from the // [utxoSpenders] map. // Assumes the lock is held. -func (m *Mempool) removeSpenders(tx *atomic.Tx) { +func (m *Mempool) removeSpenders(tx *Tx) { for utxoID := range tx.InputUTXOs() { delete(m.utxoSpenders, utxoID) } @@ -574,7 +565,7 @@ func (m *Mempool) removeSpenders(tx *atomic.Tx) { // RemoveTx removes [txID] from the mempool completely. // Evicts [tx] from the discarded cache if present. -func (m *Mempool) RemoveTx(tx *atomic.Tx) { +func (m *Mempool) RemoveTx(tx *Tx) { m.lock.Lock() defer m.lock.Unlock() diff --git a/plugin/evm/mempool_test.go b/plugin/evm/atomic/mempool_test.go similarity index 92% rename from plugin/evm/mempool_test.go rename to plugin/evm/atomic/mempool_test.go index 8129edc577..9334853a5e 100644 --- a/plugin/evm/mempool_test.go +++ b/plugin/evm/atomic/mempool_test.go @@ -1,14 +1,13 @@ // Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package atomic import ( "testing" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" ) @@ -21,7 +20,7 @@ func TestMempoolAddTx(t *testing.T) { txs := make([]*GossipAtomicTx, 0) for i := 0; i < 3_000; i++ { tx := &GossipAtomicTx{ - Tx: &atomic.Tx{ + Tx: &Tx{ UnsignedAtomicTx: &TestUnsignedTx{ IDV: ids.GenerateTestID(), }, @@ -44,7 +43,7 @@ func TestMempoolAdd(t *testing.T) { require.NoError(err) tx := &GossipAtomicTx{ - Tx: &atomic.Tx{ + Tx: &Tx{ UnsignedAtomicTx: &TestUnsignedTx{ IDV: ids.GenerateTestID(), }, diff --git a/plugin/evm/test_tx.go b/plugin/evm/atomic/test_tx.go similarity index 74% rename from plugin/evm/test_tx.go rename to plugin/evm/atomic/test_tx.go index e001cb4dda..71437ea41e 100644 --- a/plugin/evm/test_tx.go +++ b/plugin/evm/atomic/test_tx.go @@ -1,25 +1,41 @@ // (c) 2020-2021, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package atomic import ( "math/big" "math/rand" + "github.com/ava-labs/avalanchego/codec" + "github.com/ava-labs/avalanchego/codec/linearcodec" "github.com/ava-labs/avalanchego/utils" avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" - "github.com/ava-labs/avalanchego/codec" - "github.com/ava-labs/avalanchego/codec/linearcodec" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/coreth/plugin/evm/atomic" ) +var TestTxCodec codec.Manager + +func init() { + TestTxCodec = codec.NewDefaultManager() + c := linearcodec.NewDefault() + + errs := wrappers.Errs{} + errs.Add( + c.RegisterType(&TestUnsignedTx{}), + TestTxCodec.RegisterCodec(CodecVersion, c), + ) + + if errs.Errored() { + panic(errs.Err) + } +} + type TestUnsignedTx struct { GasUsedV uint64 `serialize:"true"` AcceptRequestsBlockchainIDV ids.ID `serialize:"true"` @@ -34,7 +50,7 @@ type TestUnsignedTx struct { EVMStateTransferV error } -var _ atomic.UnsignedAtomicTx = &TestUnsignedTx{} +var _ UnsignedAtomicTx = &TestUnsignedTx{} // GasUsed implements the UnsignedAtomicTx interface func (t *TestUnsignedTx) GasUsed(fixedFee bool) (uint64, error) { return t.GasUsedV, nil } @@ -66,40 +82,39 @@ func (t *TestUnsignedTx) SignedBytes() []byte { return t.SignedBytesV } func (t *TestUnsignedTx) InputUTXOs() set.Set[ids.ID] { return t.InputUTXOsV } // SemanticVerify implements the UnsignedAtomicTx interface -func (t *TestUnsignedTx) SemanticVerify(backend *atomic.Backend, stx *atomic.Tx, parent atomic.AtomicBlockContext, baseFee *big.Int) error { +func (t *TestUnsignedTx) SemanticVerify(backend *Backend, stx *Tx, parent AtomicBlockContext, baseFee *big.Int) error { return t.SemanticVerifyV } // EVMStateTransfer implements the UnsignedAtomicTx interface -func (t *TestUnsignedTx) EVMStateTransfer(ctx *snow.Context, state atomic.StateDB) error { +func (t *TestUnsignedTx) EVMStateTransfer(ctx *snow.Context, state StateDB) error { return t.EVMStateTransferV } -func testTxCodec() codec.Manager { - codec := codec.NewDefaultManager() - c := linearcodec.NewDefault() +var TestBlockchainID = ids.GenerateTestID() - errs := wrappers.Errs{} - errs.Add( - c.RegisterType(&TestUnsignedTx{}), - c.RegisterType(&avalancheatomic.Element{}), - c.RegisterType(&avalancheatomic.Requests{}), - codec.RegisterCodec(atomic.CodecVersion, c), - ) - - if errs.Errored() { - panic(errs.Err) +func GenerateTestImportTxWithGas(gasUsed uint64, burned uint64) *Tx { + return &Tx{ + UnsignedAtomicTx: &TestUnsignedTx{ + IDV: ids.GenerateTestID(), + GasUsedV: gasUsed, + BurnedV: burned, + AcceptRequestsBlockchainIDV: TestBlockchainID, + AcceptRequestsV: &avalancheatomic.Requests{ + RemoveRequests: [][]byte{ + utils.RandomBytes(32), + utils.RandomBytes(32), + }, + }, + }, } - return codec } -var blockChainID = ids.GenerateTestID() - -func testDataImportTx() *atomic.Tx { - return &atomic.Tx{ +func GenerateTestImportTx() *Tx { + return &Tx{ UnsignedAtomicTx: &TestUnsignedTx{ IDV: ids.GenerateTestID(), - AcceptRequestsBlockchainIDV: blockChainID, + AcceptRequestsBlockchainIDV: TestBlockchainID, AcceptRequestsV: &avalancheatomic.Requests{ RemoveRequests: [][]byte{ utils.RandomBytes(32), @@ -110,11 +125,11 @@ func testDataImportTx() *atomic.Tx { } } -func testDataExportTx() *atomic.Tx { - return &atomic.Tx{ +func GenerateTestExportTx() *Tx { + return &Tx{ UnsignedAtomicTx: &TestUnsignedTx{ IDV: ids.GenerateTestID(), - AcceptRequestsBlockchainIDV: blockChainID, + AcceptRequestsBlockchainIDV: TestBlockchainID, AcceptRequestsV: &avalancheatomic.Requests{ PutRequests: []*avalancheatomic.Element{ { @@ -131,22 +146,22 @@ func testDataExportTx() *atomic.Tx { } } -func newTestTx() *atomic.Tx { +func NewTestTx() *Tx { txType := rand.Intn(2) switch txType { case 0: - return testDataImportTx() + return GenerateTestImportTx() case 1: - return testDataExportTx() + return GenerateTestExportTx() default: panic("rng generated unexpected value for tx type") } } -func newTestTxs(numTxs int) []*atomic.Tx { - txs := make([]*atomic.Tx, 0, numTxs) +func NewTestTxs(numTxs int) []*Tx { + txs := make([]*Tx, 0, numTxs) for i := 0; i < numTxs; i++ { - txs = append(txs, newTestTx()) + txs = append(txs, NewTestTx()) } return txs diff --git a/plugin/evm/atomic/tx_heap.go b/plugin/evm/atomic/tx_heap.go new file mode 100644 index 0000000000..bcec314cd7 --- /dev/null +++ b/plugin/evm/atomic/tx_heap.go @@ -0,0 +1,163 @@ +// (c) 2020-2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package atomic + +import ( + "container/heap" + + "github.com/ava-labs/avalanchego/ids" +) + +// txEntry is used to track the [gasPrice] transactions pay to be included in +// the mempool. +type txEntry struct { + id ids.ID + gasPrice uint64 + tx *Tx + index int +} + +// internalTxHeap is used to track pending atomic transactions by [gasPrice] +type internalTxHeap struct { + isMinHeap bool + items []*txEntry + lookup map[ids.ID]*txEntry +} + +func newInternalTxHeap(items int, isMinHeap bool) *internalTxHeap { + return &internalTxHeap{ + isMinHeap: isMinHeap, + items: make([]*txEntry, 0, items), + lookup: map[ids.ID]*txEntry{}, + } +} + +func (th internalTxHeap) Len() int { return len(th.items) } + +func (th internalTxHeap) Less(i, j int) bool { + if th.isMinHeap { + return th.items[i].gasPrice < th.items[j].gasPrice + } + return th.items[i].gasPrice > th.items[j].gasPrice +} + +func (th internalTxHeap) Swap(i, j int) { + th.items[i], th.items[j] = th.items[j], th.items[i] + th.items[i].index = i + th.items[j].index = j +} + +func (th *internalTxHeap) Push(x interface{}) { + entry := x.(*txEntry) + if th.Has(entry.id) { + return + } + th.items = append(th.items, entry) + th.lookup[entry.id] = entry +} + +func (th *internalTxHeap) Pop() interface{} { + n := len(th.items) + item := th.items[n-1] + th.items[n-1] = nil // avoid memory leak + th.items = th.items[0 : n-1] + delete(th.lookup, item.id) + return item +} + +func (th *internalTxHeap) Get(id ids.ID) (*txEntry, bool) { + entry, ok := th.lookup[id] + if !ok { + return nil, false + } + return entry, true +} + +func (th *internalTxHeap) Has(id ids.ID) bool { + _, has := th.Get(id) + return has +} + +type txHeap struct { + maxHeap *internalTxHeap + minHeap *internalTxHeap +} + +func newTxHeap(maxSize int) *txHeap { + return &txHeap{ + maxHeap: newInternalTxHeap(maxSize, false), + minHeap: newInternalTxHeap(maxSize, true), + } +} + +func (th *txHeap) Push(tx *Tx, gasPrice uint64) { + txID := tx.ID() + oldLen := th.Len() + heap.Push(th.maxHeap, &txEntry{ + id: txID, + gasPrice: gasPrice, + tx: tx, + index: oldLen, + }) + heap.Push(th.minHeap, &txEntry{ + id: txID, + gasPrice: gasPrice, + tx: tx, + index: oldLen, + }) +} + +// Assumes there is non-zero items in [txHeap] +func (th *txHeap) PeekMax() (*Tx, uint64) { + txEntry := th.maxHeap.items[0] + return txEntry.tx, txEntry.gasPrice +} + +// Assumes there is non-zero items in [txHeap] +func (th *txHeap) PeekMin() (*Tx, uint64) { + txEntry := th.minHeap.items[0] + return txEntry.tx, txEntry.gasPrice +} + +// Assumes there is non-zero items in [txHeap] +func (th *txHeap) PopMax() *Tx { + return th.Remove(th.maxHeap.items[0].id) +} + +// Assumes there is non-zero items in [txHeap] +func (th *txHeap) PopMin() *Tx { + return th.Remove(th.minHeap.items[0].id) +} + +func (th *txHeap) Remove(id ids.ID) *Tx { + maxEntry, ok := th.maxHeap.Get(id) + if !ok { + return nil + } + heap.Remove(th.maxHeap, maxEntry.index) + + minEntry, ok := th.minHeap.Get(id) + if !ok { + // This should never happen, as that would mean the heaps are out of + // sync. + return nil + } + return heap.Remove(th.minHeap, minEntry.index).(*txEntry).tx +} + +func (th *txHeap) Len() int { + return th.maxHeap.Len() +} + +func (th *txHeap) Get(id ids.ID) (*Tx, bool) { + txEntry, ok := th.maxHeap.Get(id) + if !ok { + return nil, false + } + return txEntry.tx, true +} + +func (th *txHeap) Has(id ids.ID) bool { + return th.maxHeap.Has(id) +} diff --git a/plugin/evm/atomic/tx_heap_test.go b/plugin/evm/atomic/tx_heap_test.go new file mode 100644 index 0000000000..c9f602ccea --- /dev/null +++ b/plugin/evm/atomic/tx_heap_test.go @@ -0,0 +1,142 @@ +// (c) 2019-2021, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package atomic + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestTxHeap(t *testing.T) { + var ( + tx0 = &Tx{ + UnsignedAtomicTx: &UnsignedImportTx{ + NetworkID: 0, + }, + } + tx0Bytes = []byte{0} + + tx1 = &Tx{ + UnsignedAtomicTx: &UnsignedImportTx{ + NetworkID: 1, + }, + } + tx1Bytes = []byte{1} + + tx2 = &Tx{ + UnsignedAtomicTx: &UnsignedImportTx{ + NetworkID: 2, + }, + } + tx2Bytes = []byte{2} + ) + tx0.Initialize(tx0Bytes, tx0Bytes) + tx1.Initialize(tx1Bytes, tx1Bytes) + tx2.Initialize(tx2Bytes, tx2Bytes) + + id0 := tx0.ID() + id1 := tx1.ID() + id2 := tx2.ID() + + t.Run("add/remove single entry", func(t *testing.T) { + h := newTxHeap(3) + assert.Zero(t, h.Len()) + + assert := assert.New(t) + h.Push(tx0, 5) + assert.True(h.Has(id0)) + gTx0, gHas0 := h.Get(id0) + assert.Equal(tx0, gTx0) + assert.True(gHas0) + h.Remove(id0) + assert.False(h.Has(id0)) + assert.Zero(h.Len()) + h.Push(tx0, 5) + assert.True(h.Has(id0)) + assert.Equal(1, h.Len()) + }) + + t.Run("add other items", func(t *testing.T) { + h := newTxHeap(3) + assert.Zero(t, h.Len()) + + assert := assert.New(t) + h.Push(tx1, 10) + assert.True(h.Has(id1)) + gTx1, gHas1 := h.Get(id1) + assert.Equal(tx1, gTx1) + assert.True(gHas1) + + h.Push(tx2, 2) + assert.True(h.Has(id2)) + gTx2, gHas2 := h.Get(id2) + assert.Equal(tx2, gTx2) + assert.True(gHas2) + + assert.Equal(id1, h.PopMax().ID()) + assert.Equal(id2, h.PopMax().ID()) + + assert.False(h.Has(id0)) + gTx0, gHas0 := h.Get(id0) + assert.Nil(gTx0) + assert.False(gHas0) + + assert.False(h.Has(id1)) + gTx1, gHas1 = h.Get(id1) + assert.Nil(gTx1) + assert.False(gHas1) + + assert.False(h.Has(id2)) + gTx2, gHas2 = h.Get(id2) + assert.Nil(gTx2) + assert.False(gHas2) + }) + + verifyRemovalOrder := func(t *testing.T, h *txHeap) { + t.Helper() + + assert := assert.New(t) + assert.Equal(id2, h.PopMin().ID()) + assert.True(h.Has(id0)) + assert.True(h.Has(id1)) + assert.False(h.Has(id2)) + assert.Equal(id0, h.PopMin().ID()) + assert.False(h.Has(id0)) + assert.True(h.Has(id1)) + assert.False(h.Has(id2)) + assert.Equal(id1, h.PopMin().ID()) + assert.False(h.Has(id0)) + assert.False(h.Has(id1)) + assert.False(h.Has(id2)) + } + + t.Run("drop", func(t *testing.T) { + h := newTxHeap(3) + assert.Zero(t, h.Len()) + + h.Push(tx0, 5) + h.Push(tx1, 10) + h.Push(tx2, 2) + verifyRemovalOrder(t, h) + }) + t.Run("drop (alt order)", func(t *testing.T) { + h := newTxHeap(3) + assert.Zero(t, h.Len()) + + h.Push(tx0, 5) + h.Push(tx2, 2) + h.Push(tx1, 10) + verifyRemovalOrder(t, h) + }) + t.Run("drop (alt order 2)", func(t *testing.T) { + h := newTxHeap(3) + assert.Zero(t, h.Len()) + + h.Push(tx2, 2) + h.Push(tx0, 5) + h.Push(tx1, 10) + verifyRemovalOrder(t, h) + }) +} diff --git a/plugin/evm/atomic_syncer_test.go b/plugin/evm/atomic_syncer_test.go index 7540be1a32..86589cc4d8 100644 --- a/plugin/evm/atomic_syncer_test.go +++ b/plugin/evm/atomic_syncer_test.go @@ -17,6 +17,7 @@ import ( "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/coreth/core/rawdb" + "github.com/ava-labs/coreth/plugin/evm/config" "github.com/ava-labs/coreth/plugin/evm/message" syncclient "github.com/ava-labs/coreth/sync/client" "github.com/ava-labs/coreth/sync/handlers" @@ -64,7 +65,7 @@ func testAtomicSyncer(t *testing.T, serverTrieDB *triedb.Database, targetHeight // next trie. for i, checkpoint := range checkpoints { // Create syncer targeting the current [syncTrie]. - syncer, err := atomicBackend.Syncer(mockClient, targetRoot, targetHeight, defaultStateSyncRequestSize) + syncer, err := atomicBackend.Syncer(mockClient, targetRoot, targetHeight, config.DefaultStateSyncRequestSize) if err != nil { t.Fatal(err) } @@ -91,7 +92,7 @@ func testAtomicSyncer(t *testing.T, serverTrieDB *triedb.Database, targetHeight } // Create syncer targeting the current [targetRoot]. - syncer, err := atomicBackend.Syncer(mockClient, targetRoot, targetHeight, defaultStateSyncRequestSize) + syncer, err := atomicBackend.Syncer(mockClient, targetRoot, targetHeight, config.DefaultStateSyncRequestSize) if err != nil { t.Fatal(err) } diff --git a/plugin/evm/atomic_trie_iterator_test.go b/plugin/evm/atomic_trie_iterator_test.go index 922aed4cfc..21ec9913f9 100644 --- a/plugin/evm/atomic_trie_iterator_test.go +++ b/plugin/evm/atomic_trie_iterator_test.go @@ -6,32 +6,33 @@ package evm import ( "testing" - "github.com/ava-labs/avalanchego/chains/atomic" + avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func testSharedMemory() atomic.SharedMemory { - m := atomic.NewMemory(memdb.New()) +func testSharedMemory() avalancheatomic.SharedMemory { + m := avalancheatomic.NewMemory(memdb.New()) return m.NewSharedMemory(testCChainID) } func TestIteratorCanIterate(t *testing.T) { lastAcceptedHeight := uint64(1000) db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec repo, err := NewAtomicTxRepository(db, codec, lastAcceptedHeight) assert.NoError(t, err) // create state with multiple transactions // since each test transaction generates random ID for blockchainID we should get // multiple blockchain IDs per block in the overall combined atomic operation map - operationsMap := make(map[uint64]map[ids.ID]*atomic.Requests) + operationsMap := make(map[uint64]map[ids.ID]*avalancheatomic.Requests) writeTxs(t, repo, 1, lastAcceptedHeight, constTxsPerHeight(3), nil, operationsMap) // create an atomic trie @@ -64,14 +65,14 @@ func TestIteratorHandlesInvalidData(t *testing.T) { require := require.New(t) lastAcceptedHeight := uint64(1000) db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec repo, err := NewAtomicTxRepository(db, codec, lastAcceptedHeight) require.NoError(err) // create state with multiple transactions // since each test transaction generates random ID for blockchainID we should get // multiple blockchain IDs per block in the overall combined atomic operation map - operationsMap := make(map[uint64]map[ids.ID]*atomic.Requests) + operationsMap := make(map[uint64]map[ids.ID]*avalancheatomic.Requests) writeTxs(t, repo, 1, lastAcceptedHeight, constTxsPerHeight(3), nil, operationsMap) // create an atomic trie diff --git a/plugin/evm/atomic_trie_test.go b/plugin/evm/atomic_trie_test.go index 193226f588..2a82964e94 100644 --- a/plugin/evm/atomic_trie_test.go +++ b/plugin/evm/atomic_trie_test.go @@ -139,7 +139,7 @@ func TestAtomicTrieInitialize(t *testing.T) { } { t.Run(name, func(t *testing.T) { db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec repo, err := NewAtomicTxRepository(db, codec, test.lastAcceptedHeight) if err != nil { t.Fatal(err) @@ -188,7 +188,7 @@ func TestAtomicTrieInitialize(t *testing.T) { // during the initialization phase will cause an invalid root when indexing continues. nextCommitHeight := nearestCommitHeight(test.lastAcceptedHeight+test.commitInterval, test.commitInterval) for i := test.lastAcceptedHeight + 1; i <= nextCommitHeight; i++ { - txs := newTestTxs(test.numTxsPerBlock(i)) + txs := atomic.NewTestTxs(test.numTxsPerBlock(i)) if err := repo.Write(i, txs); err != nil { t.Fatal(err) } @@ -228,7 +228,7 @@ func TestAtomicTrieInitialize(t *testing.T) { func TestIndexerInitializesOnlyOnce(t *testing.T) { lastAcceptedHeight := uint64(25) db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec repo, err := NewAtomicTxRepository(db, codec, lastAcceptedHeight) assert.NoError(t, err) operationsMap := make(map[uint64]map[ids.ID]*avalancheatomic.Requests) @@ -247,7 +247,7 @@ func TestIndexerInitializesOnlyOnce(t *testing.T) { // re-initialize the atomic trie since initialize is not supposed to run again the height // at the trie should still be the old height with the old commit hash without any changes. // This scenario is not realistic, but is used to test potential double initialization behavior. - err = repo.Write(15, []*atomic.Tx{testDataExportTx()}) + err = repo.Write(15, []*atomic.Tx{atomic.GenerateTestExportTx()}) assert.NoError(t, err) // Re-initialize the atomic trie @@ -262,7 +262,7 @@ func TestIndexerInitializesOnlyOnce(t *testing.T) { func newTestAtomicTrie(t *testing.T) AtomicTrie { db := versiondb.New(memdb.New()) - repo, err := NewAtomicTxRepository(db, testTxCodec(), 0) + repo, err := NewAtomicTxRepository(db, atomic.TestTxCodec, 0) if err != nil { t.Fatal(err) } @@ -282,7 +282,7 @@ func TestIndexerWriteAndRead(t *testing.T) { // process 305 blocks so that we get three commits (100, 200, 300) for height := uint64(1); height <= testCommitInterval*3+5; /*=305*/ height++ { - atomicRequests := mustAtomicOps(testDataImportTx()) + atomicRequests := mustAtomicOps(atomic.GenerateTestImportTx()) err := indexAtomicTxs(atomicTrie, height, atomicRequests) assert.NoError(t, err) if height%testCommitInterval == 0 { @@ -313,8 +313,8 @@ func TestAtomicOpsAreNotTxOrderDependent(t *testing.T) { atomicTrie2 := newTestAtomicTrie(t) for height := uint64(0); height <= testCommitInterval; /*=205*/ height++ { - tx1 := testDataImportTx() - tx2 := testDataImportTx() + tx1 := atomic.GenerateTestImportTx() + tx2 := atomic.GenerateTestImportTx() atomicRequests1, err := mergeAtomicOps([]*atomic.Tx{tx1, tx2}) assert.NoError(t, err) atomicRequests2, err := mergeAtomicOps([]*atomic.Tx{tx2, tx1}) @@ -339,7 +339,7 @@ func TestAtomicTrieDoesNotSkipBonusBlocks(t *testing.T) { commitInterval := uint64(10) expectedCommitHeight := uint64(100) db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec repo, err := NewAtomicTxRepository(db, codec, lastAcceptedHeight) if err != nil { t.Fatal(err) @@ -371,7 +371,7 @@ func TestIndexingNilShouldNotImpactTrie(t *testing.T) { // operations to index ops := make([]map[ids.ID]*avalancheatomic.Requests, 0) for i := 0; i <= testCommitInterval; i++ { - ops = append(ops, mustAtomicOps(testDataImportTx())) + ops = append(ops, mustAtomicOps(atomic.GenerateTestImportTx())) } // without nils @@ -511,9 +511,9 @@ func TestApplyToSharedMemory(t *testing.T) { commitInterval: 10, lastAcceptedHeight: 25, setMarker: func(a *atomicBackend) error { - cursor := make([]byte, wrappers.LongLen+len(blockChainID[:])) + cursor := make([]byte, wrappers.LongLen+len(atomic.TestBlockchainID[:])) binary.BigEndian.PutUint64(cursor, 10) - copy(cursor[wrappers.LongLen:], blockChainID[:]) + copy(cursor[wrappers.LongLen:], atomic.TestBlockchainID[:]) return a.metadataDB.Put(appliedSharedMemoryCursorKey, cursor) }, expectOpsApplied: func(height uint64) bool { return height > 10 && height <= 20 }, @@ -527,7 +527,7 @@ func TestApplyToSharedMemory(t *testing.T) { } { t.Run(name, func(t *testing.T) { db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec repo, err := NewAtomicTxRepository(db, codec, test.lastAcceptedHeight) assert.NoError(t, err) operationsMap := make(map[uint64]map[ids.ID]*avalancheatomic.Requests) @@ -535,7 +535,7 @@ func TestApplyToSharedMemory(t *testing.T) { // Initialize atomic repository m := avalancheatomic.NewMemory(db) - sharedMemories := newSharedMemories(m, testCChainID, blockChainID) + sharedMemories := newSharedMemories(m, testCChainID, atomic.TestBlockchainID) backend, err := NewAtomicBackend(db, sharedMemories.thisChain, test.bonusBlockHeights, repo, test.lastAcceptedHeight, common.Hash{}, test.commitInterval) assert.NoError(t, err) atomicTrie := backend.AtomicTrie().(*atomicTrie) @@ -593,7 +593,7 @@ func TestApplyToSharedMemory(t *testing.T) { func BenchmarkAtomicTrieInit(b *testing.B) { db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec operationsMap := make(map[uint64]map[ids.ID]*avalancheatomic.Requests) @@ -628,7 +628,7 @@ func BenchmarkAtomicTrieInit(b *testing.B) { func BenchmarkAtomicTrieIterate(b *testing.B) { db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec operationsMap := make(map[uint64]map[ids.ID]*avalancheatomic.Requests) @@ -707,7 +707,7 @@ func BenchmarkApplyToSharedMemory(b *testing.B) { func benchmarkApplyToSharedMemory(b *testing.B, disk database.Database, blocks uint64) { db := versiondb.New(disk) - codec := testTxCodec() + codec := atomic.TestTxCodec sharedMemory := testSharedMemory() lastAcceptedHeight := blocks @@ -720,7 +720,7 @@ func benchmarkApplyToSharedMemory(b *testing.B, disk database.Database, blocks u } trie := backend.AtomicTrie() for height := uint64(1); height <= lastAcceptedHeight; height++ { - txs := newTestTxs(constTxsPerHeight(3)(height)) + txs := atomic.NewTestTxs(constTxsPerHeight(3)(height)) ops, err := mergeAtomicOps(txs) assert.NoError(b, err) assert.NoError(b, indexAtomicTxs(trie, height, ops)) diff --git a/plugin/evm/atomic_tx_repository_test.go b/plugin/evm/atomic_tx_repository_test.go index 091bcd8f56..224f8fa726 100644 --- a/plugin/evm/atomic_tx_repository_test.go +++ b/plugin/evm/atomic_tx_repository_test.go @@ -32,7 +32,7 @@ func addTxs(t testing.TB, codec codec.Manager, acceptedAtomicTxDB database.Datab for height := fromHeight; height < toHeight; height++ { txs := make([]*atomic.Tx, 0, txsPerHeight) for i := 0; i < txsPerHeight; i++ { - tx := newTestTx() + tx := atomic.NewTestTx() txs = append(txs, tx) txBytes, err := codec.Marshal(atomic.CodecVersion, tx) assert.NoError(t, err) @@ -74,7 +74,7 @@ func writeTxs(t testing.TB, repo AtomicTxRepository, fromHeight uint64, toHeight txsPerHeight func(height uint64) int, txMap map[uint64][]*atomic.Tx, operationsMap map[uint64]map[ids.ID]*avalancheatomic.Requests, ) { for height := fromHeight; height < toHeight; height++ { - txs := newTestTxs(txsPerHeight(height)) + txs := atomic.NewTestTxs(txsPerHeight(height)) if err := repo.Write(height, txs); err != nil { t.Fatal(err) } @@ -183,7 +183,7 @@ func verifyOperations(t testing.TB, atomicTrie AtomicTrie, codec codec.Manager, func TestAtomicRepositoryReadWriteSingleTx(t *testing.T) { db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec repo, err := NewAtomicTxRepository(db, codec, 0) if err != nil { t.Fatal(err) @@ -196,7 +196,7 @@ func TestAtomicRepositoryReadWriteSingleTx(t *testing.T) { func TestAtomicRepositoryReadWriteMultipleTxs(t *testing.T) { db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec repo, err := NewAtomicTxRepository(db, codec, 0) if err != nil { t.Fatal(err) @@ -209,7 +209,7 @@ func TestAtomicRepositoryReadWriteMultipleTxs(t *testing.T) { func TestAtomicRepositoryPreAP5Migration(t *testing.T) { db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec acceptedAtomicTxDB := prefixdb.New(atomicTxIDDBPrefix, db) txMap := make(map[uint64][]*atomic.Tx) @@ -234,7 +234,7 @@ func TestAtomicRepositoryPreAP5Migration(t *testing.T) { func TestAtomicRepositoryPostAP5Migration(t *testing.T) { db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec acceptedAtomicTxDB := prefixdb.New(atomicTxIDDBPrefix, db) txMap := make(map[uint64][]*atomic.Tx) @@ -259,7 +259,7 @@ func TestAtomicRepositoryPostAP5Migration(t *testing.T) { func benchAtomicRepositoryIndex10_000(b *testing.B, maxHeight uint64, txsPerHeight int) { db := versiondb.New(memdb.New()) - codec := testTxCodec() + codec := atomic.TestTxCodec acceptedAtomicTxDB := prefixdb.New(atomicTxIDDBPrefix, db) txMap := make(map[uint64][]*atomic.Tx) diff --git a/plugin/evm/block.go b/plugin/evm/block.go index 99451cb071..9a2de32601 100644 --- a/plugin/evm/block.go +++ b/plugin/evm/block.go @@ -225,8 +225,9 @@ func (b *Block) handlePrecompileAccept(rules params.Rules) error { func (b *Block) Reject(context.Context) error { log.Debug(fmt.Sprintf("Rejecting block %s (%s) at height %d", b.ID().Hex(), b.ID(), b.Height())) for _, tx := range b.atomicTxs { + // Re-issue the transaction in the mempool, continue even if it fails b.vm.mempool.RemoveTx(tx) - if err := b.vm.mempool.AddTx(tx); err != nil { + if err := b.vm.mempool.AddRemoteTx(tx); err != nil { log.Debug("Failed to re-issue transaction in rejected block", "txID", tx.ID(), "err", err) } } diff --git a/plugin/evm/block_builder.go b/plugin/evm/block_builder.go index d8a1d07024..721561ff40 100644 --- a/plugin/evm/block_builder.go +++ b/plugin/evm/block_builder.go @@ -11,6 +11,7 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/holiman/uint256" "github.com/ava-labs/avalanchego/snow" @@ -29,7 +30,7 @@ type blockBuilder struct { chainConfig *params.ChainConfig txPool *txpool.TxPool - mempool *Mempool + mempool *atomic.Mempool shutdownChan <-chan struct{} shutdownWg *sync.WaitGroup diff --git a/plugin/evm/client/client.go b/plugin/evm/client/client.go index ddf05184d7..a6716b4b27 100644 --- a/plugin/evm/client/client.go +++ b/plugin/evm/client/client.go @@ -20,6 +20,7 @@ import ( "github.com/ava-labs/avalanchego/utils/json" "github.com/ava-labs/avalanchego/utils/rpc" "github.com/ava-labs/coreth/plugin/evm/atomic" + "github.com/ava-labs/coreth/plugin/evm/config" ) // Interface compliance @@ -43,7 +44,7 @@ type Client interface { MemoryProfile(ctx context.Context, options ...rpc.Option) error LockProfile(ctx context.Context, options ...rpc.Option) error SetLogLevel(ctx context.Context, level slog.Level, options ...rpc.Option) error - // GetVMConfig(ctx context.Context, options ...rpc.Option) (*Config, error) + GetVMConfig(ctx context.Context, options ...rpc.Option) (*config.Config, error) } // Client implementation for interacting with EVM [chain] @@ -302,9 +303,13 @@ func (c *client) SetLogLevel(ctx context.Context, level slog.Level, options ...r }, &api.EmptyReply{}, options...) } +type ConfigReply struct { + Config *config.Config `json:"config"` +} + // GetVMConfig returns the current config of the VM -// func (c *client) GetVMConfig(ctx context.Context, options ...rpc.Option) (*Config, error) { -// res := &ConfigReply{} -// err := c.adminRequester.SendRequest(ctx, "admin.getVMConfig", struct{}{}, res, options...) -// return res.Config, err -// } +func (c *client) GetVMConfig(ctx context.Context, options ...rpc.Option) (*config.Config, error) { + res := &ConfigReply{} + err := c.adminRequester.SendRequest(ctx, "admin.getVMConfig", struct{}{}, res, options...) + return res.Config, err +} diff --git a/plugin/evm/config.go b/plugin/evm/config/config.go similarity index 95% rename from plugin/evm/config.go rename to plugin/evm/config/config.go index c0fa3b0386..a92405bcb5 100644 --- a/plugin/evm/config.go +++ b/plugin/evm/config/config.go @@ -1,13 +1,14 @@ // (c) 2019-2020, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package config import ( "encoding/json" "fmt" "time" + "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/coreth/core/txpool/legacypool" "github.com/ava-labs/coreth/eth" "github.com/ethereum/go-ethereum/common" @@ -59,7 +60,7 @@ const ( // - normal bootstrap processing time: ~14 blocks / second // - state sync time: ~6 hrs. defaultStateSyncMinBlocks = 300_000 - defaultStateSyncRequestSize = 1024 // the number of key/values to ask peers for per request + DefaultStateSyncRequestSize = 1024 // the number of key/values to ask peers for per request ) var ( @@ -277,7 +278,7 @@ func (c *Config) SetDefaults() { c.StateSyncServerTrieCache = defaultStateSyncServerTrieCache c.StateSyncCommitInterval = defaultSyncableCommitInterval c.StateSyncMinBlocks = defaultStateSyncMinBlocks - c.StateSyncRequestSize = defaultStateSyncRequestSize + c.StateSyncRequestSize = DefaultStateSyncRequestSize c.AllowUnprotectedTxHashes = defaultAllowUnprotectedTxHashes c.AcceptedCacheSize = defaultAcceptedCacheSize } @@ -302,7 +303,17 @@ func (d Duration) MarshalJSON() ([]byte, error) { } // Validate returns an error if this is an invalid config. -func (c *Config) Validate() error { +func (c *Config) Validate(networkID uint32) error { + // Ensure that non-standard commit interval is not allowed for production networks + if constants.ProductionNetworkIDs.Contains(networkID) { + if c.CommitInterval != defaultCommitInterval { + return fmt.Errorf("cannot start non-local network with commit interval %d different than %d", c.CommitInterval, defaultCommitInterval) + } + if c.StateSyncCommitInterval != defaultSyncableCommitInterval { + return fmt.Errorf("cannot start non-local network with syncable interval %d different than %d", c.StateSyncCommitInterval, defaultSyncableCommitInterval) + } + } + if c.PopulateMissingTries != nil && (c.OfflinePruning || c.Pruning) { return fmt.Errorf("cannot enable populate missing tries while offline pruning (enabled: %t)/pruning (enabled: %t) are enabled", c.OfflinePruning, c.Pruning) } diff --git a/plugin/evm/config_test.go b/plugin/evm/config/config_test.go similarity index 99% rename from plugin/evm/config_test.go rename to plugin/evm/config/config_test.go index 9a8384bf5d..ad13ebdfed 100644 --- a/plugin/evm/config_test.go +++ b/plugin/evm/config/config_test.go @@ -1,7 +1,7 @@ // (c) 2019-2020, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package config import ( "encoding/json" diff --git a/plugin/evm/config/constants.go b/plugin/evm/config/constants.go new file mode 100644 index 0000000000..2e47489f1c --- /dev/null +++ b/plugin/evm/config/constants.go @@ -0,0 +1,8 @@ +package config + +const ( + TxGossipBloomMinTargetElements = 8 * 1024 + TxGossipBloomTargetFalsePositiveRate = 0.01 + TxGossipBloomResetFalsePositiveRate = 0.05 + TxGossipBloomChurnMultiplier = 3 +) diff --git a/plugin/evm/export_tx_test.go b/plugin/evm/export_tx_test.go index eabbb05ede..36b74ab45a 100644 --- a/plugin/evm/export_tx_test.go +++ b/plugin/evm/export_tx_test.go @@ -1944,7 +1944,7 @@ func TestNewExportTxMulticoin(t *testing.T) { t.Fatal(err) } - if err := vm.mempool.AddTx(tx); err != nil { + if err := vm.mempool.AddRemoteTx(tx); err != nil { t.Fatal(err) } diff --git a/plugin/evm/gossip.go b/plugin/evm/gossip.go index d6b377d13a..16d632bd94 100644 --- a/plugin/evm/gossip.go +++ b/plugin/evm/gossip.go @@ -1,13 +1,15 @@ // Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. +// TODO: move to network + package evm import ( "context" "fmt" "sync" - syncatomic "sync/atomic" + "sync/atomic" "time" ethcommon "github.com/ethereum/go-ethereum/common" @@ -24,7 +26,7 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/eth" - "github.com/ava-labs/coreth/plugin/evm/atomic" + "github.com/ava-labs/coreth/plugin/evm/config" ) const pendingTxsBuffer = 10 @@ -32,11 +34,9 @@ const pendingTxsBuffer = 10 var ( _ p2p.Handler = (*txGossipHandler)(nil) - _ gossip.Gossipable = (*GossipEthTx)(nil) - _ gossip.Gossipable = (*GossipAtomicTx)(nil) - _ gossip.Marshaller[*GossipAtomicTx] = (*GossipAtomicTxMarshaller)(nil) - _ gossip.Marshaller[*GossipEthTx] = (*GossipEthTxMarshaller)(nil) - _ gossip.Set[*GossipEthTx] = (*GossipEthTxPool)(nil) + _ gossip.Gossipable = (*GossipEthTx)(nil) + _ gossip.Marshaller[*GossipEthTx] = (*GossipEthTxMarshaller)(nil) + _ gossip.Set[*GossipEthTx] = (*GossipEthTxPool)(nil) _ eth.PushGossiper = (*EthPushGossiper)(nil) ) @@ -91,29 +91,14 @@ func (t txGossipHandler) AppRequest(ctx context.Context, nodeID ids.NodeID, dead return t.appRequestHandler.AppRequest(ctx, nodeID, deadline, requestBytes) } -type GossipAtomicTxMarshaller struct{} - -func (g GossipAtomicTxMarshaller) MarshalGossip(tx *GossipAtomicTx) ([]byte, error) { - return tx.Tx.SignedBytes(), nil -} - -func (g GossipAtomicTxMarshaller) UnmarshalGossip(bytes []byte) (*GossipAtomicTx, error) { - tx, err := atomic.ExtractAtomicTx(bytes, atomic.Codec) - return &GossipAtomicTx{ - Tx: tx, - }, err -} - -type GossipAtomicTx struct { - Tx *atomic.Tx -} - -func (tx *GossipAtomicTx) GossipID() ids.ID { - return tx.Tx.ID() -} - func NewGossipEthTxPool(mempool *txpool.TxPool, registerer prometheus.Registerer) (*GossipEthTxPool, error) { - bloom, err := gossip.NewBloomFilter(registerer, "eth_tx_bloom_filter", txGossipBloomMinTargetElements, txGossipBloomTargetFalsePositiveRate, txGossipBloomResetFalsePositiveRate) + bloom, err := gossip.NewBloomFilter( + registerer, + "eth_tx_bloom_filter", + config.TxGossipBloomMinTargetElements, + config.TxGossipBloomTargetFalsePositiveRate, + config.TxGossipBloomResetFalsePositiveRate, + ) if err != nil { return nil, fmt.Errorf("failed to initialize bloom filter: %w", err) } @@ -134,7 +119,7 @@ type GossipEthTxPool struct { // subscribed is set to true when the gossip subscription is active // mostly used for testing - subscribed syncatomic.Bool + subscribed atomic.Bool } // IsSubscribed returns whether or not the gossip subscription is active. @@ -161,7 +146,7 @@ func (g *GossipEthTxPool) Subscribe(ctx context.Context) { return case pendingTxs := <-g.pendingTxs: g.lock.Lock() - optimalElements := (g.mempool.PendingSize(txpool.PendingFilter{}) + len(pendingTxs.Txs)) * txGossipBloomChurnMultiplier + optimalElements := (g.mempool.PendingSize(txpool.PendingFilter{}) + len(pendingTxs.Txs)) * config.TxGossipBloomChurnMultiplier for _, pendingTx := range pendingTxs.Txs { tx := &GossipEthTx{Tx: pendingTx} g.bloom.Add(tx) diff --git a/plugin/evm/gossip_stats.go b/plugin/evm/gossip_stats.go deleted file mode 100644 index 9805c7f1ff..0000000000 --- a/plugin/evm/gossip_stats.go +++ /dev/null @@ -1,67 +0,0 @@ -// (c) 2022, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package evm - -import "github.com/ava-labs/coreth/metrics" - -var _ GossipStats = &gossipStats{} - -// GossipStats contains methods for updating incoming and outgoing gossip stats. -type GossipStats interface { - IncAtomicGossipReceived() - IncEthTxsGossipReceived() - - // new vs. known txs received - IncAtomicGossipReceivedDropped() - IncAtomicGossipReceivedError() - IncAtomicGossipReceivedKnown() - IncAtomicGossipReceivedNew() - IncEthTxsGossipReceivedError() - IncEthTxsGossipReceivedKnown() - IncEthTxsGossipReceivedNew() -} - -// gossipStats implements stats for incoming and outgoing gossip stats. -type gossipStats struct { - // messages - atomicGossipReceived metrics.Counter - ethTxsGossipReceived metrics.Counter - - // new vs. known txs received - atomicGossipReceivedDropped metrics.Counter - atomicGossipReceivedError metrics.Counter - atomicGossipReceivedKnown metrics.Counter - atomicGossipReceivedNew metrics.Counter - ethTxsGossipReceivedError metrics.Counter - ethTxsGossipReceivedKnown metrics.Counter - ethTxsGossipReceivedNew metrics.Counter -} - -func NewGossipStats() GossipStats { - return &gossipStats{ - atomicGossipReceived: metrics.GetOrRegisterCounter("gossip_atomic_received", nil), - ethTxsGossipReceived: metrics.GetOrRegisterCounter("gossip_eth_txs_received", nil), - - atomicGossipReceivedDropped: metrics.GetOrRegisterCounter("gossip_atomic_received_dropped", nil), - atomicGossipReceivedError: metrics.GetOrRegisterCounter("gossip_atomic_received_error", nil), - atomicGossipReceivedKnown: metrics.GetOrRegisterCounter("gossip_atomic_received_known", nil), - atomicGossipReceivedNew: metrics.GetOrRegisterCounter("gossip_atomic_received_new", nil), - ethTxsGossipReceivedError: metrics.GetOrRegisterCounter("gossip_eth_txs_received_error", nil), - ethTxsGossipReceivedKnown: metrics.GetOrRegisterCounter("gossip_eth_txs_received_known", nil), - ethTxsGossipReceivedNew: metrics.GetOrRegisterCounter("gossip_eth_txs_received_new", nil), - } -} - -// incoming messages -func (g *gossipStats) IncAtomicGossipReceived() { g.atomicGossipReceived.Inc(1) } -func (g *gossipStats) IncEthTxsGossipReceived() { g.ethTxsGossipReceived.Inc(1) } - -// new vs. known txs received -func (g *gossipStats) IncAtomicGossipReceivedDropped() { g.atomicGossipReceivedDropped.Inc(1) } -func (g *gossipStats) IncAtomicGossipReceivedError() { g.atomicGossipReceivedError.Inc(1) } -func (g *gossipStats) IncAtomicGossipReceivedKnown() { g.atomicGossipReceivedKnown.Inc(1) } -func (g *gossipStats) IncAtomicGossipReceivedNew() { g.atomicGossipReceivedNew.Inc(1) } -func (g *gossipStats) IncEthTxsGossipReceivedError() { g.ethTxsGossipReceivedError.Inc(1) } -func (g *gossipStats) IncEthTxsGossipReceivedKnown() { g.ethTxsGossipReceivedKnown.Inc(1) } -func (g *gossipStats) IncEthTxsGossipReceivedNew() { g.ethTxsGossipReceivedNew.Inc(1) } diff --git a/plugin/evm/gossip_test.go b/plugin/evm/gossip_test.go index 15ebd15871..84380001dc 100644 --- a/plugin/evm/gossip_test.go +++ b/plugin/evm/gossip_test.go @@ -9,11 +9,7 @@ import ( "testing" "time" - "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/network/p2p/gossip" - "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" - "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/coreth/consensus/dummy" "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/rawdb" @@ -22,7 +18,6 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/core/vm" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/prometheus/client_golang/prometheus" @@ -30,110 +25,6 @@ import ( "github.com/stretchr/testify/require" ) -func TestGossipAtomicTxMarshaller(t *testing.T) { - require := require.New(t) - - want := &GossipAtomicTx{ - Tx: &atomic.Tx{ - UnsignedAtomicTx: &atomic.UnsignedImportTx{}, - Creds: []verify.Verifiable{}, - }, - } - marshaller := GossipAtomicTxMarshaller{} - - key0 := testKeys[0] - require.NoError(want.Tx.Sign(atomic.Codec, [][]*secp256k1.PrivateKey{{key0}})) - - bytes, err := marshaller.MarshalGossip(want) - require.NoError(err) - - got, err := marshaller.UnmarshalGossip(bytes) - require.NoError(err) - require.Equal(want.GossipID(), got.GossipID()) -} - -func TestAtomicMempoolIterate(t *testing.T) { - txs := []*GossipAtomicTx{ - { - Tx: &atomic.Tx{ - UnsignedAtomicTx: &TestUnsignedTx{ - IDV: ids.GenerateTestID(), - }, - }, - }, - { - Tx: &atomic.Tx{ - UnsignedAtomicTx: &TestUnsignedTx{ - IDV: ids.GenerateTestID(), - }, - }, - }, - } - - tests := []struct { - name string - add []*GossipAtomicTx - f func(tx *GossipAtomicTx) bool - possibleValues []*GossipAtomicTx - expectedLen int - }{ - { - name: "func matches nothing", - add: txs, - f: func(*GossipAtomicTx) bool { - return false - }, - possibleValues: nil, - }, - { - name: "func matches all", - add: txs, - f: func(*GossipAtomicTx) bool { - return true - }, - possibleValues: txs, - expectedLen: 2, - }, - { - name: "func matches subset", - add: txs, - f: func(tx *GossipAtomicTx) bool { - return tx.Tx == txs[0].Tx - }, - possibleValues: txs, - expectedLen: 1, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require := require.New(t) - m, err := NewMempool(&snow.Context{}, prometheus.NewRegistry(), 10, nil) - require.NoError(err) - - for _, add := range tt.add { - require.NoError(m.Add(add)) - } - - matches := make([]*GossipAtomicTx, 0) - f := func(tx *GossipAtomicTx) bool { - match := tt.f(tx) - - if match { - matches = append(matches, tx) - } - - return match - } - - m.Iterate(f) - - require.Len(matches, tt.expectedLen) - require.Subset(tt.possibleValues, matches) - }) - } -} - func TestGossipEthTxMarshaller(t *testing.T) { require := require.New(t) diff --git a/plugin/evm/gossiper_atomic_gossiping_test.go b/plugin/evm/gossiper_atomic_gossiping_test.go index 0974b50638..e2c97167f8 100644 --- a/plugin/evm/gossiper_atomic_gossiping_test.go +++ b/plugin/evm/gossiper_atomic_gossiping_test.go @@ -5,17 +5,21 @@ package evm import ( "context" + "encoding/binary" "sync" "testing" "time" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/network/p2p" + "github.com/ava-labs/avalanchego/proto/pb/sdk" "github.com/ava-labs/avalanchego/utils/set" "github.com/stretchr/testify/assert" + "google.golang.org/protobuf/proto" commonEng "github.com/ava-labs/avalanchego/snow/engine/common" - "github.com/ava-labs/coreth/plugin/evm/message" + "github.com/ava-labs/coreth/plugin/evm/atomic" ) // show that a txID discovered from gossip is requested to the same node only if @@ -53,14 +57,17 @@ func TestMempoolAtmTxsAppGossipHandling(t *testing.T) { tx, conflictingTx := importTxs[0], importTxs[1] // gossip tx and check it is accepted and gossiped - msg := message.AtomicTxGossip{ - Tx: tx.SignedBytes(), + msg := atomic.GossipAtomicTx{ + Tx: tx, } - msgBytes, err := message.BuildGossipMessage(vm.networkCodec, msg) + marshaller := atomic.GossipAtomicTxMarshaller{} + txBytes, err := marshaller.MarshalGossip(&msg) assert.NoError(err) - vm.ctx.Lock.Unlock() + msgBytes, err := buildAtomicPushGossip(txBytes) + assert.NoError(err) + // show that no txID is requested assert.NoError(vm.AppGossip(context.Background(), nodeID, msgBytes)) time.Sleep(500 * time.Millisecond) @@ -85,14 +92,17 @@ func TestMempoolAtmTxsAppGossipHandling(t *testing.T) { txGossipedLock.Unlock() // show that conflicting tx is not added to mempool - msg = message.AtomicTxGossip{ - Tx: conflictingTx.SignedBytes(), + msg = atomic.GossipAtomicTx{ + Tx: conflictingTx, } - msgBytes, err = message.BuildGossipMessage(vm.networkCodec, msg) + marshaller = atomic.GossipAtomicTxMarshaller{} + txBytes, err = marshaller.MarshalGossip(&msg) assert.NoError(err) vm.ctx.Lock.Unlock() + msgBytes, err = buildAtomicPushGossip(txBytes) + assert.NoError(err) assert.NoError(vm.AppGossip(context.Background(), nodeID, msgBytes)) vm.ctx.Lock.Lock() @@ -137,7 +147,7 @@ func TestMempoolAtmTxsAppGossipHandlingDiscardedTx(t *testing.T) { tx, conflictingTx := importTxs[0], importTxs[1] txID := tx.ID() - mempool.AddTx(tx) + mempool.AddRemoteTx(tx) mempool.NextTx() mempool.DiscardCurrentTx(txID) @@ -147,14 +157,17 @@ func TestMempoolAtmTxsAppGossipHandlingDiscardedTx(t *testing.T) { // Gossip the transaction to the VM and ensure that it is not added to the mempool // and is not re-gossipped. nodeID := ids.GenerateTestNodeID() - msg := message.AtomicTxGossip{ - Tx: tx.SignedBytes(), + msg := atomic.GossipAtomicTx{ + Tx: tx, } - msgBytes, err := message.BuildGossipMessage(vm.networkCodec, msg) + marshaller := atomic.GossipAtomicTxMarshaller{} + txBytes, err := marshaller.MarshalGossip(&msg) assert.NoError(err) vm.ctx.Lock.Unlock() + msgBytes, err := buildAtomicPushGossip(txBytes) + assert.NoError(err) assert.NoError(vm.AppGossip(context.Background(), nodeID, msgBytes)) vm.ctx.Lock.Lock() @@ -171,8 +184,8 @@ func TestMempoolAtmTxsAppGossipHandlingDiscardedTx(t *testing.T) { // Conflicting tx must be submitted over the API to be included in push gossip. // (i.e., txs received via p2p are not included in push gossip) // This test adds it directly to the mempool + gossiper to simulate that. - vm.mempool.AddTx(conflictingTx) - vm.atomicTxPushGossiper.Add(&GossipAtomicTx{conflictingTx}) + vm.mempool.AddRemoteTx(conflictingTx) + vm.atomicTxPushGossiper.Add(&atomic.GossipAtomicTx{Tx: conflictingTx}) time.Sleep(500 * time.Millisecond) vm.ctx.Lock.Lock() @@ -185,3 +198,16 @@ func TestMempoolAtmTxsAppGossipHandlingDiscardedTx(t *testing.T) { assert.False(mempool.Has(txID)) assert.True(mempool.Has(conflictingTx.ID())) } + +func buildAtomicPushGossip(txBytes []byte) ([]byte, error) { + inboundGossip := &sdk.PushGossip{ + Gossip: [][]byte{txBytes}, + } + inboundGossipBytes, err := proto.Marshal(inboundGossip) + if err != nil { + return nil, err + } + + inboundGossipMsg := append(binary.AppendUvarint(nil, p2p.AtomicTxGossipHandlerID), inboundGossipBytes...) + return inboundGossipMsg, nil +} diff --git a/plugin/evm/handler.go b/plugin/evm/handler.go deleted file mode 100644 index c4b41a85e7..0000000000 --- a/plugin/evm/handler.go +++ /dev/null @@ -1,140 +0,0 @@ -// (c) 2019-2021, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package evm - -import ( - "github.com/ava-labs/avalanchego/ids" - - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - - "github.com/ava-labs/coreth/core/txpool" - "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ava-labs/coreth/plugin/evm/message" -) - -// GossipHandler handles incoming gossip messages -type GossipHandler struct { - vm *VM - atomicMempool *Mempool - txPool *txpool.TxPool - stats GossipStats -} - -func NewGossipHandler(vm *VM, stats GossipStats) *GossipHandler { - return &GossipHandler{ - vm: vm, - atomicMempool: vm.mempool, - txPool: vm.txPool, - stats: stats, - } -} - -func (h *GossipHandler) HandleAtomicTx(nodeID ids.NodeID, msg message.AtomicTxGossip) error { - log.Trace( - "AppGossip called with AtomicTxGossip", - "peerID", nodeID, - ) - - if len(msg.Tx) == 0 { - log.Trace( - "AppGossip received empty AtomicTxGossip Message", - "peerID", nodeID, - ) - return nil - } - - // In the case that the gossip message contains a transaction, - // attempt to parse it and add it as a remote. - tx := atomic.Tx{} - if _, err := atomic.Codec.Unmarshal(msg.Tx, &tx); err != nil { - log.Trace( - "AppGossip provided invalid tx", - "err", err, - ) - return nil - } - unsignedBytes, err := atomic.Codec.Marshal(atomic.CodecVersion, &tx.UnsignedAtomicTx) - if err != nil { - log.Trace( - "AppGossip failed to marshal unsigned tx", - "err", err, - ) - return nil - } - tx.Initialize(unsignedBytes, msg.Tx) - - txID := tx.ID() - h.stats.IncAtomicGossipReceived() - if _, dropped, found := h.atomicMempool.GetTx(txID); found { - h.stats.IncAtomicGossipReceivedKnown() - return nil - } else if dropped { - h.stats.IncAtomicGossipReceivedDropped() - return nil - } - - h.stats.IncAtomicGossipReceivedNew() - - h.vm.ctx.Lock.RLock() - defer h.vm.ctx.Lock.RUnlock() - - if err := h.vm.mempool.AddTx(&tx); err != nil { - log.Trace( - "AppGossip provided invalid transaction", - "peerID", nodeID, - "err", err, - ) - h.stats.IncAtomicGossipReceivedError() - } - - return nil -} - -func (h *GossipHandler) HandleEthTxs(nodeID ids.NodeID, msg message.EthTxsGossip) error { - log.Trace( - "AppGossip called with EthTxsGossip", - "peerID", nodeID, - "size(txs)", len(msg.Txs), - ) - - if len(msg.Txs) == 0 { - log.Trace( - "AppGossip received empty EthTxsGossip Message", - "peerID", nodeID, - ) - return nil - } - - // The maximum size of this encoded object is enforced by the codec. - txs := make([]*types.Transaction, 0) - if err := rlp.DecodeBytes(msg.Txs, &txs); err != nil { - log.Trace( - "AppGossip provided invalid txs", - "peerID", nodeID, - "err", err, - ) - return nil - } - h.stats.IncEthTxsGossipReceived() - errs := h.txPool.Add(txs, false, false) - for i, err := range errs { - if err != nil { - log.Trace( - "AppGossip failed to add to mempool", - "err", err, - "tx", txs[i].Hash(), - ) - if err == txpool.ErrAlreadyKnown { - h.stats.IncEthTxsGossipReceivedKnown() - } else { - h.stats.IncEthTxsGossipReceivedError() - } - continue - } - h.stats.IncEthTxsGossipReceivedNew() - } - return nil -} diff --git a/plugin/evm/mempool_atomic_gossiping_test.go b/plugin/evm/mempool_atomic_gossiping_test.go index 3e22fef486..9f2cc89535 100644 --- a/plugin/evm/mempool_atomic_gossiping_test.go +++ b/plugin/evm/mempool_atomic_gossiping_test.go @@ -9,9 +9,11 @@ import ( "testing" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/components/chain" "github.com/ava-labs/coreth/plugin/evm/atomic" + "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" ) @@ -53,7 +55,7 @@ func TestMempoolAddLocallyCreateAtomicTx(t *testing.T) { // try to add a conflicting tx err = vm.mempool.AddLocalTx(conflictingTx) - assert.ErrorIs(err, errConflictingAtomicTx) + assert.ErrorIs(err, atomic.ErrConflictingAtomicTx) has = mempool.Has(conflictingTxID) assert.False(has, "conflicting tx in mempool") @@ -92,27 +94,22 @@ func TestMempoolAddLocallyCreateAtomicTx(t *testing.T) { func TestMempoolMaxMempoolSizeHandling(t *testing.T) { assert := assert.New(t) - _, vm, _, sharedMemory, _ := GenesisVM(t, true, "", "", "") - defer func() { - err := vm.Shutdown(context.Background()) - assert.NoError(err) - }() - mempool := vm.mempool - + mempool, err := atomic.NewMempool(&snow.Context{}, prometheus.NewRegistry(), 1, nil) + assert.NoError(err) // create candidate tx (we will drop before validation) - tx := createImportTxOptions(t, vm, sharedMemory)[0] + tx := atomic.GenerateTestImportTx() - // shortcut to simulated almost filled mempool - mempool.maxSize = 0 - - assert.ErrorIs(mempool.AddTx(tx), errTooManyAtomicTx) - assert.False(mempool.Has(tx.ID())) - - // shortcut to simulated empty mempool - mempool.maxSize = defaultMempoolSize - - assert.NoError(mempool.AddTx(tx)) + assert.NoError(mempool.AddRemoteTx(tx)) assert.True(mempool.Has(tx.ID())) + // promote tx to be issued + _, ok := mempool.NextTx() + assert.True(ok) + mempool.IssueCurrentTxs() + + // try to add one more tx + tx2 := atomic.GenerateTestImportTx() + assert.ErrorIs(mempool.AddRemoteTx(tx2), atomic.ErrTooManyAtomicTx) + assert.False(mempool.Has(tx2.ID())) } // mempool will drop transaction with the lowest fee @@ -129,21 +126,21 @@ func TestMempoolPriorityDrop(t *testing.T) { err := vm.Shutdown(context.Background()) assert.NoError(err) }() - mempool := vm.mempool - mempool.maxSize = 1 + mempool, err := atomic.NewMempool(vm.ctx, prometheus.NewRegistry(), 1, vm.verifyTxAtTip) + assert.NoError(err) tx1, err := vm.newImportTx(vm.ctx.XChainID, testEthAddrs[0], initialBaseFee, []*secp256k1.PrivateKey{testKeys[0]}) if err != nil { t.Fatal(err) } - assert.NoError(mempool.AddTx(tx1)) + assert.NoError(mempool.AddRemoteTx(tx1)) assert.True(mempool.Has(tx1.ID())) tx2, err := vm.newImportTx(vm.ctx.XChainID, testEthAddrs[1], initialBaseFee, []*secp256k1.PrivateKey{testKeys[1]}) if err != nil { t.Fatal(err) } - assert.ErrorIs(mempool.AddTx(tx2), errInsufficientAtomicTxFee) + assert.ErrorIs(mempool.AddRemoteTx(tx2), atomic.ErrInsufficientAtomicTxFee) assert.True(mempool.Has(tx1.ID())) assert.False(mempool.Has(tx2.ID())) @@ -151,7 +148,7 @@ func TestMempoolPriorityDrop(t *testing.T) { if err != nil { t.Fatal(err) } - assert.NoError(mempool.AddTx(tx3)) + assert.NoError(mempool.AddRemoteTx(tx3)) assert.False(mempool.Has(tx1.ID())) assert.False(mempool.Has(tx2.ID())) assert.True(mempool.Has(tx3.ID())) diff --git a/plugin/evm/message/codec.go b/plugin/evm/message/codec.go index de3603b9c2..664c9252bb 100644 --- a/plugin/evm/message/codec.go +++ b/plugin/evm/message/codec.go @@ -15,20 +15,16 @@ const ( maxMessageSize = 2*units.MiB - 64*units.KiB // Subtract 64 KiB from p2p network cap to leave room for encoding overhead from AvalancheGo ) -var ( - Codec codec.Manager -) +var Codec codec.Manager func init() { Codec = codec.NewManager(maxMessageSize) c := linearcodec.NewDefault() errs := wrappers.Errs{} + // Gossip types removed from codec + c.SkipRegistrations(2) errs.Add( - // Gossip types - c.RegisterType(AtomicTxGossip{}), - c.RegisterType(EthTxsGossip{}), - // Types for state sync frontier consensus c.RegisterType(SyncSummary{}), diff --git a/plugin/evm/message/handler.go b/plugin/evm/message/handler.go index 9b94828509..1b910e3826 100644 --- a/plugin/evm/message/handler.go +++ b/plugin/evm/message/handler.go @@ -6,33 +6,10 @@ package message import ( "context" - "github.com/ethereum/go-ethereum/log" - "github.com/ava-labs/avalanchego/ids" ) -var ( - _ GossipHandler = NoopMempoolGossipHandler{} - _ RequestHandler = NoopRequestHandler{} -) - -// GossipHandler handles incoming gossip messages -type GossipHandler interface { - HandleAtomicTx(nodeID ids.NodeID, msg AtomicTxGossip) error - HandleEthTxs(nodeID ids.NodeID, msg EthTxsGossip) error -} - -type NoopMempoolGossipHandler struct{} - -func (NoopMempoolGossipHandler) HandleAtomicTx(nodeID ids.NodeID, msg AtomicTxGossip) error { - log.Debug("dropping unexpected AtomicTxGossip message", "peerID", nodeID) - return nil -} - -func (NoopMempoolGossipHandler) HandleEthTxs(nodeID ids.NodeID, msg EthTxsGossip) error { - log.Debug("dropping unexpected EthTxsGossip message", "peerID", nodeID) - return nil -} +var _ RequestHandler = NoopRequestHandler{} // RequestHandler interface handles incoming requests from peers // Must have methods in format of handleType(context.Context, ids.NodeID, uint32, request Type) error diff --git a/plugin/evm/message/handler_test.go b/plugin/evm/message/handler_test.go deleted file mode 100644 index a27b1f9d4f..0000000000 --- a/plugin/evm/message/handler_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// (c) 2019-2021, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package message - -import ( - "testing" - - "github.com/ava-labs/avalanchego/ids" - - "github.com/stretchr/testify/assert" -) - -type CounterHandler struct { - AtomicTx, EthTxs int -} - -func (h *CounterHandler) HandleAtomicTx(ids.NodeID, AtomicTxGossip) error { - h.AtomicTx++ - return nil -} - -func (h *CounterHandler) HandleEthTxs(ids.NodeID, EthTxsGossip) error { - h.EthTxs++ - return nil -} - -func TestHandleAtomicTx(t *testing.T) { - assert := assert.New(t) - - handler := CounterHandler{} - msg := AtomicTxGossip{} - - err := msg.Handle(&handler, ids.EmptyNodeID) - assert.NoError(err) - assert.Equal(1, handler.AtomicTx) - assert.Zero(handler.EthTxs) -} - -func TestHandleEthTxs(t *testing.T) { - assert := assert.New(t) - - handler := CounterHandler{} - msg := EthTxsGossip{} - - err := msg.Handle(&handler, ids.EmptyNodeID) - assert.NoError(err) - assert.Zero(handler.AtomicTx) - assert.Equal(1, handler.EthTxs) -} - -func TestNoopHandler(t *testing.T) { - assert := assert.New(t) - - handler := NoopMempoolGossipHandler{} - - err := handler.HandleEthTxs(ids.EmptyNodeID, EthTxsGossip{}) - assert.NoError(err) - - err = handler.HandleAtomicTx(ids.EmptyNodeID, AtomicTxGossip{}) - assert.NoError(err) -} diff --git a/plugin/evm/message/message.go b/plugin/evm/message/message.go deleted file mode 100644 index c8c80a0343..0000000000 --- a/plugin/evm/message/message.go +++ /dev/null @@ -1,78 +0,0 @@ -// (c) 2019-2021, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package message - -import ( - "errors" - "fmt" - - "github.com/ava-labs/avalanchego/codec" - - "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/utils/units" -) - -const ( - // EthMsgSoftCapSize is the ideal size of encoded transaction bytes we send in - // any [EthTxsGossip] or [AtomicTxGossip] message. We do not limit inbound messages to - // this size, however. Max inbound message size is enforced by the codec - // (512KB). - EthMsgSoftCapSize = 64 * units.KiB -) - -var ( - _ GossipMessage = AtomicTxGossip{} - _ GossipMessage = EthTxsGossip{} - - errUnexpectedCodecVersion = errors.New("unexpected codec version") -) - -type GossipMessage interface { - // types implementing GossipMessage should also implement fmt.Stringer for logging purposes. - fmt.Stringer - - // Handle this gossip message with the gossip handler. - Handle(handler GossipHandler, nodeID ids.NodeID) error -} - -type AtomicTxGossip struct { - Tx []byte `serialize:"true"` -} - -func (msg AtomicTxGossip) Handle(handler GossipHandler, nodeID ids.NodeID) error { - return handler.HandleAtomicTx(nodeID, msg) -} - -func (msg AtomicTxGossip) String() string { - return fmt.Sprintf("AtomicTxGossip(Len=%d)", len(msg.Tx)) -} - -type EthTxsGossip struct { - Txs []byte `serialize:"true"` -} - -func (msg EthTxsGossip) Handle(handler GossipHandler, nodeID ids.NodeID) error { - return handler.HandleEthTxs(nodeID, msg) -} - -func (msg EthTxsGossip) String() string { - return fmt.Sprintf("EthTxsGossip(Len=%d)", len(msg.Txs)) -} - -func ParseGossipMessage(codec codec.Manager, bytes []byte) (GossipMessage, error) { - var msg GossipMessage - version, err := codec.Unmarshal(bytes, &msg) - if err != nil { - return nil, err - } - if version != Version { - return nil, errUnexpectedCodecVersion - } - return msg, nil -} - -func BuildGossipMessage(codec codec.Manager, msg GossipMessage) ([]byte, error) { - bytes, err := codec.Marshal(Version, &msg) - return bytes, err -} diff --git a/plugin/evm/message/message_test.go b/plugin/evm/message/message_test.go deleted file mode 100644 index dbcdea2d75..0000000000 --- a/plugin/evm/message/message_test.go +++ /dev/null @@ -1,78 +0,0 @@ -// (c) 2019-2021, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package message - -import ( - "encoding/base64" - "testing" - - "github.com/ava-labs/avalanchego/utils" - "github.com/ava-labs/avalanchego/utils/units" - - "github.com/stretchr/testify/assert" -) - -// TestMarshalAtomicTx asserts that the structure or serialization logic hasn't changed, primarily to -// ensure compatibility with the network. -func TestMarshalAtomicTx(t *testing.T) { - assert := assert.New(t) - - base64AtomicTxGossip := "AAAAAAAAAAAABGJsYWg=" - msg := []byte("blah") - builtMsg := AtomicTxGossip{ - Tx: msg, - } - builtMsgBytes, err := BuildGossipMessage(Codec, builtMsg) - assert.NoError(err) - assert.Equal(base64AtomicTxGossip, base64.StdEncoding.EncodeToString(builtMsgBytes)) - - parsedMsgIntf, err := ParseGossipMessage(Codec, builtMsgBytes) - assert.NoError(err) - - parsedMsg, ok := parsedMsgIntf.(AtomicTxGossip) - assert.True(ok) - - assert.Equal(msg, parsedMsg.Tx) -} - -// TestMarshalEthTxs asserts that the structure or serialization logic hasn't changed, primarily to -// ensure compatibility with the network. -func TestMarshalEthTxs(t *testing.T) { - assert := assert.New(t) - - base64EthTxGossip := "AAAAAAABAAAABGJsYWg=" - msg := []byte("blah") - builtMsg := EthTxsGossip{ - Txs: msg, - } - builtMsgBytes, err := BuildGossipMessage(Codec, builtMsg) - assert.NoError(err) - assert.Equal(base64EthTxGossip, base64.StdEncoding.EncodeToString(builtMsgBytes)) - - parsedMsgIntf, err := ParseGossipMessage(Codec, builtMsgBytes) - assert.NoError(err) - - parsedMsg, ok := parsedMsgIntf.(EthTxsGossip) - assert.True(ok) - - assert.Equal(msg, parsedMsg.Txs) -} - -func TestEthTxsTooLarge(t *testing.T) { - assert := assert.New(t) - - builtMsg := EthTxsGossip{ - Txs: utils.RandomBytes(maxMessageSize), - } - _, err := BuildGossipMessage(Codec, builtMsg) - assert.Error(err) -} - -func TestParseGibberish(t *testing.T) { - assert := assert.New(t) - - randomBytes := utils.RandomBytes(256 * units.KiB) - _, err := ParseGossipMessage(Codec, randomBytes) - assert.Error(err) -} diff --git a/plugin/evm/service.go b/plugin/evm/service.go index 40f09314f4..49ad2a895f 100644 --- a/plugin/evm/service.go +++ b/plugin/evm/service.go @@ -196,7 +196,7 @@ func (service *AvaxAPI) Import(_ *http.Request, args *client.ImportArgs, respons if err := service.vm.mempool.AddLocalTx(tx); err != nil { return err } - service.vm.atomicTxPushGossiper.Add(&GossipAtomicTx{tx}) + service.vm.atomicTxPushGossiper.Add(&atomic.GossipAtomicTx{Tx: tx}) return nil } @@ -280,7 +280,7 @@ func (service *AvaxAPI) Export(_ *http.Request, args *client.ExportArgs, respons if err := service.vm.mempool.AddLocalTx(tx); err != nil { return err } - service.vm.atomicTxPushGossiper.Add(&GossipAtomicTx{tx}) + service.vm.atomicTxPushGossiper.Add(&atomic.GossipAtomicTx{Tx: tx}) return nil } @@ -390,7 +390,7 @@ func (service *AvaxAPI) IssueTx(r *http.Request, args *api.FormattedTx, response if err := service.vm.mempool.AddLocalTx(tx); err != nil { return err } - service.vm.atomicTxPushGossiper.Add(&GossipAtomicTx{tx}) + service.vm.atomicTxPushGossiper.Add(&atomic.GossipAtomicTx{Tx: tx}) return nil } diff --git a/plugin/evm/tx_gossip_test.go b/plugin/evm/tx_gossip_test.go index 514b7fadbd..35527a51f7 100644 --- a/plugin/evm/tx_gossip_test.go +++ b/plugin/evm/tx_gossip_test.go @@ -36,6 +36,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/plugin/evm/atomic" + "github.com/ava-labs/coreth/plugin/evm/config" "github.com/ava-labs/coreth/utils" ) @@ -104,7 +105,13 @@ func TestEthTxGossip(t *testing.T) { } // Ask the VM for any new transactions. We should get nothing at first. - emptyBloomFilter, err := gossip.NewBloomFilter(prometheus.NewRegistry(), "", txGossipBloomMinTargetElements, txGossipBloomTargetFalsePositiveRate, txGossipBloomResetFalsePositiveRate) + emptyBloomFilter, err := gossip.NewBloomFilter( + prometheus.NewRegistry(), + "", + config.TxGossipBloomMinTargetElements, + config.TxGossipBloomTargetFalsePositiveRate, + config.TxGossipBloomResetFalsePositiveRate, + ) require.NoError(err) emptyBloomFilterBytes, _ := emptyBloomFilter.Marshal() request := &sdk.PullGossipRequest{ @@ -231,7 +238,13 @@ func TestAtomicTxGossip(t *testing.T) { } // Ask the VM for any new transactions. We should get nothing at first. - emptyBloomFilter, err := gossip.NewBloomFilter(prometheus.NewRegistry(), "", txGossipBloomMinTargetElements, txGossipBloomTargetFalsePositiveRate, txGossipBloomResetFalsePositiveRate) + emptyBloomFilter, err := gossip.NewBloomFilter( + prometheus.NewRegistry(), + "", + config.TxGossipBloomMinTargetElements, + config.TxGossipBloomTargetFalsePositiveRate, + config.TxGossipBloomResetFalsePositiveRate, + ) require.NoError(err) emptyBloomFilterBytes, _ := emptyBloomFilter.Marshal() request := &sdk.PullGossipRequest{ @@ -278,7 +291,7 @@ func TestAtomicTxGossip(t *testing.T) { // Ask the VM for new transactions. We should get the newly issued tx. wg.Add(1) - marshaller := GossipAtomicTxMarshaller{} + marshaller := atomic.GossipAtomicTxMarshaller{} onResponse = func(_ context.Context, nodeID ids.NodeID, responseBytes []byte, err error) { require.NoError(err) @@ -479,7 +492,7 @@ func TestAtomicTxPushGossipOutbound(t *testing.T) { tx, err := atomic.NewImportTx(vm.ctx, vm.currentRules(), vm.clock.Unix(), vm.ctx.XChainID, address, initialBaseFee, secp256k1fx.NewKeychain(pk), []*avax.UTXO{utxo}) require.NoError(err) require.NoError(vm.mempool.AddLocalTx(tx)) - vm.atomicTxPushGossiper.Add(&GossipAtomicTx{tx}) + vm.atomicTxPushGossiper.Add(&atomic.GossipAtomicTx{Tx: tx}) gossipedBytes := <-sender.SentAppGossip require.Equal(byte(p2p.AtomicTxGossipHandlerID), gossipedBytes[0]) @@ -488,7 +501,7 @@ func TestAtomicTxPushGossipOutbound(t *testing.T) { require.NoError(proto.Unmarshal(gossipedBytes[1:], outboundGossipMsg)) require.Len(outboundGossipMsg.Gossip, 1) - marshaller := GossipAtomicTxMarshaller{} + marshaller := atomic.GossipAtomicTxMarshaller{} gossipedTx, err := marshaller.UnmarshalGossip(outboundGossipMsg.Gossip[0]) require.NoError(err) require.Equal(tx.ID(), gossipedTx.Tx.ID()) @@ -551,8 +564,8 @@ func TestAtomicTxPushGossipInbound(t *testing.T) { require.NoError(err) require.NoError(vm.mempool.AddLocalTx(tx)) - marshaller := GossipAtomicTxMarshaller{} - gossipedTx := &GossipAtomicTx{ + marshaller := atomic.GossipAtomicTxMarshaller{} + gossipedTx := &atomic.GossipAtomicTx{ Tx: tx, } gossipBytes, err := marshaller.MarshalGossip(gossipedTx) diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index d3221e8f34..6900c26ea0 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -41,6 +41,7 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/peer" "github.com/ava-labs/coreth/plugin/evm/atomic" + "github.com/ava-labs/coreth/plugin/evm/config" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/triedb" "github.com/ava-labs/coreth/triedb/hashdb" @@ -129,16 +130,12 @@ const ( targetAtomicTxsSize = 40 * units.KiB // gossip constants - pushGossipDiscardedElements = 16_384 - txGossipBloomMinTargetElements = 8 * 1024 - txGossipBloomTargetFalsePositiveRate = 0.01 - txGossipBloomResetFalsePositiveRate = 0.05 - txGossipBloomChurnMultiplier = 3 - txGossipTargetMessageSize = 20 * units.KiB - maxValidatorSetStaleness = time.Minute - txGossipThrottlingPeriod = 10 * time.Second - txGossipThrottlingLimit = 2 - txGossipPollSize = 1 + pushGossipDiscardedElements = 16_384 + txGossipTargetMessageSize = 20 * units.KiB + maxValidatorSetStaleness = time.Minute + txGossipThrottlingPeriod = 10 * time.Second + txGossipThrottlingLimit = 2 + txGossipPollSize = 1 ) // Define the API endpoints for the VM @@ -168,15 +165,12 @@ var ( errEmptyBlock = errors.New("empty block") errUnsupportedFXs = errors.New("unsupported feature extensions") errInvalidBlock = errors.New("invalid block") - errInsufficientAtomicTxFee = errors.New("atomic tx fee too low for atomic mempool") errInvalidNonce = errors.New("invalid nonce") errUnclesUnsupported = errors.New("uncles unsupported") errRejectedParent = errors.New("rejected parent") errNilBaseFeeApricotPhase3 = errors.New("nil base fee is invalid after apricotPhase3") errNilExtDataGasUsedApricotPhase4 = errors.New("nil extDataGasUsed is invalid after apricotPhase4") errNilBlockGasCostApricotPhase4 = errors.New("nil blockGasCost is invalid after apricotPhase4") - errConflictingAtomicTx = errors.New("conflicting atomic tx present") - errTooManyAtomicTx = errors.New("too many atomic tx") errInvalidHeaderPredicateResults = errors.New("invalid header predicate results") ) @@ -217,7 +211,7 @@ type VM struct { // with an efficient caching layer. *chain.State - config Config + config config.Config chainID *big.Int networkID uint64 @@ -265,7 +259,7 @@ type VM struct { baseCodec codec.Registry clock mockable.Clock - mempool *Mempool + mempool *atomic.Mempool shutdownChan chan struct{} shutdownWg sync.WaitGroup @@ -303,7 +297,7 @@ type VM struct { ethTxPushGossiper avalancheUtils.Atomic[*gossip.PushGossiper[*GossipEthTx]] ethTxPullGossiper gossip.Gossiper atomicTxGossipHandler p2p.Handler - atomicTxPushGossiper *gossip.PushGossiper[*GossipAtomicTx] + atomicTxPushGossiper *gossip.PushGossiper[*atomic.GossipAtomicTx] atomicTxPullGossiper gossip.Gossiper chainAlias string @@ -349,7 +343,9 @@ func (vm *VM) Initialize( return fmt.Errorf("failed to unmarshal config %s: %w", string(configBytes), err) } } - if err := vm.config.Validate(); err != nil { + vm.ctx = chainCtx + + if err := vm.config.Validate(vm.ctx.NetworkID); err != nil { return err } // We should deprecate config flags as the first thing, before we do anything else @@ -357,8 +353,6 @@ func (vm *VM) Initialize( // initialized the logger. deprecateMsg := vm.config.Deprecate() - vm.ctx = chainCtx - // Create logger alias, err := vm.ctx.BCLookup.PrimaryAlias(vm.ctx.ChainID) if err != nil { @@ -452,16 +446,6 @@ func (vm *VM) Initialize( } vm.syntacticBlockValidator = NewBlockValidator(extDataHashes) - // Ensure that non-standard commit interval is not allowed for production networks - if avalanchegoConstants.ProductionNetworkIDs.Contains(chainCtx.NetworkID) { - if vm.config.CommitInterval != defaultCommitInterval { - return fmt.Errorf("cannot start non-local network with commit interval %d", vm.config.CommitInterval) - } - if vm.config.StateSyncCommitInterval != defaultSyncableCommitInterval { - return fmt.Errorf("cannot start non-local network with syncable interval %d", vm.config.StateSyncCommitInterval) - } - } - // Free the memory of the extDataHash map that is not used (i.e. if mainnet // config, free fuji) fujiExtDataHashes = nil @@ -543,7 +527,7 @@ func (vm *VM) Initialize( } // TODO: read size from settings - vm.mempool, err = NewMempool(chainCtx, vm.sdkMetrics, defaultMempoolSize, vm.verifyTxAtTip) + vm.mempool, err = atomic.NewMempool(chainCtx, vm.sdkMetrics, defaultMempoolSize, vm.verifyTxAtTip) if err != nil { return fmt.Errorf("failed to initialize mempool: %w", err) } @@ -553,6 +537,7 @@ func (vm *VM) Initialize( vm.p2pSender = appSender } + // TODO: move all network stuff to peer.NewNetwork p2pNetwork, err := p2p.NewNetwork(vm.ctx.Log, vm.p2pSender, vm.sdkMetrics, "p2p") if err != nil { return fmt.Errorf("failed to initialize p2p network: %w", err) @@ -1077,7 +1062,7 @@ func (vm *VM) initBlockBuilding() error { vm.shutdownWg.Done() }() - atomicTxGossipMarshaller := GossipAtomicTxMarshaller{} + atomicTxGossipMarshaller := atomic.GossipAtomicTxMarshaller{} atomicTxGossipClient := vm.Network.NewClient(p2p.AtomicTxGossipHandlerID, p2p.WithValidatorSampling(vm.validators)) atomicTxGossipMetrics, err := gossip.NewMetrics(vm.sdkMetrics, atomicTxGossipNamespace) if err != nil { @@ -1115,7 +1100,7 @@ func (vm *VM) initBlockBuilding() error { } if vm.atomicTxPushGossiper == nil { - vm.atomicTxPushGossiper, err = gossip.NewPushGossiper[*GossipAtomicTx]( + vm.atomicTxPushGossiper, err = gossip.NewPushGossiper[*atomic.GossipAtomicTx]( atomicTxGossipMarshaller, vm.mempool, vm.validators, @@ -1133,10 +1118,8 @@ func (vm *VM) initBlockBuilding() error { } // NOTE: gossip network must be initialized first otherwise ETH tx gossip will not work. - gossipStats := NewGossipStats() vm.builder = vm.NewBlockBuilder(vm.toEngine) vm.builder.awaitSubmittedTxs() - vm.Network.SetGossipHandler(NewGossipHandler(vm, gossipStats)) if vm.ethTxGossipHandler == nil { vm.ethTxGossipHandler = newTxGossipHandler[*GossipEthTx]( @@ -1156,7 +1139,7 @@ func (vm *VM) initBlockBuilding() error { } if vm.atomicTxGossipHandler == nil { - vm.atomicTxGossipHandler = newTxGossipHandler[*GossipAtomicTx]( + vm.atomicTxGossipHandler = newTxGossipHandler[*atomic.GossipAtomicTx]( vm.ctx.Log, atomicTxGossipMarshaller, vm.mempool, @@ -1200,7 +1183,7 @@ func (vm *VM) initBlockBuilding() error { }() if vm.atomicTxPullGossiper == nil { - atomicTxPullGossiper := gossip.NewPullGossiper[*GossipAtomicTx]( + atomicTxPullGossiper := gossip.NewPullGossiper[*atomic.GossipAtomicTx]( vm.ctx.Log, atomicTxGossipMarshaller, vm.mempool, diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index a9a5bbd6e3..56b56cf93c 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -25,6 +25,7 @@ import ( "github.com/ava-labs/coreth/eth/filters" "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/plugin/evm/atomic" + "github.com/ava-labs/coreth/plugin/evm/config" "github.com/ava-labs/coreth/trie" "github.com/ava-labs/coreth/utils" @@ -400,7 +401,7 @@ func TestVMConfigDefaults(t *testing.T) { configJSON := fmt.Sprintf(`{"rpc-tx-fee-cap": %g,"eth-apis": %s}`, txFeeCap, fmt.Sprintf("[%q]", enabledEthAPIs[0])) _, vm, _, _, _ := GenesisVM(t, false, "", configJSON, "") - var vmConfig Config + var vmConfig config.Config vmConfig.SetDefaults() vmConfig.RPCTxFeeCap = txFeeCap vmConfig.EnabledEthAPIs = enabledEthAPIs @@ -412,7 +413,7 @@ func TestVMNilConfig(t *testing.T) { _, vm, _, _, _ := GenesisVM(t, false, "", "", "") // VM Config should match defaults if no config is passed in - var vmConfig Config + var vmConfig config.Config vmConfig.SetDefaults() require.Equal(t, vmConfig, vm.config, "VM Config should match default config") require.NoError(t, vm.Shutdown(context.Background())) @@ -1094,8 +1095,8 @@ func TestReissueAtomicTxHigherGasPrice(t *testing.T) { t.Fatal(err) } - if err := vm.mempool.AddLocalTx(reissuanceTx1); !errors.Is(err, errConflictingAtomicTx) { - t.Fatalf("Expected to fail with err: %s, but found err: %s", errConflictingAtomicTx, err) + if err := vm.mempool.AddLocalTx(reissuanceTx1); !errors.Is(err, atomic.ErrConflictingAtomicTx) { + t.Fatalf("Expected to fail with err: %s, but found err: %s", atomic.ErrConflictingAtomicTx, err) } assert.True(t, vm.mempool.Has(importTx1.ID())) @@ -1118,12 +1119,12 @@ func TestReissueAtomicTxHigherGasPrice(t *testing.T) { issuedTxs, evictedTxs := issueTxs(t, vm, sharedMemory) for i, tx := range issuedTxs { - _, issued := vm.mempool.txHeap.Get(tx.ID()) + _, issued := vm.mempool.GetPendingTx(tx.ID()) assert.True(t, issued, "expected issued tx at index %d to be issued", i) } for i, tx := range evictedTxs { - _, discarded := vm.mempool.discardedTxs.Get(tx.ID()) + _, discarded, _ := vm.mempool.GetTx(tx.ID()) assert.True(t, discarded, "expected discarded tx at index %d to be discarded", i) } }) @@ -3039,7 +3040,7 @@ func TestAtomicTxFailsEVMStateTransferBuildBlock(t *testing.T) { t.Fatal("Should have failed to issue due to an invalid export tx") } - if err := vm.mempool.AddTx(exportTx2); err == nil { + if err := vm.mempool.AddRemoteTx(exportTx2); err == nil { t.Fatal("Should have failed to add because conflicting") } @@ -3576,8 +3577,8 @@ func TestConsecutiveAtomicTransactionsRevertSnapshot(t *testing.T) { // Add the two conflicting transactions directly to the mempool, so that two consecutive transactions // will fail verification when build block is called. - vm.mempool.AddTx(importTxs[1]) - vm.mempool.AddTx(importTxs[2]) + vm.mempool.AddRemoteTx(importTxs[1]) + vm.mempool.AddRemoteTx(importTxs[2]) if _, err := vm.BuildBlock(context.Background()); err == nil { t.Fatal("Expected build block to fail due to empty block") From cf1dd75b2209fc19e300193aeae90933ea43b6b9 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Fri, 3 Jan 2025 08:21:49 -0800 Subject: [PATCH 15/69] refactor trie_prefetcher to be similar to upstream structurally (#727) Co-authored-by: Quentin McGaw Co-authored-by: Arran Schlosberg <519948+ARR4N@users.noreply.github.com> --- RELEASES.md | 1 + core/blockchain.go | 20 +- core/state/statedb.go | 22 +- core/state/trie_prefetcher.go | 538 ++++++----------------- core/state/trie_prefetcher.libevm.go | 126 ++++++ core/state/trie_prefetcher_extra_test.go | 189 ++++++++ core/state/trie_prefetcher_test.go | 6 +- libevm/options/options.go | 42 ++ libevm/sync/sync.go | 52 +++ miner/worker.go | 7 +- 10 files changed, 585 insertions(+), 418 deletions(-) create mode 100644 core/state/trie_prefetcher.libevm.go create mode 100644 core/state/trie_prefetcher_extra_test.go create mode 100644 libevm/options/options.go create mode 100644 libevm/sync/sync.go diff --git a/RELEASES.md b/RELEASES.md index 7f8393b5de..bce253816e 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -3,6 +3,7 @@ ## [v0.14.1](https://github.com/ava-labs/coreth/releases/tag/v0.14.1) - Remove API eth_getAssetBalance that was used to query ANT balances (deprecated since v0.10.0) - Remove legacy gossip handler and metrics (deprecated since v0.10.0) +- Refactored trie_prefetcher.go to be structurally similar to [upstream](https://github.com/ethereum/go-ethereum/tree/v1.13.14). ## [v0.14.0](https://github.com/ava-labs/coreth/releases/tag/v0.14.0) - Minor version update to correspond to avalanchego v1.12.0 / Etna. diff --git a/core/blockchain.go b/core/blockchain.go index db3a49bdb0..0199ceaf8a 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -1288,16 +1288,6 @@ func (bc *BlockChain) insertBlock(block *types.Block, writes bool) error { blockContentValidationTimer.Inc(time.Since(substart).Milliseconds()) // No validation errors for the block - var activeState *state.StateDB - defer func() { - // The chain importer is starting and stopping trie prefetchers. If a bad - // block or other error is hit however, an early return may not properly - // terminate the background threads. This defer ensures that we clean up - // and dangling prefetcher, without deferring each and holding on live refs. - if activeState != nil { - activeState.StopPrefetcher() - } - }() // Retrieve the parent block to determine which root to build state on substart = time.Now() @@ -1316,8 +1306,8 @@ func (bc *BlockChain) insertBlock(block *types.Block, writes bool) error { blockStateInitTimer.Inc(time.Since(substart).Milliseconds()) // Enable prefetching to pull in trie node paths while processing transactions - statedb.StartPrefetcher("chain", bc.cacheConfig.TriePrefetcherParallelism) - activeState = statedb + statedb.StartPrefetcher("chain", state.WithConcurrentWorkers(bc.cacheConfig.TriePrefetcherParallelism)) + defer statedb.StopPrefetcher() // Process block using the parent state as reference point pstart := time.Now() @@ -1675,10 +1665,8 @@ func (bc *BlockChain) reprocessBlock(parent *types.Block, current *types.Block) } // Enable prefetching to pull in trie node paths while processing transactions - statedb.StartPrefetcher("chain", bc.cacheConfig.TriePrefetcherParallelism) - defer func() { - statedb.StopPrefetcher() - }() + statedb.StartPrefetcher("chain", state.WithConcurrentWorkers(bc.cacheConfig.TriePrefetcherParallelism)) + defer statedb.StopPrefetcher() // Process previously stored block receipts, _, usedGas, err := bc.processor.Process(current, parent.Header(), statedb, vm.Config{}) diff --git a/core/state/statedb.go b/core/state/statedb.go index 3096589b6e..0dccd28bf8 100644 --- a/core/state/statedb.go +++ b/core/state/statedb.go @@ -42,6 +42,7 @@ import ( "github.com/ava-labs/coreth/trie" "github.com/ava-labs/coreth/trie/trienode" "github.com/ava-labs/coreth/trie/triestate" + "github.com/ava-labs/coreth/utils" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/log" @@ -201,16 +202,33 @@ func NewWithSnapshot(root common.Hash, db Database, snap snapshot.Snapshot) (*St return sdb, nil } +type workerPool struct { + *utils.BoundedWorkers +} + +func (wp *workerPool) Done() { + // Done is guaranteed to only be called after all work is already complete, + // so Wait()ing is redundant, but it also releases resources. + wp.BoundedWorkers.Wait() +} + +func WithConcurrentWorkers(prefetchers int) PrefetcherOption { + pool := &workerPool{ + BoundedWorkers: utils.NewBoundedWorkers(prefetchers), + } + return WithWorkerPools(func() WorkerPool { return pool }) +} + // StartPrefetcher initializes a new trie prefetcher to pull in nodes from the // state trie concurrently while the state is mutated so that when we reach the // commit phase, most of the needed data is already hot. -func (s *StateDB) StartPrefetcher(namespace string, maxConcurrency int) { +func (s *StateDB) StartPrefetcher(namespace string, opts ...PrefetcherOption) { if s.prefetcher != nil { s.prefetcher.close() s.prefetcher = nil } if s.snap != nil { - s.prefetcher = newTriePrefetcher(s.db, s.originalRoot, namespace, maxConcurrency) + s.prefetcher = newTriePrefetcher(s.db, s.originalRoot, namespace, opts...) } } diff --git a/core/state/trie_prefetcher.go b/core/state/trie_prefetcher.go index 5b01083f59..fc7be65b4a 100644 --- a/core/state/trie_prefetcher.go +++ b/core/state/trie_prefetcher.go @@ -1,13 +1,3 @@ -// (c) 2019-2020, Ava Labs, Inc. -// -// This file is a derived work, based on the go-ethereum library whose original -// notices appear below. -// -// It is distributed under a license compatible with the licensing terms of the -// original code from which it is derived. -// -// Much love to the original authors for their work. -// ********** // Copyright 2020 The go-ethereum Authors // This file is part of the go-ethereum library. // @@ -28,16 +18,17 @@ package state import ( "sync" - "time" + "github.com/ava-labs/coreth/libevm/options" "github.com/ava-labs/coreth/metrics" - "github.com/ava-labs/coreth/utils" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" ) -// triePrefetchMetricsPrefix is the prefix under which to publish the metrics. -const triePrefetchMetricsPrefix = "trie/prefetch/" +var ( + // triePrefetchMetricsPrefix is the prefix under which to publish the metrics. + triePrefetchMetricsPrefix = "trie/prefetch/" +) // triePrefetcher is an active prefetcher, which receives accounts or storage // items and does trie-loading of them. The goal is to get as much useful content @@ -50,91 +41,61 @@ type triePrefetcher struct { fetches map[string]Trie // Partially or fully fetched tries. Only populated for inactive copies. fetchers map[string]*subfetcher // Subfetchers for each trie - maxConcurrency int - workers *utils.BoundedWorkers - - subfetcherWorkersMeter metrics.Meter - subfetcherWaitTimer metrics.Counter - subfetcherCopiesMeter metrics.Meter - + deliveryMissMeter metrics.Meter accountLoadMeter metrics.Meter accountDupMeter metrics.Meter accountSkipMeter metrics.Meter accountWasteMeter metrics.Meter + storageLoadMeter metrics.Meter + storageDupMeter metrics.Meter + storageSkipMeter metrics.Meter + storageWasteMeter metrics.Meter - storageFetchersMeter metrics.Meter - storageLoadMeter metrics.Meter - storageLargestLoadMeter metrics.Meter - storageDupMeter metrics.Meter - storageSkipMeter metrics.Meter - storageWasteMeter metrics.Meter + options []PrefetcherOption } -func newTriePrefetcher(db Database, root common.Hash, namespace string, maxConcurrency int) *triePrefetcher { +func newTriePrefetcher(db Database, root common.Hash, namespace string, opts ...PrefetcherOption) *triePrefetcher { prefix := triePrefetchMetricsPrefix + namespace - return &triePrefetcher{ + p := &triePrefetcher{ db: db, root: root, fetchers: make(map[string]*subfetcher), // Active prefetchers use the fetchers map - maxConcurrency: maxConcurrency, - workers: utils.NewBoundedWorkers(maxConcurrency), // Scale up as needed to [maxConcurrency] - - subfetcherWorkersMeter: metrics.GetOrRegisterMeter(prefix+"/subfetcher/workers", nil), - subfetcherWaitTimer: metrics.GetOrRegisterCounter(prefix+"/subfetcher/wait", nil), - subfetcherCopiesMeter: metrics.GetOrRegisterMeter(prefix+"/subfetcher/copies", nil), - + deliveryMissMeter: metrics.GetOrRegisterMeter(prefix+"/deliverymiss", nil), accountLoadMeter: metrics.GetOrRegisterMeter(prefix+"/account/load", nil), accountDupMeter: metrics.GetOrRegisterMeter(prefix+"/account/dup", nil), accountSkipMeter: metrics.GetOrRegisterMeter(prefix+"/account/skip", nil), accountWasteMeter: metrics.GetOrRegisterMeter(prefix+"/account/waste", nil), + storageLoadMeter: metrics.GetOrRegisterMeter(prefix+"/storage/load", nil), + storageDupMeter: metrics.GetOrRegisterMeter(prefix+"/storage/dup", nil), + storageSkipMeter: metrics.GetOrRegisterMeter(prefix+"/storage/skip", nil), + storageWasteMeter: metrics.GetOrRegisterMeter(prefix+"/storage/waste", nil), - storageFetchersMeter: metrics.GetOrRegisterMeter(prefix+"/storage/fetchers", nil), - storageLoadMeter: metrics.GetOrRegisterMeter(prefix+"/storage/load", nil), - storageLargestLoadMeter: metrics.GetOrRegisterMeter(prefix+"/storage/lload", nil), - storageDupMeter: metrics.GetOrRegisterMeter(prefix+"/storage/dup", nil), - storageSkipMeter: metrics.GetOrRegisterMeter(prefix+"/storage/skip", nil), - storageWasteMeter: metrics.GetOrRegisterMeter(prefix+"/storage/waste", nil), + options: opts, } + return p } // close iterates over all the subfetchers, aborts any that were left spinning // and reports the stats to the metrics subsystem. func (p *triePrefetcher) close() { - // If the prefetcher is an inactive one, bail out - if p.fetches != nil { - return - } - - // Collect stats from all fetchers - var ( - storageFetchers int64 - largestLoad int64 - ) for _, fetcher := range p.fetchers { - fetcher.abort() // safe to call multiple times (should be a no-op on happy path) + fetcher.abort() // safe to do multiple times if metrics.Enabled { - p.subfetcherCopiesMeter.Mark(int64(fetcher.copies())) - if fetcher.root == p.root { p.accountLoadMeter.Mark(int64(len(fetcher.seen))) p.accountDupMeter.Mark(int64(fetcher.dups)) - p.accountSkipMeter.Mark(int64(fetcher.skips())) + p.accountSkipMeter.Mark(int64(len(fetcher.tasks))) for _, key := range fetcher.used { delete(fetcher.seen, string(key)) } p.accountWasteMeter.Mark(int64(len(fetcher.seen))) } else { - storageFetchers++ - oseen := int64(len(fetcher.seen)) - if oseen > largestLoad { - largestLoad = oseen - } - p.storageLoadMeter.Mark(oseen) + p.storageLoadMeter.Mark(int64(len(fetcher.seen))) p.storageDupMeter.Mark(int64(fetcher.dups)) - p.storageSkipMeter.Mark(int64(fetcher.skips())) + p.storageSkipMeter.Mark(int64(len(fetcher.tasks))) for _, key := range fetcher.used { delete(fetcher.seen, string(key)) @@ -143,20 +104,7 @@ func (p *triePrefetcher) close() { } } } - if metrics.Enabled { - p.storageFetchersMeter.Mark(storageFetchers) - p.storageLargestLoadMeter.Mark(largestLoad) - } - - // Stop all workers once fetchers are aborted (otherwise - // could stop while waiting) - // - // Record number of workers that were spawned during this run - workersUsed := int64(p.workers.Wait()) - if metrics.Enabled { - p.subfetcherWorkersMeter.Mark(workersUsed) - } - + p.releaseWorkerPools() // Clear out all fetchers (will crash on a second call, deliberate) p.fetchers = nil } @@ -169,23 +117,19 @@ func (p *triePrefetcher) copy() *triePrefetcher { copy := &triePrefetcher{ db: p.db, root: p.root, - fetches: make(map[string]Trie), // Active prefetchers use the fetchers map - - subfetcherWorkersMeter: p.subfetcherWorkersMeter, - subfetcherWaitTimer: p.subfetcherWaitTimer, - subfetcherCopiesMeter: p.subfetcherCopiesMeter, + fetches: make(map[string]Trie), // Active prefetchers use the fetches map + deliveryMissMeter: p.deliveryMissMeter, accountLoadMeter: p.accountLoadMeter, accountDupMeter: p.accountDupMeter, accountSkipMeter: p.accountSkipMeter, accountWasteMeter: p.accountWasteMeter, + storageLoadMeter: p.storageLoadMeter, + storageDupMeter: p.storageDupMeter, + storageSkipMeter: p.storageSkipMeter, + storageWasteMeter: p.storageWasteMeter, - storageFetchersMeter: p.storageFetchersMeter, - storageLoadMeter: p.storageLoadMeter, - storageLargestLoadMeter: p.storageLargestLoadMeter, - storageDupMeter: p.storageDupMeter, - storageSkipMeter: p.storageSkipMeter, - storageWasteMeter: p.storageWasteMeter, + options: p.options, } // If the prefetcher is already a copy, duplicate the data if p.fetches != nil { @@ -210,12 +154,11 @@ func (p *triePrefetcher) prefetch(owner common.Hash, root common.Hash, addr comm if p.fetches != nil { return } - // Active fetcher, schedule the retrievals id := p.trieID(owner, root) fetcher := p.fetchers[id] if fetcher == nil { - fetcher = newSubfetcher(p, owner, root, addr) + fetcher = newSubfetcher(p.db, p.root, owner, root, addr, p.options...) p.fetchers[id] = fetcher } fetcher.schedule(keys) @@ -229,27 +172,24 @@ func (p *triePrefetcher) trie(owner common.Hash, root common.Hash) Trie { if p.fetches != nil { trie := p.fetches[id] if trie == nil { + p.deliveryMissMeter.Mark(1) return nil } return p.db.CopyTrie(trie) } - // Otherwise the prefetcher is active, bail if no trie was prefetched for this root fetcher := p.fetchers[id] if fetcher == nil { + p.deliveryMissMeter.Mark(1) return nil } + // Interrupt the prefetcher if it's by any chance still running and return + // a copy of any pre-loaded trie. + fetcher.abort() // safe to do multiple times - // Wait for the fetcher to finish and shutdown orchestrator, if it exists - start := time.Now() - fetcher.wait() - if metrics.Enabled { - p.subfetcherWaitTimer.Inc(time.Since(start).Milliseconds()) - } - - // Return a copy of one of the prefetched tries trie := fetcher.peek() if trie == nil { + p.deliveryMissMeter.Mark(1) return nil } return trie @@ -276,365 +216,175 @@ func (p *triePrefetcher) trieID(owner common.Hash, root common.Hash) string { // main prefetcher is paused and either all requested items are processed or if // the trie being worked on is retrieved from the prefetcher. type subfetcher struct { - p *triePrefetcher - db Database // Database to load trie nodes through state common.Hash // Root hash of the state to prefetch owner common.Hash // Owner of the trie, usually account hash root common.Hash // Root hash of the trie to prefetch addr common.Address // Address of the account that the trie belongs to + trie Trie // Trie being populated with nodes + + tasks [][]byte // Items queued up for retrieval + lock sync.Mutex // Lock protecting the task queue - to *trieOrchestrator // Orchestrate concurrent fetching of a single trie + wake chan struct{} // Wake channel if a new task is scheduled + stop chan struct{} // Channel to interrupt processing + term chan struct{} // Channel to signal interruption + copy chan chan Trie // Channel to request a copy of the current trie seen map[string]struct{} // Tracks the entries already loaded dups int // Number of duplicate preload tasks used [][]byte // Tracks the entries used in the end + + pool *subfetcherPool } // newSubfetcher creates a goroutine to prefetch state items belonging to a // particular root hash. -func newSubfetcher(p *triePrefetcher, owner common.Hash, root common.Hash, addr common.Address) *subfetcher { +func newSubfetcher(db Database, state common.Hash, owner common.Hash, root common.Hash, addr common.Address, opts ...PrefetcherOption) *subfetcher { sf := &subfetcher{ - p: p, - db: p.db, - state: p.root, + db: db, + state: state, owner: owner, root: root, addr: addr, + wake: make(chan struct{}, 1), + stop: make(chan struct{}), + term: make(chan struct{}), + copy: make(chan chan Trie), seen: make(map[string]struct{}), } - sf.to = newTrieOrchestrator(sf) - if sf.to != nil { - go sf.to.processTasks() - } - // We return [sf] here to ensure we don't try to re-create if - // we aren't able to setup a [newTrieOrchestrator] the first time. + options.As[prefetcherConfig](opts...).applyTo(sf) + go sf.loop() return sf } // schedule adds a batch of trie keys to the queue to prefetch. -// This should never block, so an array is used instead of a channel. -// -// This is not thread-safe. func (sf *subfetcher) schedule(keys [][]byte) { // Append the tasks to the current queue - tasks := make([][]byte, 0, len(keys)) - for _, key := range keys { - // Check if keys already seen - sk := string(key) - if _, ok := sf.seen[sk]; ok { - sf.dups++ - continue - } - sf.seen[sk] = struct{}{} - tasks = append(tasks, key) - } + sf.lock.Lock() + sf.tasks = append(sf.tasks, keys...) + sf.lock.Unlock() - // After counting keys, exit if they can't be prefetched - if sf.to == nil { - return + // Notify the prefetcher, it's fine if it's already terminated + select { + case sf.wake <- struct{}{}: + default: } - - // Add tasks to queue for prefetching - sf.to.enqueueTasks(tasks) } // peek tries to retrieve a deep copy of the fetcher's trie in whatever form it // is currently. func (sf *subfetcher) peek() Trie { - if sf.to == nil { - return nil - } - return sf.to.copyBase() -} + ch := make(chan Trie) + select { + case sf.copy <- ch: + // Subfetcher still alive, return copy from it + return <-ch -// wait must only be called if [triePrefetcher] has not been closed. If this happens, -// workers will not finish. -func (sf *subfetcher) wait() { - if sf.to == nil { - // Unable to open trie - return + case <-sf.term: + // Subfetcher already terminated, return a copy directly + if sf.trie == nil { + return nil + } + return sf.db.CopyTrie(sf.trie) } - sf.to.wait() } +// abort interrupts the subfetcher immediately. It is safe to call abort multiple +// times but it is not thread safe. func (sf *subfetcher) abort() { - if sf.to == nil { - // Unable to open trie - return - } - sf.to.abort() -} - -func (sf *subfetcher) skips() int { - if sf.to == nil { - // Unable to open trie - return 0 - } - return sf.to.skipCount() -} - -func (sf *subfetcher) copies() int { - if sf.to == nil { - // Unable to open trie - return 0 + select { + case <-sf.stop: + default: + close(sf.stop) } - return sf.to.copies + <-sf.term } -// trieOrchestrator is not thread-safe. -type trieOrchestrator struct { - sf *subfetcher - - // base is an unmodified Trie we keep for - // creating copies for each worker goroutine. - // - // We care more about quick copies than good copies - // because most (if not all) of the nodes that will be populated - // in the copy will come from the underlying triedb cache. Ones - // that don't come from this cache probably had to be fetched - // from disk anyways. - base Trie - baseLock sync.Mutex - - tasksAllowed bool - skips int // number of tasks skipped - pendingTasks [][]byte - taskLock sync.Mutex - - processingTasks sync.WaitGroup - - wake chan struct{} - stop chan struct{} - stopOnce sync.Once - loopTerm chan struct{} - - copies int - copyChan chan Trie - copySpawner chan struct{} -} +// loop waits for new tasks to be scheduled and keeps loading them until it runs +// out of tasks or its underlying trie is retrieved for committing. +func (sf *subfetcher) loop() { + // No matter how the loop stops, signal anyone waiting that it's terminated + defer func() { + sf.pool.wait() + close(sf.term) + }() -func newTrieOrchestrator(sf *subfetcher) *trieOrchestrator { // Start by opening the trie and stop processing if it fails - var ( - base Trie - err error - ) if sf.owner == (common.Hash{}) { - base, err = sf.db.OpenTrie(sf.root) + trie, err := sf.db.OpenTrie(sf.root) if err != nil { log.Warn("Trie prefetcher failed opening trie", "root", sf.root, "err", err) - return nil + return } + sf.trie = trie } else { // The trie argument can be nil as verkle doesn't support prefetching // yet. TODO FIX IT(rjl493456442), otherwise code will panic here. - base, err = sf.db.OpenStorageTrie(sf.state, sf.addr, sf.root, nil) + trie, err := sf.db.OpenStorageTrie(sf.state, sf.addr, sf.root, nil) if err != nil { log.Warn("Trie prefetcher failed opening trie", "root", sf.root, "err", err) - return nil + return } + sf.trie = trie } + // Trie opened successfully, keep prefetching items + for { + select { + case <-sf.wake: + // Subfetcher was woken up, retrieve any tasks to avoid spinning the lock + sf.lock.Lock() + tasks := sf.tasks + sf.tasks = nil + sf.lock.Unlock() + + // Prefetch any tasks until the loop is interrupted + for _, task := range tasks { + select { + case ch := <-sf.copy: + // Somebody wants a copy of the current trie, grant them + ch <- sf.db.CopyTrie(sf.trie) + + default: + // No termination request yet, prefetch the next entry + if _, ok := sf.seen[string(task)]; ok { + sf.dups++ + } else { + if len(task) == common.AddressLength { + sf.pool.GetAccount(common.BytesToAddress(task)) + } else { + sf.pool.GetStorage(sf.addr, task) + } + sf.seen[string(task)] = struct{}{} + } + } + } - // Instantiate trieOrchestrator - to := &trieOrchestrator{ - sf: sf, - base: base, - - tasksAllowed: true, - wake: make(chan struct{}, 1), - stop: make(chan struct{}), - loopTerm: make(chan struct{}), - - copyChan: make(chan Trie, sf.p.maxConcurrency), - copySpawner: make(chan struct{}, sf.p.maxConcurrency), - } - - // Create initial trie copy - to.copies++ - to.copySpawner <- struct{}{} - to.copyChan <- to.copyBase() - return to -} - -func (to *trieOrchestrator) copyBase() Trie { - to.baseLock.Lock() - defer to.baseLock.Unlock() - - return to.sf.db.CopyTrie(to.base) -} - -func (to *trieOrchestrator) skipCount() int { - to.taskLock.Lock() - defer to.taskLock.Unlock() - - return to.skips -} - -func (to *trieOrchestrator) enqueueTasks(tasks [][]byte) { - to.taskLock.Lock() - defer to.taskLock.Unlock() - - if len(tasks) == 0 { - return - } - - // Add tasks to [pendingTasks] - if !to.tasksAllowed { - to.skips += len(tasks) - return - } - to.processingTasks.Add(len(tasks)) - to.pendingTasks = append(to.pendingTasks, tasks...) - - // Wake up processor - select { - case to.wake <- struct{}{}: - default: - } -} - -func (to *trieOrchestrator) handleStop(remaining int) { - to.taskLock.Lock() - to.skips += remaining - to.taskLock.Unlock() - to.processingTasks.Add(-remaining) -} + case ch := <-sf.copy: + // Somebody wants a copy of the current trie, grant them + ch <- sf.db.CopyTrie(sf.trie) -func (to *trieOrchestrator) processTasks() { - defer close(to.loopTerm) + case <-sf.stop: + //libevm:start + // + // This is copied, with alteration, from ethereum/go-ethereum#29519 + // and can be deleted once we update to include that change. - for { - // Determine if we should process or exit - select { - case <-to.wake: - case <-to.stop: - return - } + // Termination is requested, abort if no more tasks are pending. If + // there are some, exhaust them first. + sf.lock.Lock() + done := len(sf.tasks) == 0 + sf.lock.Unlock() - // Get current tasks - to.taskLock.Lock() - tasks := to.pendingTasks - to.pendingTasks = nil - to.taskLock.Unlock() - - // Enqueue more work as soon as trie copies are available - lt := len(tasks) - for i := 0; i < lt; i++ { - // Try to stop as soon as possible, if channel is closed - remaining := lt - i - select { - case <-to.stop: - to.handleStop(remaining) + if done { return - default: } - // Try to create to get an active copy first (select is non-deterministic, - // so we may end up creating a new copy when we don't need to) - var t Trie select { - case t = <-to.copyChan: + case sf.wake <- struct{}{}: default: - // Wait for an available copy or create one, if we weren't - // able to get a previously created copy - select { - case <-to.stop: - to.handleStop(remaining) - return - case t = <-to.copyChan: - case to.copySpawner <- struct{}{}: - to.copies++ - t = to.copyBase() - } - } - - // Enqueue work, unless stopped. - fTask := tasks[i] - f := func() { - // Perform task - var err error - if len(fTask) == common.AddressLength { - _, err = t.GetAccount(common.BytesToAddress(fTask)) - } else { - _, err = t.GetStorage(to.sf.addr, fTask) - } - if err != nil { - log.Error("Trie prefetcher failed fetching", "root", to.sf.root, "err", err) - } - to.processingTasks.Done() - - // Return copy when we are done with it, so someone else can use it - // - // channel is buffered and will not block - to.copyChan <- t } - - // Enqueue task for processing (may spawn new goroutine - // if not at [maxConcurrency]) - // - // If workers are stopped before calling [Execute], this function may - // panic. - to.sf.p.workers.Execute(f) + //libevm:end } } } - -func (to *trieOrchestrator) stopAcceptingTasks() { - to.taskLock.Lock() - defer to.taskLock.Unlock() - - if !to.tasksAllowed { - return - } - to.tasksAllowed = false - - // We don't clear [to.pendingTasks] here because - // it will be faster to prefetch them even though we - // are still waiting. -} - -// wait stops accepting new tasks and waits for ongoing tasks to complete. If -// wait is called, it is not necessary to call [abort]. -// -// It is safe to call wait multiple times. -func (to *trieOrchestrator) wait() { - // Prevent more tasks from being enqueued - to.stopAcceptingTasks() - - // Wait for processing tasks to complete - to.processingTasks.Wait() - - // Stop orchestrator loop - to.stopOnce.Do(func() { - close(to.stop) - }) - <-to.loopTerm -} - -// abort stops any ongoing tasks and shuts down the orchestrator loop. If abort -// is called, it is not necessary to call [wait]. -// -// It is safe to call abort multiple times. -func (to *trieOrchestrator) abort() { - // Prevent more tasks from being enqueued - to.stopAcceptingTasks() - - // Stop orchestrator loop - to.stopOnce.Do(func() { - close(to.stop) - }) - <-to.loopTerm - - // Capture any dangling pending tasks (processTasks - // may exit before enqueing all pendingTasks) - to.taskLock.Lock() - pendingCount := len(to.pendingTasks) - to.skips += pendingCount - to.pendingTasks = nil - to.taskLock.Unlock() - to.processingTasks.Add(-pendingCount) - - // Wait for processing tasks to complete - to.processingTasks.Wait() -} diff --git a/core/state/trie_prefetcher.libevm.go b/core/state/trie_prefetcher.libevm.go new file mode 100644 index 0000000000..7a2a35ddc8 --- /dev/null +++ b/core/state/trie_prefetcher.libevm.go @@ -0,0 +1,126 @@ +// Copyright 2024 the libevm authors. +// +// The libevm additions to go-ethereum are free software: you can redistribute +// them and/or modify them under the terms of the GNU Lesser General Public License +// as published by the Free Software Foundation, either version 3 of the License, +// or (at your option) any later version. +// +// The libevm additions are distributed in the hope that they will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser +// General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see +// . + +package state + +import ( + "github.com/ava-labs/coreth/libevm/options" + "github.com/ava-labs/coreth/libevm/sync" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" +) + +// A PrefetcherOption configures behaviour of trie prefetching. +type PrefetcherOption = options.Option[prefetcherConfig] + +type prefetcherConfig struct { + newWorkers func() WorkerPool +} + +// A WorkerPool executes functions asynchronously. Done() is called to signal +// that the pool is no longer needed and that Execute() is guaranteed to not be +// called again. +type WorkerPool interface { + Execute(func()) + Done() +} + +// WithWorkerPools configures trie prefetching to execute asynchronously. The +// provided constructor is called once for each trie being fetched but it MAY +// return the same pool. +func WithWorkerPools(ctor func() WorkerPool) PrefetcherOption { + return options.Func[prefetcherConfig](func(c *prefetcherConfig) { + c.newWorkers = ctor + }) +} + +type subfetcherPool struct { + workers WorkerPool + tries sync.Pool[Trie] + wg sync.WaitGroup +} + +// applyTo configures the [subfetcher] to use a [WorkerPool] if one was provided +// with a [PrefetcherOption]. +func (c *prefetcherConfig) applyTo(sf *subfetcher) { + sf.pool = &subfetcherPool{ + tries: sync.Pool[Trie]{ + // Although the workers may be shared between all subfetchers, each + // MUST have its own Trie pool. + New: func() Trie { + return sf.db.CopyTrie(sf.trie) + }, + }, + } + if c.newWorkers != nil { + sf.pool.workers = c.newWorkers() + } +} + +// releaseWorkerPools calls Done() on all [WorkerPool]s. This MUST only be +// called after [subfetcher.abort] returns on ALL fetchers as a pool is allowed +// to be shared between them. This is because we guarantee in the public API +// that no further calls will be made to Execute() after a call to Done(). +func (p *triePrefetcher) releaseWorkerPools() { + for _, f := range p.fetchers { + if w := f.pool.workers; w != nil { + w.Done() + } + } +} + +func (p *subfetcherPool) wait() { + p.wg.Wait() +} + +// execute runs the provided function with a copy of the subfetcher's Trie. +// Copies are stored in a [sync.Pool] to reduce creation overhead. If p was +// configured with a [WorkerPool] then it is used for function execution, +// otherwise `fn` is just called directly. +func (p *subfetcherPool) execute(fn func(Trie)) { + p.wg.Add(1) + do := func() { + t := p.tries.Get() + fn(t) + p.tries.Put(t) + p.wg.Done() + } + + if w := p.workers; w != nil { + w.Execute(do) + } else { + do() + } +} + +// GetAccount optimistically pre-fetches an account, dropping the returned value +// and logging errors. See [subfetcherPool.execute] re worker pools. +func (p *subfetcherPool) GetAccount(addr common.Address) { + p.execute(func(t Trie) { + if _, err := t.GetAccount(addr); err != nil { + log.Error("account prefetching failed", "address", addr, "err", err) + } + }) +} + +// GetStorage is the storage equivalent of [subfetcherPool.GetAccount]. +func (p *subfetcherPool) GetStorage(addr common.Address, key []byte) { + p.execute(func(t Trie) { + if _, err := t.GetStorage(addr, key); err != nil { + log.Error("storage prefetching failed", "address", addr, "key", key, "err", err) + } + }) +} diff --git a/core/state/trie_prefetcher_extra_test.go b/core/state/trie_prefetcher_extra_test.go new file mode 100644 index 0000000000..d768d46a9d --- /dev/null +++ b/core/state/trie_prefetcher_extra_test.go @@ -0,0 +1,189 @@ +// (c) 2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package state + +import ( + "crypto/rand" + "encoding/binary" + "fmt" + "os" + "path" + "strconv" + "testing" + + "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/coreth/core/rawdb" + "github.com/ava-labs/coreth/core/state/snapshot" + "github.com/ava-labs/coreth/core/types" + "github.com/ava-labs/coreth/metrics" + "github.com/ava-labs/coreth/triedb" + "github.com/ava-labs/coreth/triedb/hashdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/stretchr/testify/require" +) + +const namespace = "chain" + +// BenchmarkPrefetcherDatabase benchmarks the performance of the trie +// prefetcher. By default, a state with 100k storage keys is created and stored +// in a temporary directory. Setting the TEST_DB_KVS and TEST_DB_DIR environment +// variables modifies the defaults. The benchmark measures the time to update +// the trie after 100, 200, and 500 storage slot updates per iteration, +// simulating a block with that number of storage slot updates. For performance +// reasons, when making changes involving the trie prefetcher, this benchmark +// should be run against a state including around 100m storage entries. +func BenchmarkPrefetcherDatabase(b *testing.B) { + require := require.New(b) + + dir := b.TempDir() + if env := os.Getenv("TEST_DB_DIR"); env != "" { + dir = env + } + wantKVs := 100_000 + if env := os.Getenv("TEST_DB_KVS"); env != "" { + var err error + wantKVs, err = strconv.Atoi(env) + require.NoError(err) + } + + levelDB, err := rawdb.NewLevelDBDatabase(path.Join(dir, "level.db"), 0, 0, "", false) + require.NoError(err) + + root := types.EmptyRootHash + count := uint64(0) + block := uint64(0) + + rootKey := []byte("root") + countKey := []byte("count") + blockKey := []byte("block") + got, err := levelDB.Get(rootKey) + if err == nil { // on success + root = common.BytesToHash(got) + } + got, err = levelDB.Get(countKey) + if err == nil { // on success + count = binary.BigEndian.Uint64(got) + } + got, err = levelDB.Get(blockKey) + if err == nil { // on success + block = binary.BigEndian.Uint64(got) + } + + // Make a trie on the levelDB + address1 := common.Address{42} + address2 := common.Address{43} + addBlock := func(db Database, snaps *snapshot.Tree, kvsPerBlock int, prefetchers int) { + _, root, err = addKVs(db, snaps, address1, address2, root, block, kvsPerBlock, prefetchers) + require.NoError(err) + count += uint64(kvsPerBlock) + block++ + } + + lastCommit := block + commit := func(levelDB ethdb.Database, snaps *snapshot.Tree, db Database) { + require.NoError(db.TrieDB().Commit(root, false)) + + for i := lastCommit + 1; i <= block; i++ { + require.NoError(snaps.Flatten(fakeHash(i))) + } + lastCommit = block + + // update the tracking keys + require.NoError(levelDB.Put(rootKey, root.Bytes())) + require.NoError(database.PutUInt64(levelDB, blockKey, block)) + require.NoError(database.PutUInt64(levelDB, countKey, count)) + } + + tdbConfig := &triedb.Config{ + HashDB: &hashdb.Config{ + CleanCacheSize: 3 * 1024 * 1024 * 1024, + }, + } + db := NewDatabaseWithConfig(levelDB, tdbConfig) + snaps := snapshot.NewTestTree(levelDB, fakeHash(block), root) + for count < uint64(wantKVs) { + previous := root + addBlock(db, snaps, 100_000, 0) // Note this updates root and count + b.Logf("Root: %v, kvs: %d, block: %d", root, count, block) + + // Commit every 10 blocks or on the last iteration + if block%10 == 0 || count >= uint64(wantKVs) { + commit(levelDB, snaps, db) + b.Logf("Root: %v, kvs: %d, block: %d (committed)", root, count, block) + } + if previous != root { + require.NoError(db.TrieDB().Dereference(previous)) + } else { + b.Fatal("root did not change") + } + } + require.NoError(levelDB.Close()) + b.Logf("Starting benchmarks") + b.Logf("Root: %v, kvs: %d, block: %d", root, count, block) + for _, updates := range []int{100, 200, 500} { + for _, prefetchers := range []int{0, 1, 4, 16} { + b.Run(fmt.Sprintf("updates_%d_prefetchers_%d", updates, prefetchers), func(b *testing.B) { + startRoot, startBlock, startCount := root, block, count + defer func() { root, block, count = startRoot, startBlock, startCount }() + + levelDB, err := rawdb.NewLevelDBDatabase(path.Join(dir, "level.db"), 0, 0, "", false) + require.NoError(err) + snaps := snapshot.NewTestTree(levelDB, fakeHash(block), root) + db := NewDatabaseWithConfig(levelDB, tdbConfig) + getMetric := func(metric string) int64 { + meter := metrics.GetOrRegisterMeter(triePrefetchMetricsPrefix+namespace+"/storage/"+metric, nil) + return meter.Snapshot().Count() + } + startLoads := getMetric("load") + for i := 0; i < b.N; i++ { + addBlock(db, snaps, updates, prefetchers) + } + require.NoError(levelDB.Close()) + b.ReportMetric(float64(getMetric("load")-startLoads)/float64(b.N), "loads") + }) + } + } +} + +func fakeHash(block uint64) common.Hash { + return common.BytesToHash(binary.BigEndian.AppendUint64(nil, block)) +} + +// addKVs adds count random key-value pairs to the state trie of address1 and +// address2 (each count/2) and returns the new state db and root. +func addKVs( + db Database, snaps *snapshot.Tree, + address1, address2 common.Address, root common.Hash, block uint64, + count int, prefetchers int, +) (*StateDB, common.Hash, error) { + snap := snaps.Snapshot(root) + if snap == nil { + return nil, common.Hash{}, fmt.Errorf("snapshot not found") + } + statedb, err := NewWithSnapshot(root, db, snap) + if err != nil { + return nil, common.Hash{}, fmt.Errorf("creating state with snapshot: %w", err) + } + if prefetchers > 0 { + statedb.StartPrefetcher(namespace, WithConcurrentWorkers(prefetchers)) + defer statedb.StopPrefetcher() + } + for _, address := range []common.Address{address1, address2} { + statedb.SetNonce(address, 1) + for i := 0; i < count/2; i++ { + key := make([]byte, 32) + value := make([]byte, 32) + rand.Read(key) + rand.Read(value) + + statedb.SetState(address, common.BytesToHash(key), common.BytesToHash(value)) + } + } + root, err = statedb.CommitWithSnap(block+1, true, snaps, fakeHash(block+1), fakeHash(block)) + if err != nil { + return nil, common.Hash{}, fmt.Errorf("committing with snap: %w", err) + } + return statedb, root, nil +} diff --git a/core/state/trie_prefetcher_test.go b/core/state/trie_prefetcher_test.go index 4f70b49179..4c1ff686e3 100644 --- a/core/state/trie_prefetcher_test.go +++ b/core/state/trie_prefetcher_test.go @@ -59,7 +59,7 @@ func filledStateDB() *StateDB { func TestCopyAndClose(t *testing.T) { db := filledStateDB() - prefetcher := newTriePrefetcher(db.db, db.originalRoot, "", maxConcurrency) + prefetcher := newTriePrefetcher(db.db, db.originalRoot, "", WithConcurrentWorkers(maxConcurrency)) skey := common.HexToHash("aaa") prefetcher.prefetch(common.Hash{}, db.originalRoot, common.Address{}, [][]byte{skey.Bytes()}) prefetcher.prefetch(common.Hash{}, db.originalRoot, common.Address{}, [][]byte{skey.Bytes()}) @@ -84,7 +84,7 @@ func TestCopyAndClose(t *testing.T) { func TestUseAfterClose(t *testing.T) { db := filledStateDB() - prefetcher := newTriePrefetcher(db.db, db.originalRoot, "", maxConcurrency) + prefetcher := newTriePrefetcher(db.db, db.originalRoot, "", WithConcurrentWorkers(maxConcurrency)) skey := common.HexToHash("aaa") prefetcher.prefetch(common.Hash{}, db.originalRoot, common.Address{}, [][]byte{skey.Bytes()}) a := prefetcher.trie(common.Hash{}, db.originalRoot) @@ -100,7 +100,7 @@ func TestUseAfterClose(t *testing.T) { func TestCopyClose(t *testing.T) { db := filledStateDB() - prefetcher := newTriePrefetcher(db.db, db.originalRoot, "", maxConcurrency) + prefetcher := newTriePrefetcher(db.db, db.originalRoot, "", WithConcurrentWorkers(maxConcurrency)) skey := common.HexToHash("aaa") prefetcher.prefetch(common.Hash{}, db.originalRoot, common.Address{}, [][]byte{skey.Bytes()}) cpy := prefetcher.copy() diff --git a/libevm/options/options.go b/libevm/options/options.go new file mode 100644 index 0000000000..af7bc751a9 --- /dev/null +++ b/libevm/options/options.go @@ -0,0 +1,42 @@ +// Copyright 2024 the libevm authors. +// +// The libevm additions to go-ethereum are free software: you can redistribute +// them and/or modify them under the terms of the GNU Lesser General Public License +// as published by the Free Software Foundation, either version 3 of the License, +// or (at your option) any later version. +// +// The libevm additions are distributed in the hope that they will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser +// General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see +// . + +// Package options provides a generic mechanism for defining configuration of +// arbitrary types. +package options + +// An Option configures values of arbitrary type. +type Option[T any] interface { + Configure(*T) +} + +// As applies Options to a zero-value T, which it then returns. +func As[T any](opts ...Option[T]) *T { + var t T + for _, o := range opts { + o.Configure(&t) + } + return &t +} + +// A Func converts a function into an [Option], using itself as the Configure +// method. +type Func[T any] func(*T) + +var _ Option[struct{}] = Func[struct{}](nil) + +// Configure implements the [Option] interface. +func (f Func[T]) Configure(t *T) { f(t) } diff --git a/libevm/sync/sync.go b/libevm/sync/sync.go new file mode 100644 index 0000000000..e280f4bbe9 --- /dev/null +++ b/libevm/sync/sync.go @@ -0,0 +1,52 @@ +// Copyright 2024 the coreth authors. +// +// The libevm additions to go-ethereum are free software: you can redistribute +// them and/or modify them under the terms of the GNU Lesser General Public License +// as published by the Free Software Foundation, either version 3 of the License, +// or (at your option) any later version. +// +// The libevm additions are distributed in the hope that they will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser +// General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see +// . + +// Package sync extends the standard library's sync package. +package sync + +import "sync" + +// Aliases of stdlib sync's types to avoid having to import it alongside this +// package. +type ( + Cond = sync.Cond + Locker = sync.Locker + Map = sync.Map + Mutex = sync.Mutex + Once = sync.Once + RWMutex = sync.RWMutex + WaitGroup = sync.WaitGroup +) + +// A Pool is a type-safe wrapper around [sync.Pool]. +type Pool[T any] struct { + New func() T + pool sync.Pool + once Once +} + +// Get is equivalent to [sync.Pool.Get]. +func (p *Pool[T]) Get() T { + p.once.Do(func() { // Do() guarantees at least once, not just only once + p.pool.New = func() any { return p.New() } + }) + return p.pool.Get().(T) //nolint:forcetypeassert +} + +// Put is equivalent to [sync.Pool.Put]. +func (p *Pool[T]) Put(t T) { + p.pool.Put(t) +} diff --git a/miner/worker.go b/miner/worker.go index ec2bd60fca..96ab02c23d 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -264,14 +264,15 @@ func (w *worker) commitNewWork(predicateContext *precompileconfig.PredicateConte } func (w *worker) createCurrentEnvironment(predicateContext *precompileconfig.PredicateContext, parent *types.Header, header *types.Header, tstart time.Time) (*environment, error) { - state, err := w.chain.StateAt(parent.Root) + currentState, err := w.chain.StateAt(parent.Root) if err != nil { return nil, err } - state.StartPrefetcher("miner", w.eth.BlockChain().CacheConfig().TriePrefetcherParallelism) + numPrefetchers := w.chain.CacheConfig().TriePrefetcherParallelism + currentState.StartPrefetcher("miner", state.WithConcurrentWorkers(numPrefetchers)) return &environment{ signer: types.MakeSigner(w.chainConfig, header.Number, header.Time), - state: state, + state: currentState, parent: parent, header: header, tcount: 0, From 0fe743ab6474ed23b758159340c9a6c8f1ad4e11 Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Mon, 6 Jan 2025 16:34:30 +0300 Subject: [PATCH 16/69] bump avago 902377d447ba (#732) --- go.mod | 7 ++++--- go.sum | 8 ++++++++ scripts/versions.sh | 2 +- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 5d184fd9e5..a4acd1705f 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.22.8 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.12.2-0.20241224181600-fade5be3051d + github.com/ava-labs/avalanchego v1.12.2-0.20250106102004-902377d447ba github.com/cespare/cp v0.1.0 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 @@ -37,7 +37,7 @@ require ( github.com/tyler-smith/go-bip39 v1.1.0 github.com/urfave/cli/v2 v2.25.7 go.uber.org/goleak v1.3.0 - go.uber.org/mock v0.4.0 + go.uber.org/mock v0.5.0 golang.org/x/crypto v0.31.0 golang.org/x/exp v0.0.0-20231127185646-65229373498e golang.org/x/sync v0.10.0 @@ -120,7 +120,8 @@ require ( go.opentelemetry.io/proto/otlp v1.0.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.26.0 // indirect - golang.org/x/net v0.28.0 // indirect + golang.org/x/mod v0.18.0 // indirect + golang.org/x/net v0.33.0 // indirect golang.org/x/term v0.27.0 // indirect gonum.org/v1/gonum v0.11.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20240604185151-ef581f913117 // indirect diff --git a/go.sum b/go.sum index 40a7c0d3cf..4bf0d64d42 100644 --- a/go.sum +++ b/go.sum @@ -58,6 +58,8 @@ github.com/ava-labs/avalanchego v1.12.2-0.20241224161435-3998475d671d h1:QCtjS4A github.com/ava-labs/avalanchego v1.12.2-0.20241224161435-3998475d671d/go.mod h1:cDoT0Hq3P+/XfCyVvzrBj66yoid2I5LnMuj7LIkap+o= github.com/ava-labs/avalanchego v1.12.2-0.20241224181600-fade5be3051d h1:iPlsqC9pIy4emCo8wyI/VmVmfljpzmw58ZqahVdcehI= github.com/ava-labs/avalanchego v1.12.2-0.20241224181600-fade5be3051d/go.mod h1:dKawab3nXqwI7ZcOFatTOv//l1V0t8MRBnhXoOqbN4E= +github.com/ava-labs/avalanchego v1.12.2-0.20250106102004-902377d447ba h1:7t2ORGM53sqdsczNZGFQIK99of9yeetCld90keJ47Os= +github.com/ava-labs/avalanchego v1.12.2-0.20250106102004-902377d447ba/go.mod h1:oK/C7ZGo5cAEayBKBoawh2EpOo3E9gD1rpd9NAM0RkQ= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= @@ -586,6 +588,8 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU= go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= +go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU= +go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo= @@ -643,6 +647,8 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0= +golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -689,6 +695,8 @@ golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE= golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg= +golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= diff --git a/scripts/versions.sh b/scripts/versions.sh index 2018ff1398..ba63c1148c 100644 --- a/scripts/versions.sh +++ b/scripts/versions.sh @@ -6,4 +6,4 @@ set -euo pipefail # Don't export them as they're used in the context of other calls -AVALANCHE_VERSION=${AVALANCHE_VERSION:-'fade5be3051d'} +AVALANCHE_VERSION=${AVALANCHE_VERSION:-'902377d447ba'} From b16fc67e21d07b9b3a934ce3fe3ba49bc3bad310 Mon Sep 17 00:00:00 2001 From: Quentin McGaw Date: Tue, 7 Jan 2025 13:30:33 +0100 Subject: [PATCH 17/69] chore(scripts): simplify mocks generation (#721) * header.yml is missing so removing ineffective go-license * Remove unneeded source constants * Remove unneeded source versions * Use go generate commands to generate mocks * Remove the need to install mockgen in the script * Add mock-up-to-date step to test CI workflow * Remove all mocks before generating them in CI * Add generate command for non-tracked mock (Note using source mode was compulsory due to CGO) * Use bash shell for mock check step * Remove script mock.gen.sh * docs(contributing): add mocks section * mockgen version used is the one defined in go.mod - requires a `tools.go` blank importing golang.org/x/tools/imports in order to have the `golang.org/x/tools` dependency satisfied for mockgen v0.4 - less future deltas when upgrading mockgen * ci: use more precise go generate regex * Add `git add --intent-to-add --all` to detect untracked files * Add copyright notices --- .github/CONTRIBUTING.md | 33 +++++++++++ .github/workflows/ci.yml | 7 +++ go.mod | 3 +- go.sum | 14 ++--- precompile/contract/mocks.go | 45 ++++++++------- precompile/contract/mocks_generate_test.go | 6 ++ precompile/precompileconfig/mocks.go | 38 +++++++------ .../precompileconfig/mocks_generate_test.go | 6 ++ scripts/mock.gen.sh | 44 --------------- scripts/mocks.mockgen.txt | 2 - tools.go | 8 +++ warp/aggregator/mock_signature_getter.go | 55 +++++++++++++++++-- warp/aggregator/mocks_generate_test.go | 6 ++ 13 files changed, 167 insertions(+), 100 deletions(-) create mode 100644 precompile/contract/mocks_generate_test.go create mode 100644 precompile/precompileconfig/mocks_generate_test.go delete mode 100755 scripts/mock.gen.sh delete mode 100644 scripts/mocks.mockgen.txt create mode 100644 tools.go create mode 100644 warp/aggregator/mocks_generate_test.go diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 87c79fcfe2..9e89d2d0da 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -33,3 +33,36 @@ Please make sure your contributions adhere to our coding guidelines: Before you submit a feature request, please check and make sure that it isn't possible through some other means. +## Mocks + +Mocks are auto-generated using [mockgen](https://pkg.go.dev/go.uber.org/mock/mockgen) and `//go:generate` commands in the code. + +* To **re-generate all mocks**, use the command below from the root of the project: + + ```sh + go generate -run "go.uber.org/mock/mockgen" ./... + ``` + +* To **add** an interface that needs a corresponding mock generated: + * if the file `mocks_generate_test.go` exists in the package where the interface is located, either: + * modify its `//go:generate go run go.uber.org/mock/mockgen` to generate a mock for your interface (preferred); or + * add another `//go:generate go run go.uber.org/mock/mockgen` to generate a mock for your interface according to specific mock generation settings + * if the file `mocks_generate_test.go` does not exist in the package where the interface is located, create it with content (adapt as needed): + + ```go + // Copyright (C) 2025-2025, Ava Labs, Inc. All rights reserved. + // See the file LICENSE for licensing terms. + + package mypackage + + //go:generate go run go.uber.org/mock/mockgen -package=${GOPACKAGE} -destination=mocks_test.go . YourInterface + ``` + + Notes: + 1. Ideally generate all mocks to `mocks_test.go` for the package you need to use the mocks for and do not export mocks to other packages. This reduces package dependencies, reduces production code pollution and forces to have locally defined narrow interfaces. + 1. Prefer using reflect mode to generate mocks than source mode, unless you need a mock for an unexported interface, which should be rare. +* To **remove** an interface from having a corresponding mock generated: + 1. Edit the `mocks_generate_test.go` file in the directory where the interface is defined + 1. If the `//go:generate` mockgen command line: + * generates a mock file for multiple interfaces, remove your interface from the line + * generates a mock file only for the interface, remove the entire line. If the file is empty, remove `mocks_generate_test.go` as well. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 553c2761d7..48056c04f2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,6 +84,13 @@ jobs: run: echo "TIMEOUT=1200s" >> "$GITHUB_ENV" - run: go mod download shell: bash + - name: Mocks are up to date + shell: bash + run: | + grep -lr -E '^// Code generated by MockGen\. DO NOT EDIT\.$' . | xargs -r rm + go generate -run "go.uber.org/mock/mockgen" ./... + git add --intent-to-add --all + git diff --exit-code - run: ./scripts/build.sh evm shell: bash - run: ./scripts/build_test.sh diff --git a/go.mod b/go.mod index a4acd1705f..63146cd8d2 100644 --- a/go.mod +++ b/go.mod @@ -44,6 +44,7 @@ require ( golang.org/x/sys v0.28.0 golang.org/x/text v0.21.0 golang.org/x/time v0.3.0 + golang.org/x/tools v0.22.0 google.golang.org/protobuf v1.34.2 gopkg.in/natefinch/lumberjack.v2 v2.0.0 ) @@ -120,7 +121,7 @@ require ( go.opentelemetry.io/proto/otlp v1.0.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.26.0 // indirect - golang.org/x/mod v0.18.0 // indirect + golang.org/x/mod v0.22.0 // indirect golang.org/x/net v0.33.0 // indirect golang.org/x/term v0.27.0 // indirect gonum.org/v1/gonum v0.11.0 // indirect diff --git a/go.sum b/go.sum index 4bf0d64d42..9391e7bb79 100644 --- a/go.sum +++ b/go.sum @@ -54,10 +54,6 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/avalanchego v1.12.2-0.20241224161435-3998475d671d h1:QCtjS4ANcNfCdL6Z2sKpanDVJNt1MU0bUyVdW0g5zuU= -github.com/ava-labs/avalanchego v1.12.2-0.20241224161435-3998475d671d/go.mod h1:cDoT0Hq3P+/XfCyVvzrBj66yoid2I5LnMuj7LIkap+o= -github.com/ava-labs/avalanchego v1.12.2-0.20241224181600-fade5be3051d h1:iPlsqC9pIy4emCo8wyI/VmVmfljpzmw58ZqahVdcehI= -github.com/ava-labs/avalanchego v1.12.2-0.20241224181600-fade5be3051d/go.mod h1:dKawab3nXqwI7ZcOFatTOv//l1V0t8MRBnhXoOqbN4E= github.com/ava-labs/avalanchego v1.12.2-0.20250106102004-902377d447ba h1:7t2ORGM53sqdsczNZGFQIK99of9yeetCld90keJ47Os= github.com/ava-labs/avalanchego v1.12.2-0.20250106102004-902377d447ba/go.mod h1:oK/C7ZGo5cAEayBKBoawh2EpOo3E9gD1rpd9NAM0RkQ= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= @@ -586,8 +582,6 @@ go.opentelemetry.io/proto/otlp v1.0.0 h1:T0TX0tmXU8a3CbNXzEKGeU5mIVOdf0oykP+u2lI go.opentelemetry.io/proto/otlp v1.0.0/go.mod h1:Sy6pihPLfYHkr3NkUbEhGHFhINUSI/v80hjKIs5JXpM= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU= -go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU= go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -647,8 +641,8 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0= -golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4= +golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -693,8 +687,6 @@ golang.org/x/net v0.0.0-20211008194852-3b03d305991f/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE= -golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg= golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -865,6 +857,8 @@ golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.22.0 h1:gqSGLZqv+AI9lIQzniJ0nZDRG5GBPsSi+DRNHWNz6yA= +golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/precompile/contract/mocks.go b/precompile/contract/mocks.go index 94bf9c5ba0..546090339f 100644 --- a/precompile/contract/mocks.go +++ b/precompile/contract/mocks.go @@ -3,7 +3,7 @@ // // Generated by this command: // -// mockgen -package=contract -destination=precompile/contract/mocks.go github.com/ava-labs/coreth/precompile/contract BlockContext,AccessibleState,StateDB +// mockgen -package=contract -destination=mocks.go . BlockContext,AccessibleState,StateDB // // Package contract is a generated GoMock package. @@ -24,6 +24,7 @@ import ( type MockBlockContext struct { ctrl *gomock.Controller recorder *MockBlockContextMockRecorder + isgomock struct{} } // MockBlockContextMockRecorder is the mock recorder for MockBlockContext. @@ -44,17 +45,17 @@ func (m *MockBlockContext) EXPECT() *MockBlockContextMockRecorder { } // GetPredicateResults mocks base method. -func (m *MockBlockContext) GetPredicateResults(arg0 common.Hash, arg1 common.Address) []byte { +func (m *MockBlockContext) GetPredicateResults(txHash common.Hash, precompileAddress common.Address) []byte { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPredicateResults", arg0, arg1) + ret := m.ctrl.Call(m, "GetPredicateResults", txHash, precompileAddress) ret0, _ := ret[0].([]byte) return ret0 } // GetPredicateResults indicates an expected call of GetPredicateResults. -func (mr *MockBlockContextMockRecorder) GetPredicateResults(arg0, arg1 any) *gomock.Call { +func (mr *MockBlockContextMockRecorder) GetPredicateResults(txHash, precompileAddress any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPredicateResults", reflect.TypeOf((*MockBlockContext)(nil).GetPredicateResults), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPredicateResults", reflect.TypeOf((*MockBlockContext)(nil).GetPredicateResults), txHash, precompileAddress) } // Number mocks base method. @@ -89,6 +90,7 @@ func (mr *MockBlockContextMockRecorder) Timestamp() *gomock.Call { type MockAccessibleState struct { ctrl *gomock.Controller recorder *MockAccessibleStateMockRecorder + isgomock struct{} } // MockAccessibleStateMockRecorder is the mock recorder for MockAccessibleState. @@ -165,9 +167,9 @@ func (mr *MockAccessibleStateMockRecorder) GetStateDB() *gomock.Call { } // NativeAssetCall mocks base method. -func (m *MockAccessibleState) NativeAssetCall(arg0 common.Address, arg1 []byte, arg2, arg3 uint64, arg4 bool) ([]byte, uint64, error) { +func (m *MockAccessibleState) NativeAssetCall(caller common.Address, input []byte, suppliedGas, gasCost uint64, readOnly bool) ([]byte, uint64, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "NativeAssetCall", arg0, arg1, arg2, arg3, arg4) + ret := m.ctrl.Call(m, "NativeAssetCall", caller, input, suppliedGas, gasCost, readOnly) ret0, _ := ret[0].([]byte) ret1, _ := ret[1].(uint64) ret2, _ := ret[2].(error) @@ -175,15 +177,16 @@ func (m *MockAccessibleState) NativeAssetCall(arg0 common.Address, arg1 []byte, } // NativeAssetCall indicates an expected call of NativeAssetCall. -func (mr *MockAccessibleStateMockRecorder) NativeAssetCall(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { +func (mr *MockAccessibleStateMockRecorder) NativeAssetCall(caller, input, suppliedGas, gasCost, readOnly any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NativeAssetCall", reflect.TypeOf((*MockAccessibleState)(nil).NativeAssetCall), arg0, arg1, arg2, arg3, arg4) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NativeAssetCall", reflect.TypeOf((*MockAccessibleState)(nil).NativeAssetCall), caller, input, suppliedGas, gasCost, readOnly) } // MockStateDB is a mock of StateDB interface. type MockStateDB struct { ctrl *gomock.Controller recorder *MockStateDBMockRecorder + isgomock struct{} } // MockStateDBMockRecorder is the mock recorder for MockStateDB. @@ -216,15 +219,15 @@ func (mr *MockStateDBMockRecorder) AddBalance(arg0, arg1 any) *gomock.Call { } // AddLog mocks base method. -func (m *MockStateDB) AddLog(arg0 common.Address, arg1 []common.Hash, arg2 []byte, arg3 uint64) { +func (m *MockStateDB) AddLog(addr common.Address, topics []common.Hash, data []byte, blockNumber uint64) { m.ctrl.T.Helper() - m.ctrl.Call(m, "AddLog", arg0, arg1, arg2, arg3) + m.ctrl.Call(m, "AddLog", addr, topics, data, blockNumber) } // AddLog indicates an expected call of AddLog. -func (mr *MockStateDBMockRecorder) AddLog(arg0, arg1, arg2, arg3 any) *gomock.Call { +func (mr *MockStateDBMockRecorder) AddLog(addr, topics, data, blockNumber any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddLog", reflect.TypeOf((*MockStateDB)(nil).AddLog), arg0, arg1, arg2, arg3) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddLog", reflect.TypeOf((*MockStateDB)(nil).AddLog), addr, topics, data, blockNumber) } // CreateAccount mocks base method. @@ -311,18 +314,18 @@ func (mr *MockStateDBMockRecorder) GetNonce(arg0 any) *gomock.Call { } // GetPredicateStorageSlots mocks base method. -func (m *MockStateDB) GetPredicateStorageSlots(arg0 common.Address, arg1 int) ([]byte, bool) { +func (m *MockStateDB) GetPredicateStorageSlots(address common.Address, index int) ([]byte, bool) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPredicateStorageSlots", arg0, arg1) + ret := m.ctrl.Call(m, "GetPredicateStorageSlots", address, index) ret0, _ := ret[0].([]byte) ret1, _ := ret[1].(bool) return ret0, ret1 } // GetPredicateStorageSlots indicates an expected call of GetPredicateStorageSlots. -func (mr *MockStateDBMockRecorder) GetPredicateStorageSlots(arg0, arg1 any) *gomock.Call { +func (mr *MockStateDBMockRecorder) GetPredicateStorageSlots(address, index any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPredicateStorageSlots", reflect.TypeOf((*MockStateDB)(nil).GetPredicateStorageSlots), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPredicateStorageSlots", reflect.TypeOf((*MockStateDB)(nil).GetPredicateStorageSlots), address, index) } // GetState mocks base method. @@ -378,15 +381,15 @@ func (mr *MockStateDBMockRecorder) SetNonce(arg0, arg1 any) *gomock.Call { } // SetPredicateStorageSlots mocks base method. -func (m *MockStateDB) SetPredicateStorageSlots(arg0 common.Address, arg1 [][]byte) { +func (m *MockStateDB) SetPredicateStorageSlots(address common.Address, predicates [][]byte) { m.ctrl.T.Helper() - m.ctrl.Call(m, "SetPredicateStorageSlots", arg0, arg1) + m.ctrl.Call(m, "SetPredicateStorageSlots", address, predicates) } // SetPredicateStorageSlots indicates an expected call of SetPredicateStorageSlots. -func (mr *MockStateDBMockRecorder) SetPredicateStorageSlots(arg0, arg1 any) *gomock.Call { +func (mr *MockStateDBMockRecorder) SetPredicateStorageSlots(address, predicates any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPredicateStorageSlots", reflect.TypeOf((*MockStateDB)(nil).SetPredicateStorageSlots), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPredicateStorageSlots", reflect.TypeOf((*MockStateDB)(nil).SetPredicateStorageSlots), address, predicates) } // SetState mocks base method. diff --git a/precompile/contract/mocks_generate_test.go b/precompile/contract/mocks_generate_test.go new file mode 100644 index 0000000000..ab422832da --- /dev/null +++ b/precompile/contract/mocks_generate_test.go @@ -0,0 +1,6 @@ +// Copyright (C) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package contract + +//go:generate go run go.uber.org/mock/mockgen -package=$GOPACKAGE -destination=mocks.go . BlockContext,AccessibleState,StateDB diff --git a/precompile/precompileconfig/mocks.go b/precompile/precompileconfig/mocks.go index 4be7f046ec..cba1ca13a3 100644 --- a/precompile/precompileconfig/mocks.go +++ b/precompile/precompileconfig/mocks.go @@ -3,7 +3,7 @@ // // Generated by this command: // -// mockgen -package=precompileconfig -destination=precompile/precompileconfig/mocks.go github.com/ava-labs/coreth/precompile/precompileconfig Predicater,Config,ChainConfig,Accepter +// mockgen -package=precompileconfig -destination=mocks.go . Predicater,Config,ChainConfig,Accepter // // Package precompileconfig is a generated GoMock package. @@ -20,6 +20,7 @@ import ( type MockPredicater struct { ctrl *gomock.Controller recorder *MockPredicaterMockRecorder + isgomock struct{} } // MockPredicaterMockRecorder is the mock recorder for MockPredicater. @@ -40,38 +41,39 @@ func (m *MockPredicater) EXPECT() *MockPredicaterMockRecorder { } // PredicateGas mocks base method. -func (m *MockPredicater) PredicateGas(arg0 []byte) (uint64, error) { +func (m *MockPredicater) PredicateGas(predicateBytes []byte) (uint64, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PredicateGas", arg0) + ret := m.ctrl.Call(m, "PredicateGas", predicateBytes) ret0, _ := ret[0].(uint64) ret1, _ := ret[1].(error) return ret0, ret1 } // PredicateGas indicates an expected call of PredicateGas. -func (mr *MockPredicaterMockRecorder) PredicateGas(arg0 any) *gomock.Call { +func (mr *MockPredicaterMockRecorder) PredicateGas(predicateBytes any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PredicateGas", reflect.TypeOf((*MockPredicater)(nil).PredicateGas), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PredicateGas", reflect.TypeOf((*MockPredicater)(nil).PredicateGas), predicateBytes) } // VerifyPredicate mocks base method. -func (m *MockPredicater) VerifyPredicate(arg0 *PredicateContext, arg1 []byte) error { +func (m *MockPredicater) VerifyPredicate(predicateContext *PredicateContext, predicateBytes []byte) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "VerifyPredicate", arg0, arg1) + ret := m.ctrl.Call(m, "VerifyPredicate", predicateContext, predicateBytes) ret0, _ := ret[0].(error) return ret0 } // VerifyPredicate indicates an expected call of VerifyPredicate. -func (mr *MockPredicaterMockRecorder) VerifyPredicate(arg0, arg1 any) *gomock.Call { +func (mr *MockPredicaterMockRecorder) VerifyPredicate(predicateContext, predicateBytes any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyPredicate", reflect.TypeOf((*MockPredicater)(nil).VerifyPredicate), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyPredicate", reflect.TypeOf((*MockPredicater)(nil).VerifyPredicate), predicateContext, predicateBytes) } // MockConfig is a mock of Config interface. type MockConfig struct { ctrl *gomock.Controller recorder *MockConfigMockRecorder + isgomock struct{} } // MockConfigMockRecorder is the mock recorder for MockConfig. @@ -165,6 +167,7 @@ func (mr *MockConfigMockRecorder) Verify(arg0 any) *gomock.Call { type MockChainConfig struct { ctrl *gomock.Controller recorder *MockChainConfigMockRecorder + isgomock struct{} } // MockChainConfigMockRecorder is the mock recorder for MockChainConfig. @@ -185,23 +188,24 @@ func (m *MockChainConfig) EXPECT() *MockChainConfigMockRecorder { } // IsDurango mocks base method. -func (m *MockChainConfig) IsDurango(arg0 uint64) bool { +func (m *MockChainConfig) IsDurango(time uint64) bool { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "IsDurango", arg0) + ret := m.ctrl.Call(m, "IsDurango", time) ret0, _ := ret[0].(bool) return ret0 } // IsDurango indicates an expected call of IsDurango. -func (mr *MockChainConfigMockRecorder) IsDurango(arg0 any) *gomock.Call { +func (mr *MockChainConfigMockRecorder) IsDurango(time any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsDurango", reflect.TypeOf((*MockChainConfig)(nil).IsDurango), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsDurango", reflect.TypeOf((*MockChainConfig)(nil).IsDurango), time) } // MockAccepter is a mock of Accepter interface. type MockAccepter struct { ctrl *gomock.Controller recorder *MockAccepterMockRecorder + isgomock struct{} } // MockAccepterMockRecorder is the mock recorder for MockAccepter. @@ -222,15 +226,15 @@ func (m *MockAccepter) EXPECT() *MockAccepterMockRecorder { } // Accept mocks base method. -func (m *MockAccepter) Accept(arg0 *AcceptContext, arg1 common.Hash, arg2 uint64, arg3 common.Hash, arg4 int, arg5 []common.Hash, arg6 []byte) error { +func (m *MockAccepter) Accept(acceptCtx *AcceptContext, blockHash common.Hash, blockNumber uint64, txHash common.Hash, logIndex int, topics []common.Hash, logData []byte) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Accept", arg0, arg1, arg2, arg3, arg4, arg5, arg6) + ret := m.ctrl.Call(m, "Accept", acceptCtx, blockHash, blockNumber, txHash, logIndex, topics, logData) ret0, _ := ret[0].(error) return ret0 } // Accept indicates an expected call of Accept. -func (mr *MockAccepterMockRecorder) Accept(arg0, arg1, arg2, arg3, arg4, arg5, arg6 any) *gomock.Call { +func (mr *MockAccepterMockRecorder) Accept(acceptCtx, blockHash, blockNumber, txHash, logIndex, topics, logData any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Accept", reflect.TypeOf((*MockAccepter)(nil).Accept), arg0, arg1, arg2, arg3, arg4, arg5, arg6) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Accept", reflect.TypeOf((*MockAccepter)(nil).Accept), acceptCtx, blockHash, blockNumber, txHash, logIndex, topics, logData) } diff --git a/precompile/precompileconfig/mocks_generate_test.go b/precompile/precompileconfig/mocks_generate_test.go new file mode 100644 index 0000000000..9ca4ea38df --- /dev/null +++ b/precompile/precompileconfig/mocks_generate_test.go @@ -0,0 +1,6 @@ +// Copyright (C) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package precompileconfig + +//go:generate go run go.uber.org/mock/mockgen -package=$GOPACKAGE -destination=mocks.go . Predicater,Config,ChainConfig,Accepter diff --git a/scripts/mock.gen.sh b/scripts/mock.gen.sh deleted file mode 100755 index 87465d43a9..0000000000 --- a/scripts/mock.gen.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -# Root directory -CORETH_PATH=$( - cd "$(dirname "${BASH_SOURCE[0]}")" - cd .. && pwd -) - -if ! [[ "$0" =~ scripts/mock.gen.sh ]]; then - echo "must be run from repository root" - exit 255 -fi - -# https://github.com/uber-go/mock -go install -v go.uber.org/mock/mockgen@v0.4.0 - -if ! command -v go-license &>/dev/null; then - echo "go-license not found, installing..." - # https://github.com/palantir/go-license - go install -v github.com/palantir/go-license@v1.25.0 -fi - -# Load the versions -source "$CORETH_PATH"/scripts/versions.sh - -# Load the constants -source "$CORETH_PATH"/scripts/constants.sh - -# tuples of (source interface import path, comma-separated interface names, output file path) -input="scripts/mocks.mockgen.txt" -while IFS= read -r line; do - IFS='=' read -r src_import_path interface_name output_path <<<"${line}" - package_name=$(basename "$(dirname "$output_path")") - echo "Generating ${output_path}..." - mockgen -package="${package_name}" -destination="${output_path}" "${src_import_path}" "${interface_name}" - - go-license \ - --config=./header.yml \ - "${output_path}" -done <"$input" - -echo "SUCCESS" diff --git a/scripts/mocks.mockgen.txt b/scripts/mocks.mockgen.txt deleted file mode 100644 index 694343e40e..0000000000 --- a/scripts/mocks.mockgen.txt +++ /dev/null @@ -1,2 +0,0 @@ -github.com/ava-labs/coreth/precompile/precompileconfig=Predicater,Config,ChainConfig,Accepter=precompile/precompileconfig/mocks.go -github.com/ava-labs/coreth/precompile/contract=BlockContext,AccessibleState,StateDB=precompile/contract/mocks.go diff --git a/tools.go b/tools.go new file mode 100644 index 0000000000..d7c65266dd --- /dev/null +++ b/tools.go @@ -0,0 +1,8 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package coreth + +import ( + _ "golang.org/x/tools/imports" // golang.org/x/tools to satisfy requirement for go.uber.org/mock/mockgen@v0.5 +) diff --git a/warp/aggregator/mock_signature_getter.go b/warp/aggregator/mock_signature_getter.go index 144d8a2f98..70365da0ce 100644 --- a/warp/aggregator/mock_signature_getter.go +++ b/warp/aggregator/mock_signature_getter.go @@ -1,5 +1,10 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/coreth/warp/aggregator (interfaces: SignatureGetter) +// Source: signature_getter.go +// +// Generated by this command: +// +// mockgen -package=aggregator -source=signature_getter.go -destination=mock_signature_getter.go +// // Package aggregator is a generated GoMock package. package aggregator @@ -18,6 +23,7 @@ import ( type MockSignatureGetter struct { ctrl *gomock.Controller recorder *MockSignatureGetterMockRecorder + isgomock struct{} } // MockSignatureGetterMockRecorder is the mock recorder for MockSignatureGetter. @@ -38,16 +44,55 @@ func (m *MockSignatureGetter) EXPECT() *MockSignatureGetterMockRecorder { } // GetSignature mocks base method. -func (m *MockSignatureGetter) GetSignature(arg0 context.Context, arg1 ids.NodeID, arg2 *warp.UnsignedMessage) (*bls.Signature, error) { +func (m *MockSignatureGetter) GetSignature(ctx context.Context, nodeID ids.NodeID, unsignedWarpMessage *warp.UnsignedMessage) (*bls.Signature, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSignature", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "GetSignature", ctx, nodeID, unsignedWarpMessage) ret0, _ := ret[0].(*bls.Signature) ret1, _ := ret[1].(error) return ret0, ret1 } // GetSignature indicates an expected call of GetSignature. -func (mr *MockSignatureGetterMockRecorder) GetSignature(arg0, arg1, arg2 interface{}) *gomock.Call { +func (mr *MockSignatureGetterMockRecorder) GetSignature(ctx, nodeID, unsignedWarpMessage any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSignature", reflect.TypeOf((*MockSignatureGetter)(nil).GetSignature), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSignature", reflect.TypeOf((*MockSignatureGetter)(nil).GetSignature), ctx, nodeID, unsignedWarpMessage) +} + +// MockNetworkClient is a mock of NetworkClient interface. +type MockNetworkClient struct { + ctrl *gomock.Controller + recorder *MockNetworkClientMockRecorder + isgomock struct{} +} + +// MockNetworkClientMockRecorder is the mock recorder for MockNetworkClient. +type MockNetworkClientMockRecorder struct { + mock *MockNetworkClient +} + +// NewMockNetworkClient creates a new mock instance. +func NewMockNetworkClient(ctrl *gomock.Controller) *MockNetworkClient { + mock := &MockNetworkClient{ctrl: ctrl} + mock.recorder = &MockNetworkClientMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockNetworkClient) EXPECT() *MockNetworkClientMockRecorder { + return m.recorder +} + +// SendAppRequest mocks base method. +func (m *MockNetworkClient) SendAppRequest(ctx context.Context, nodeID ids.NodeID, message []byte) ([]byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SendAppRequest", ctx, nodeID, message) + ret0, _ := ret[0].([]byte) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// SendAppRequest indicates an expected call of SendAppRequest. +func (mr *MockNetworkClientMockRecorder) SendAppRequest(ctx, nodeID, message any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAppRequest", reflect.TypeOf((*MockNetworkClient)(nil).SendAppRequest), ctx, nodeID, message) } diff --git a/warp/aggregator/mocks_generate_test.go b/warp/aggregator/mocks_generate_test.go new file mode 100644 index 0000000000..46388a6c7c --- /dev/null +++ b/warp/aggregator/mocks_generate_test.go @@ -0,0 +1,6 @@ +// Copyright (C) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package aggregator + +//go:generate go run go.uber.org/mock/mockgen -package=$GOPACKAGE -source=signature_getter.go -destination=mock_signature_getter.go From 7c069d88ee75c8104ed9839f050a2d5b291afada Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 7 Jan 2025 05:59:17 -0800 Subject: [PATCH 18/69] Sync subnet-evm changes up to 981830ed (#737) * small changes * relevant warp changes * use wrapped db package * nit * equivalent to subnet-evm 843e3f7 * add multiatch docker build to support arm (#1417) * remove build_docker_image.sh --------- Co-authored-by: Ceyhun Onur --- consensus/dummy/README.md | 2 +- core/state/pruner/pruner.go | 2 +- eth/tracers/js/tracer_test.go | 2 +- eth/tracers/logger/access_list_tracer.go | 2 +- plugin/evm/{service.go => api.go} | 0 plugin/evm/atomic_trie.go | 33 ++++---- plugin/evm/block.go | 4 +- .../wrapped_database.go} | 32 ++++---- plugin/evm/export_tx_test.go | 6 +- plugin/evm/syncervm_test.go | 9 +- plugin/evm/vm.go | 57 +++++-------- plugin/evm/vm_database.go | 82 +++++++++++++++++++ plugin/evm/vm_test.go | 2 +- precompile/contract/interfaces.go | 2 +- precompile/contracts/warp/README.md | 2 +- rpc/handler.go | 2 +- rpc/types.go | 2 +- scripts/build_docker_image.sh | 23 ------ scripts/known_flakes.txt | 1 + sync/statesync/trie_sync_stats.go | 2 +- warp/aggregator/aggregator_test.go | 2 +- warp/backend.go | 2 +- warp/backend_test.go | 7 ++ warp/verifier_backend.go | 8 +- warp/verifier_backend_test.go | 10 +-- warp/verifier_stats.go | 10 +-- 26 files changed, 184 insertions(+), 122 deletions(-) rename plugin/evm/{service.go => api.go} (100%) rename plugin/evm/{database.go => database/wrapped_database.go} (55%) create mode 100644 plugin/evm/vm_database.go delete mode 100755 scripts/build_docker_image.sh diff --git a/consensus/dummy/README.md b/consensus/dummy/README.md index 23ff20072a..cca69cf239 100644 --- a/consensus/dummy/README.md +++ b/consensus/dummy/README.md @@ -18,7 +18,7 @@ The dynamic fee algorithm aims to adjust the base fee to handle network congesti - EIP-1559 is intended for Ethereum where a block is produced roughly every 10s - C-Chain typically produces blocks every 2 seconds, but the dynamic fee algorithm needs to handle the case that the network quiesces and there are no blocks for a long period of time -- Since C-Chain produces blocks at a different cadence, it adapts EIP-1559 to sum the amount of gas consumed within a 10 second interval instead of using only the amount of gas consumed in the parent block +- Since C-Chain produces blocks at a different cadence, it adapts EIP-1559 to sum the amount of gas consumed within a 10-second interval instead of using only the amount of gas consumed in the parent block ## Consensus Engine Callbacks diff --git a/core/state/pruner/pruner.go b/core/state/pruner/pruner.go index 29431a0ecd..090b7ac6af 100644 --- a/core/state/pruner/pruner.go +++ b/core/state/pruner/pruner.go @@ -52,7 +52,7 @@ const ( // stateBloomFilePrefix is the filename prefix of state bloom filter. stateBloomFilePrefix = "statebloom" - // stateBloomFilePrefix is the filename suffix of state bloom filter. + // stateBloomFileSuffix is the filename suffix of state bloom filter. stateBloomFileSuffix = "bf.gz" // stateBloomFileTempSuffix is the filename suffix of state bloom filter diff --git a/eth/tracers/js/tracer_test.go b/eth/tracers/js/tracer_test.go index 7e46c0aa20..746fc0eb0e 100644 --- a/eth/tracers/js/tracer_test.go +++ b/eth/tracers/js/tracer_test.go @@ -206,7 +206,7 @@ func TestHaltBetweenSteps(t *testing.T) { } } -// testNoStepExec tests a regular value transfer (no exec), and accessing the statedb +// TestNoStepExec tests a regular value transfer (no exec), and accessing the statedb // in 'result' func TestNoStepExec(t *testing.T) { execTracer := func(code string) []byte { diff --git a/eth/tracers/logger/access_list_tracer.go b/eth/tracers/logger/access_list_tracer.go index e2bb12f2d7..d43198a2ff 100644 --- a/eth/tracers/logger/access_list_tracer.go +++ b/eth/tracers/logger/access_list_tracer.go @@ -87,7 +87,7 @@ func (al accessList) equal(other accessList) bool { return true } -// accesslist converts the accesslist to a types.AccessList. +// accessList converts the accesslist to a types.AccessList. func (al accessList) accessList() types.AccessList { acl := make(types.AccessList, 0, len(al)) for addr, slots := range al { diff --git a/plugin/evm/service.go b/plugin/evm/api.go similarity index 100% rename from plugin/evm/service.go rename to plugin/evm/api.go diff --git a/plugin/evm/atomic_trie.go b/plugin/evm/atomic_trie.go index d734268e23..f6add46623 100644 --- a/plugin/evm/atomic_trie.go +++ b/plugin/evm/atomic_trie.go @@ -9,7 +9,7 @@ import ( avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/codec" - "github.com/ava-labs/avalanchego/database" + avalanchedatabase "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/utils/wrappers" @@ -18,6 +18,7 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/plugin/evm/atomic" + "github.com/ava-labs/coreth/plugin/evm/database" "github.com/ava-labs/coreth/trie" "github.com/ava-labs/coreth/trie/trienode" "github.com/ava-labs/coreth/triedb" @@ -117,12 +118,12 @@ type AtomicTrieIterator interface { // atomicTrie implements the AtomicTrie interface type atomicTrie struct { - commitInterval uint64 // commit interval, same as commitHeightInterval by default - metadataDB database.Database // Underlying database containing the atomic trie metadata - trieDB *triedb.Database // Trie database - lastCommittedRoot common.Hash // trie root of the most recent commit - lastCommittedHeight uint64 // index height of the most recent commit - lastAcceptedRoot common.Hash // most recent trie root passed to accept trie or the root of the atomic trie on intialization. + commitInterval uint64 // commit interval, same as commitHeightInterval by default + metadataDB avalanchedatabase.Database // Underlying database containing the atomic trie metadata + trieDB *triedb.Database // Trie database + lastCommittedRoot common.Hash // trie root of the most recent commit + lastCommittedHeight uint64 // index height of the most recent commit + lastAcceptedRoot common.Hash // most recent trie root passed to accept trie or the root of the atomic trie on intialization. codec codec.Manager memoryCap common.StorageSize tipBuffer *core.BoundedBuffer[common.Hash] @@ -131,7 +132,7 @@ type atomicTrie struct { // newAtomicTrie returns a new instance of a atomicTrie with a configurable commitHeightInterval, used in testing. // Initializes the trie before returning it. func newAtomicTrie( - atomicTrieDB database.Database, metadataDB database.Database, + atomicTrieDB avalanchedatabase.Database, metadataDB avalanchedatabase.Database, codec codec.Manager, lastAcceptedHeight uint64, commitHeightInterval uint64, ) (*atomicTrie, error) { root, height, err := lastCommittedRootIfExists(metadataDB) @@ -153,7 +154,7 @@ func newAtomicTrie( } trieDB := triedb.NewDatabase( - rawdb.NewDatabase(Database{atomicTrieDB}), + rawdb.NewDatabase(database.WrapDatabase(atomicTrieDB)), &triedb.Config{ HashDB: &hashdb.Config{ CleanCacheSize: 64 * units.MiB, // Allocate 64MB of memory for clean cache @@ -182,17 +183,17 @@ func newAtomicTrie( // else returns empty common.Hash{} and 0 // returns error only if there are issues with the underlying data store // or if values present in the database are not as expected -func lastCommittedRootIfExists(db database.Database) (common.Hash, uint64, error) { +func lastCommittedRootIfExists(db avalanchedatabase.Database) (common.Hash, uint64, error) { // read the last committed entry if it exists and set the root hash lastCommittedHeightBytes, err := db.Get(lastCommittedKey) switch { - case err == database.ErrNotFound: + case err == avalanchedatabase.ErrNotFound: return common.Hash{}, 0, nil case err != nil: return common.Hash{}, 0, err } - height, err := database.ParseUInt64(lastCommittedHeightBytes) + height, err := avalanchedatabase.ParseUInt64(lastCommittedHeightBytes) if err != nil { return common.Hash{}, 0, fmt.Errorf("expected value at lastCommittedKey to be a valid uint64: %w", err) } @@ -251,7 +252,7 @@ func (a *atomicTrie) LastCommitted() (common.Hash, uint64) { // updateLastCommitted adds [height] -> [root] to the index and marks it as the last committed // root/height pair. func (a *atomicTrie) updateLastCommitted(root common.Hash, height uint64) error { - heightBytes := database.PackUInt64(height) + heightBytes := avalanchedatabase.PackUInt64(height) // now save the trie hash against the height it was committed at if err := a.metadataDB.Put(heightBytes, root[:]); err != nil { @@ -297,7 +298,7 @@ func (a *atomicTrie) Root(height uint64) (common.Hash, error) { // getRoot is a helper function to return the committed atomic trie root hash at [height] // from [metadataDB]. -func getRoot(metadataDB database.Database, height uint64) (common.Hash, error) { +func getRoot(metadataDB avalanchedatabase.Database, height uint64) (common.Hash, error) { if height == 0 { // if root is queried at height == 0, return the empty root hash // this may occur if peers ask for the most recent state summary @@ -305,10 +306,10 @@ func getRoot(metadataDB database.Database, height uint64) (common.Hash, error) { return types.EmptyRootHash, nil } - heightBytes := database.PackUInt64(height) + heightBytes := avalanchedatabase.PackUInt64(height) hash, err := metadataDB.Get(heightBytes) switch { - case err == database.ErrNotFound: + case err == avalanchedatabase.ErrNotFound: return common.Hash{}, nil case err != nil: return common.Hash{}, err diff --git a/plugin/evm/block.go b/plugin/evm/block.go index 9a2de32601..f94f3ebd81 100644 --- a/plugin/evm/block.go +++ b/plugin/evm/block.go @@ -143,7 +143,7 @@ func (b *Block) Accept(context.Context) error { // Although returning an error from Accept is considered fatal, it is good // practice to cleanup the batch we were modifying in the case of an error. - defer vm.db.Abort() + defer vm.versiondb.Abort() log.Debug(fmt.Sprintf("Accepting block %s (%s) at height %d", b.ID().Hex(), b.ID(), b.Height())) @@ -176,7 +176,7 @@ func (b *Block) Accept(context.Context) error { } // Get pending operations on the vm's versionDB so we can apply them atomically // with the shared memory changes. - vdbBatch, err := b.vm.db.CommitBatch() + vdbBatch, err := b.vm.versiondb.CommitBatch() if err != nil { return fmt.Errorf("could not create commit batch processing block[%s]: %w", b.ID(), err) } diff --git a/plugin/evm/database.go b/plugin/evm/database/wrapped_database.go similarity index 55% rename from plugin/evm/database.go rename to plugin/evm/database/wrapped_database.go index 479c995ba3..f8a36913bb 100644 --- a/plugin/evm/database.go +++ b/plugin/evm/database/wrapped_database.go @@ -1,7 +1,7 @@ // (c) 2019-2020, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package evm +package database import ( "errors" @@ -11,25 +11,29 @@ import ( ) var ( - _ ethdb.KeyValueStore = &Database{} + _ ethdb.KeyValueStore = ðDbWrapper{} ErrSnapshotNotSupported = errors.New("snapshot is not supported") ) -// Database implements ethdb.Database -type Database struct{ database.Database } +// ethDbWrapper implements ethdb.Database +type ethDbWrapper struct{ database.Database } + +func WrapDatabase(db database.Database) ethdb.KeyValueStore { return ethDbWrapper{db} } // Stat implements ethdb.Database -func (db Database) Stat(string) (string, error) { return "", database.ErrNotFound } +func (db ethDbWrapper) Stat(string) (string, error) { return "", database.ErrNotFound } // NewBatch implements ethdb.Database -func (db Database) NewBatch() ethdb.Batch { return Batch{db.Database.NewBatch()} } +func (db ethDbWrapper) NewBatch() ethdb.Batch { return wrappedBatch{db.Database.NewBatch()} } // NewBatchWithSize implements ethdb.Database // TODO: propagate size through avalanchego Database interface -func (db Database) NewBatchWithSize(size int) ethdb.Batch { return Batch{db.Database.NewBatch()} } +func (db ethDbWrapper) NewBatchWithSize(size int) ethdb.Batch { + return wrappedBatch{db.Database.NewBatch()} +} -func (db Database) NewSnapshot() (ethdb.Snapshot, error) { +func (db ethDbWrapper) NewSnapshot() (ethdb.Snapshot, error) { return nil, ErrSnapshotNotSupported } @@ -37,7 +41,7 @@ func (db Database) NewSnapshot() (ethdb.Snapshot, error) { // // Note: This method assumes that the prefix is NOT part of the start, so there's // no need for the caller to prepend the prefix to the start. -func (db Database) NewIterator(prefix []byte, start []byte) ethdb.Iterator { +func (db ethDbWrapper) NewIterator(prefix []byte, start []byte) ethdb.Iterator { // avalanchego's database implementation assumes that the prefix is part of the // start, so it is added here (if it is provided). if len(prefix) > 0 { @@ -50,15 +54,15 @@ func (db Database) NewIterator(prefix []byte, start []byte) ethdb.Iterator { } // NewIteratorWithStart implements ethdb.Database -func (db Database) NewIteratorWithStart(start []byte) ethdb.Iterator { +func (db ethDbWrapper) NewIteratorWithStart(start []byte) ethdb.Iterator { return db.Database.NewIteratorWithStart(start) } -// Batch implements ethdb.Batch -type Batch struct{ database.Batch } +// wrappedBatch implements ethdb.wrappedBatch +type wrappedBatch struct{ database.Batch } // ValueSize implements ethdb.Batch -func (batch Batch) ValueSize() int { return batch.Batch.Size() } +func (batch wrappedBatch) ValueSize() int { return batch.Batch.Size() } // Replay implements ethdb.Batch -func (batch Batch) Replay(w ethdb.KeyValueWriter) error { return batch.Batch.Replay(w) } +func (batch wrappedBatch) Replay(w ethdb.KeyValueWriter) error { return batch.Batch.Replay(w) } diff --git a/plugin/evm/export_tx_test.go b/plugin/evm/export_tx_test.go index 36b74ab45a..8e6c5d689b 100644 --- a/plugin/evm/export_tx_test.go +++ b/plugin/evm/export_tx_test.go @@ -1011,7 +1011,7 @@ func TestExportTxAccept(t *testing.T) { t.Fatal(err) } - commitBatch, err := vm.db.CommitBatch() + commitBatch, err := vm.versiondb.CommitBatch() if err != nil { t.Fatalf("Failed to create commit batch for VM due to %s", err) } @@ -1800,7 +1800,7 @@ func TestNewExportTx(t *testing.T) { t.Fatalf("burned wrong amount of AVAX - expected %d burned %d", test.expectedBurnedAVAX, burnedAVAX) } - commitBatch, err := vm.db.CommitBatch() + commitBatch, err := vm.versiondb.CommitBatch() if err != nil { t.Fatalf("Failed to create commit batch for VM due to %s", err) } @@ -2000,7 +2000,7 @@ func TestNewExportTxMulticoin(t *testing.T) { t.Fatal("newExportTx created an invalid transaction", err) } - commitBatch, err := vm.db.CommitBatch() + commitBatch, err := vm.versiondb.CommitBatch() if err != nil { t.Fatalf("Failed to create commit batch for VM due to %s", err) } diff --git a/plugin/evm/syncervm_test.go b/plugin/evm/syncervm_test.go index bd7f993cb5..7c8e76fa0a 100644 --- a/plugin/evm/syncervm_test.go +++ b/plugin/evm/syncervm_test.go @@ -16,7 +16,7 @@ import ( "github.com/stretchr/testify/require" avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" - "github.com/ava-labs/avalanchego/database" + avalanchedatabase "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" @@ -36,6 +36,7 @@ import ( "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/plugin/evm/atomic" + "github.com/ava-labs/coreth/plugin/evm/database" "github.com/ava-labs/coreth/predicate" statesyncclient "github.com/ava-labs/coreth/sync/client" "github.com/ava-labs/coreth/sync/statesync" @@ -334,7 +335,7 @@ func createSyncServerAndClientVMs(t *testing.T, test syncTest, numBlocks int) *s serverAtomicTrie := serverVM.atomicTrie.(*atomicTrie) serverAtomicTrie.commitInterval = test.syncableInterval require.NoError(serverAtomicTrie.commit(test.syncableInterval, serverAtomicTrie.LastAcceptedRoot())) - require.NoError(serverVM.db.Commit()) + require.NoError(serverVM.versiondb.Commit()) serverSharedMemories := newSharedMemories(serverAtomicMemory, serverVM.ctx.ChainID, serverVM.ctx.XChainID) serverSharedMemories.assertOpsApplied(t, mustAtomicOps(importTx)) @@ -430,7 +431,7 @@ type syncVMSetup struct { fundedAccounts map[*keystore.Key]*types.StateAccount syncerVM *VM - syncerDB database.Database + syncerDB avalanchedatabase.Database syncerEngineChan <-chan commonEng.Message syncerAtomicMemory *avalancheatomic.Memory shutdownOnceSyncerVM *shutdownOnceVM @@ -491,7 +492,7 @@ func testSyncerVM(t *testing.T, vmSetup *syncVMSetup, test syncTest) { if test.expectedErr != nil { require.ErrorIs(err, test.expectedErr) // Note we re-open the database here to avoid a closed error when the test is for a shutdown VM. - chaindb := Database{prefixdb.NewNested(ethDBPrefix, syncerVM.db)} + chaindb := database.WrapDatabase(prefixdb.NewNested(ethDBPrefix, syncerVM.db)) assertSyncPerformedHeights(t, chaindb, map[uint64]struct{}{}) return } diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 6900c26ea0..89c8ea4629 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -76,7 +76,6 @@ import ( "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/codec/linearcodec" "github.com/ava-labs/avalanchego/database" - "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" @@ -225,8 +224,11 @@ type VM struct { blockChain *core.BlockChain miner *miner.Miner - // [db] is the VM's current database managed by ChainState - db *versiondb.Database + // [versiondb] is the VM's current versioned database + versiondb *versiondb.Database + + // [db] is the VM's current database + db database.Database // metadataDB is used to store one off keys. metadataDB database.Database @@ -274,7 +276,7 @@ type VM struct { client peer.NetworkClient networkCodec codec.Manager - validators *p2p.Validators + p2pValidators *p2p.Validators // Metrics sdkMetrics *prometheus.Registry @@ -396,14 +398,10 @@ func (vm *VM) Initialize( if err := vm.initializeDBs(db); err != nil { return fmt.Errorf("failed to initialize databases: %w", err) } - if vm.config.InspectDatabase { - start := time.Now() - log.Info("Starting database inspection") - if err := rawdb.InspectDatabase(vm.chaindb, nil, nil); err != nil { + if err := vm.inspectDatabases(); err != nil { return err } - log.Info("Completed database inspection", "elapsed", time.Since(start)) } g := new(core.Genesis) @@ -542,7 +540,7 @@ func (vm *VM) Initialize( if err != nil { return fmt.Errorf("failed to initialize p2p network: %w", err) } - vm.validators = p2p.NewValidators(p2pNetwork.Peers, vm.ctx.Log, vm.ctx.SubnetID, vm.ctx.ValidatorState, maxValidatorSetStaleness) + vm.p2pValidators = p2p.NewValidators(p2pNetwork.Peers, vm.ctx.Log, vm.ctx.SubnetID, vm.ctx.ValidatorState, maxValidatorSetStaleness) vm.networkCodec = message.Codec vm.Network = peer.NewNetwork(p2pNetwork, appSender, vm.networkCodec, chainCtx.NodeID, vm.config.MaxOutboundActiveRequests) vm.client = peer.NewNetworkClient(vm.Network) @@ -592,12 +590,12 @@ func (vm *VM) Initialize( } // initialize atomic repository - vm.atomicTxRepository, err = NewAtomicTxRepository(vm.db, atomic.Codec, lastAcceptedHeight) + vm.atomicTxRepository, err = NewAtomicTxRepository(vm.versiondb, atomic.Codec, lastAcceptedHeight) if err != nil { return fmt.Errorf("failed to create atomic repository: %w", err) } vm.atomicBackend, err = NewAtomicBackend( - vm.db, vm.ctx.SharedMemory, bonusBlockHeights, + vm.versiondb, vm.ctx.SharedMemory, bonusBlockHeights, vm.atomicTxRepository, lastAcceptedHeight, lastAcceptedHash, vm.config.CommitInterval, ) @@ -723,7 +721,7 @@ func (vm *VM) initializeStateSyncClient(lastAcceptedHeight uint64) error { chaindb: vm.chaindb, metadataDB: vm.metadataDB, acceptedBlockDB: vm.acceptedBlockDB, - db: vm.db, + db: vm.versiondb, atomicBackend: vm.atomicBackend, toEngine: vm.toEngine, }) @@ -1047,7 +1045,7 @@ func (vm *VM) initBlockBuilding() error { vm.cancel = cancel ethTxGossipMarshaller := GossipEthTxMarshaller{} - ethTxGossipClient := vm.Network.NewClient(p2p.TxGossipHandlerID, p2p.WithValidatorSampling(vm.validators)) + ethTxGossipClient := vm.Network.NewClient(p2p.TxGossipHandlerID, p2p.WithValidatorSampling(vm.p2pValidators)) ethTxGossipMetrics, err := gossip.NewMetrics(vm.sdkMetrics, ethTxGossipNamespace) if err != nil { return fmt.Errorf("failed to initialize eth tx gossip metrics: %w", err) @@ -1063,7 +1061,7 @@ func (vm *VM) initBlockBuilding() error { }() atomicTxGossipMarshaller := atomic.GossipAtomicTxMarshaller{} - atomicTxGossipClient := vm.Network.NewClient(p2p.AtomicTxGossipHandlerID, p2p.WithValidatorSampling(vm.validators)) + atomicTxGossipClient := vm.Network.NewClient(p2p.AtomicTxGossipHandlerID, p2p.WithValidatorSampling(vm.p2pValidators)) atomicTxGossipMetrics, err := gossip.NewMetrics(vm.sdkMetrics, atomicTxGossipNamespace) if err != nil { return fmt.Errorf("failed to initialize atomic tx gossip metrics: %w", err) @@ -1084,7 +1082,7 @@ func (vm *VM) initBlockBuilding() error { ethTxPushGossiper, err = gossip.NewPushGossiper[*GossipEthTx]( ethTxGossipMarshaller, ethTxPool, - vm.validators, + vm.p2pValidators, ethTxGossipClient, ethTxGossipMetrics, pushGossipParams, @@ -1103,7 +1101,7 @@ func (vm *VM) initBlockBuilding() error { vm.atomicTxPushGossiper, err = gossip.NewPushGossiper[*atomic.GossipAtomicTx]( atomicTxGossipMarshaller, vm.mempool, - vm.validators, + vm.p2pValidators, atomicTxGossipClient, atomicTxGossipMetrics, pushGossipParams, @@ -1130,7 +1128,7 @@ func (vm *VM) initBlockBuilding() error { txGossipTargetMessageSize, txGossipThrottlingPeriod, txGossipThrottlingLimit, - vm.validators, + vm.p2pValidators, ) } @@ -1147,7 +1145,7 @@ func (vm *VM) initBlockBuilding() error { txGossipTargetMessageSize, txGossipThrottlingPeriod, txGossipThrottlingLimit, - vm.validators, + vm.p2pValidators, ) } @@ -1168,7 +1166,7 @@ func (vm *VM) initBlockBuilding() error { vm.ethTxPullGossiper = gossip.ValidatorGossiper{ Gossiper: ethTxPullGossiper, NodeID: vm.ctx.NodeID, - Validators: vm.validators, + Validators: vm.p2pValidators, } } @@ -1195,7 +1193,7 @@ func (vm *VM) initBlockBuilding() error { vm.atomicTxPullGossiper = &gossip.ValidatorGossiper{ Gossiper: atomicTxPullGossiper, NodeID: vm.ctx.NodeID, - Validators: vm.validators, + Validators: vm.p2pValidators, } } @@ -1457,6 +1455,7 @@ func (vm *VM) CreateHandlers(context.Context) (map[string]http.Handler, error) { enabledAPIs = append(enabledAPIs, "coreth-admin") } + // RPC APIs if vm.config.SnowmanAPIEnabled { if err := handler.RegisterName("snowman", &SnowmanAPI{vm}); err != nil { return nil, err @@ -1484,22 +1483,6 @@ func (vm *VM) CreateHandlers(context.Context) (map[string]http.Handler, error) { return apis, nil } -// initializeDBs initializes the databases used by the VM. -// coreth always uses the avalanchego provided database. -func (vm *VM) initializeDBs(db database.Database) error { - // Use NewNested rather than New so that the structure of the database - // remains the same regardless of the provided baseDB type. - vm.chaindb = rawdb.NewDatabase(Database{prefixdb.NewNested(ethDBPrefix, db)}) - vm.db = versiondb.New(db) - vm.acceptedBlockDB = prefixdb.New(acceptedPrefix, vm.db) - vm.metadataDB = prefixdb.New(metadataPrefix, vm.db) - // Note warpDB is not part of versiondb because it is not necessary - // that warp signatures are committed to the database atomically with - // the last accepted block. - vm.warpDB = prefixdb.New(warpPrefix, db) - return nil -} - // CreateStaticHandlers makes new http handlers that can handle API calls func (vm *VM) CreateStaticHandlers(context.Context) (map[string]http.Handler, error) { handler := rpc.NewServer(0) diff --git a/plugin/evm/vm_database.go b/plugin/evm/vm_database.go new file mode 100644 index 0000000000..f2a5b4c344 --- /dev/null +++ b/plugin/evm/vm_database.go @@ -0,0 +1,82 @@ +// (c) 2019-2021, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package evm + +import ( + "time" + + avalanchedatabase "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/prefixdb" + "github.com/ava-labs/avalanchego/database/versiondb" + "github.com/ava-labs/coreth/core/rawdb" + "github.com/ava-labs/coreth/plugin/evm/database" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" +) + +// initializeDBs initializes the databases used by the VM. +// coreth always uses the avalanchego provided database. +func (vm *VM) initializeDBs(db avalanchedatabase.Database) error { + // Use NewNested rather than New so that the structure of the database + // remains the same regardless of the provided baseDB type. + vm.chaindb = rawdb.NewDatabase(database.WrapDatabase(prefixdb.NewNested(ethDBPrefix, db))) + vm.versiondb = versiondb.New(db) + vm.acceptedBlockDB = prefixdb.New(acceptedPrefix, vm.versiondb) + vm.metadataDB = prefixdb.New(metadataPrefix, vm.versiondb) + vm.db = db + // Note warpDB is not part of versiondb because it is not necessary + // that warp signatures are committed to the database atomically with + // the last accepted block. + vm.warpDB = prefixdb.New(warpPrefix, db) + return nil +} + +func (vm *VM) inspectDatabases() error { + start := time.Now() + log.Info("Starting database inspection") + if err := rawdb.InspectDatabase(vm.chaindb, nil, nil); err != nil { + return err + } + if err := inspectDB(vm.acceptedBlockDB, "acceptedBlockDB"); err != nil { + return err + } + if err := inspectDB(vm.metadataDB, "metadataDB"); err != nil { + return err + } + if err := inspectDB(vm.warpDB, "warpDB"); err != nil { + return err + } + log.Info("Completed database inspection", "elapsed", time.Since(start)) + return nil +} + +func inspectDB(db avalanchedatabase.Database, label string) error { + it := db.NewIterator() + defer it.Release() + + var ( + count int64 + start = time.Now() + logged = time.Now() + + // Totals + total common.StorageSize + ) + // Inspect key-value database first. + for it.Next() { + var ( + key = it.Key() + size = common.StorageSize(len(key) + len(it.Value())) + ) + total += size + count++ + if count%1000 == 0 && time.Since(logged) > 8*time.Second { + log.Info("Inspecting database", "label", label, "count", count, "elapsed", common.PrettyDuration(time.Since(start))) + logged = time.Now() + } + } + // Display the database statistic. + log.Info("Database statistics", "label", label, "total", total.String(), "count", count) + return nil +} diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 56b56cf93c..2a79f3fb6f 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -3170,7 +3170,7 @@ func TestConfigureLogLevel(t *testing.T) { } } - // If the VM was not initialized, do not attept to shut it down + // If the VM was not initialized, do not attempt to shut it down if err == nil { shutdownChan := make(chan error, 1) shutdownFunc := func() { diff --git a/precompile/contract/interfaces.go b/precompile/contract/interfaces.go index b3ffb02fe2..44c3cfa633 100644 --- a/precompile/contract/interfaces.go +++ b/precompile/contract/interfaces.go @@ -62,7 +62,7 @@ type ConfigurationBlockContext interface { type BlockContext interface { ConfigurationBlockContext - // GetResults returns an arbitrary byte array result of verifying the predicates + // GetPredicateResults returns an arbitrary byte array result of verifying the predicates // of the given transaction, precompile address pair. GetPredicateResults(txHash common.Hash, precompileAddress common.Address) []byte } diff --git a/precompile/contracts/warp/README.md b/precompile/contracts/warp/README.md index 10e1daaa38..73ca165224 100644 --- a/precompile/contracts/warp/README.md +++ b/precompile/contracts/warp/README.md @@ -57,7 +57,7 @@ To use this function, the transaction must include the signed Avalanche Warp Mes This leads to the following advantages: 1. The EVM execution does not need to verify the Warp Message at runtime (no signature verification or external calls to the P-Chain) -2. The EVM can deterministically re-execute and re-verify blocks assuming the predicate was verified by the network (eg., in bootstrapping) +2. The EVM can deterministically re-execute and re-verify blocks assuming the predicate was verified by the network (e.g., in bootstrapping) This pre-verification is performed using the ProposerVM Block header during [block verification](../../../plugin/evm/block.go#L220) and [block building](../../../miner/worker.go#L200). diff --git a/rpc/handler.go b/rpc/handler.go index a15f6b20be..ef35a61ca8 100644 --- a/rpc/handler.go +++ b/rpc/handler.go @@ -479,7 +479,7 @@ func (h *handler) startCallProc(fn func(*callProc)) { } } -// handleResponse processes method call responses. +// handleResponses processes method call responses. func (h *handler) handleResponses(batch []*jsonrpcMessage, handleCall func(*jsonrpcMessage)) { var resolvedops []*requestOp handleResp := func(msg *jsonrpcMessage) { diff --git a/rpc/types.go b/rpc/types.go index b2f5b98528..c96e7bc74f 100644 --- a/rpc/types.go +++ b/rpc/types.go @@ -62,7 +62,7 @@ type ServerCodec interface { type jsonWriter interface { // writeJSON writes a message to the connection. writeJSON(ctx context.Context, msg interface{}, isError bool) error - // writeJSON writes a message to the connection with the option of skipping the deadline. + // writeJSONSkipDeadline writes a message to the connection with the option of skipping the deadline. writeJSONSkipDeadline(ctx context.Context, msg interface{}, isError bool, skip bool) error // Closed returns a channel which is closed when the connection is closed. closed() <-chan interface{} diff --git a/scripts/build_docker_image.sh b/scripts/build_docker_image.sh deleted file mode 100755 index 9126a47a8d..0000000000 --- a/scripts/build_docker_image.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -# Avalanche root directory -CORETH_PATH=$( - cd "$(dirname "${BASH_SOURCE[0]}")" - cd .. && pwd -) - -# Load the constants -source "$CORETH_PATH"/scripts/constants.sh - -# Load the versions -source "$CORETH_PATH"/scripts/versions.sh - -# WARNING: this will use the most recent commit even if there are un-committed changes present -BUILD_IMAGE_ID=${BUILD_IMAGE_ID:-"${CURRENT_BRANCH}"} -echo "Building Docker Image: $DOCKERHUB_REPO:$BUILD_IMAGE_ID based of AvalancheGo@$AVALANCHE_VERSION" -docker build -t "$DOCKERHUB_REPO:$BUILD_IMAGE_ID" "$CORETH_PATH" -f "$CORETH_PATH/Dockerfile" \ - --build-arg AVALANCHE_VERSION="$AVALANCHE_VERSION" \ - --build-arg CORETH_COMMIT="$CORETH_COMMIT" \ - --build-arg CURRENT_BRANCH="$CURRENT_BRANCH" diff --git a/scripts/known_flakes.txt b/scripts/known_flakes.txt index b28b4e710c..0f324a6714 100644 --- a/scripts/known_flakes.txt +++ b/scripts/known_flakes.txt @@ -5,6 +5,7 @@ TestMempoolAtmTxsAppGossipHandlingDiscardedTx TestMempoolEthTxsAppGossipHandling TestResumeSyncAccountsTrieInterrupted TestResyncNewRootAfterDeletes +TestTimedUnlock TestTransactionSkipIndexing TestVMShutdownWhileSyncing TestWaitDeployedCornerCases diff --git a/sync/statesync/trie_sync_stats.go b/sync/statesync/trie_sync_stats.go index bb4770e28c..c55fc8da35 100644 --- a/sync/statesync/trie_sync_stats.go +++ b/sync/statesync/trie_sync_stats.go @@ -79,7 +79,7 @@ func (t *trieSyncStats) incLeafs(segment *trieSegment, count uint64, remaining u } } -// estimateSegmentsInProgressTime retrns the ETA for all trie segments +// estimateSegmentsInProgressTime returns the ETA for all trie segments // in progress to finish (uses the one with most remaining leafs to estimate). func (t *trieSyncStats) estimateSegmentsInProgressTime() time.Duration { if len(t.remainingLeafs) == 0 { diff --git a/warp/aggregator/aggregator_test.go b/warp/aggregator/aggregator_test.go index 98e90607db..055d3edfa8 100644 --- a/warp/aggregator/aggregator_test.go +++ b/warp/aggregator/aggregator_test.go @@ -230,7 +230,7 @@ func TestAggregateSignatures(t *testing.T) { expectedErr: nil, }, { - name: "early termination of signature fetching on parent context cancelation", + name: "early termination of signature fetching on parent context cancellation", contextWithCancelFunc: func() (context.Context, context.CancelFunc) { ctx, cancel := context.WithCancel(context.Background()) cancel() diff --git a/warp/backend.go b/warp/backend.go index 6e1f6a9553..d35c96b8fb 100644 --- a/warp/backend.go +++ b/warp/backend.go @@ -180,7 +180,7 @@ func (b *backend) GetMessage(messageID ids.ID) (*avalancheWarp.UnsignedMessage, unsignedMessageBytes, err := b.db.Get(messageID[:]) if err != nil { - return nil, fmt.Errorf("failed to get warp message %s from db: %w", messageID.String(), err) + return nil, err } unsignedMessage, err := avalancheWarp.ParseUnsignedMessage(unsignedMessageBytes) diff --git a/warp/backend_test.go b/warp/backend_test.go index 4935875ece..cd7aa1ea76 100644 --- a/warp/backend_test.go +++ b/warp/backend_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/ava-labs/avalanchego/cache" + "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils" @@ -157,6 +158,12 @@ func TestOffChainMessages(t *testing.T) { require.Equal(expectedSignatureBytes, signature[:]) }, }, + "unknown message": { + check: func(require *require.Assertions, b Backend) { + _, err := b.GetMessage(testUnsignedMessage.ID()) + require.ErrorIs(err, database.ErrNotFound) + }, + }, "invalid message": { offchainMessages: [][]byte{{1, 2, 3}}, err: errParsingOffChainMessage, diff --git a/warp/verifier_backend.go b/warp/verifier_backend.go index c70563c585..3c8427b8ff 100644 --- a/warp/verifier_backend.go +++ b/warp/verifier_backend.go @@ -7,6 +7,7 @@ import ( "context" "fmt" + "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/snow/engine/common" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" @@ -24,6 +25,11 @@ func (b *backend) Verify(ctx context.Context, unsignedMessage *avalancheWarp.Uns // Known on-chain messages should be signed if _, err := b.GetMessage(messageID); err == nil { return nil + } else if err != database.ErrNotFound { + return &common.AppError{ + Code: ParseErrCode, + Message: fmt.Sprintf("failed to get message %s: %s", messageID, err.Error()), + } } parsed, err := payload.Parse(unsignedMessage.Payload) @@ -53,7 +59,7 @@ func (b *backend) verifyBlockMessage(ctx context.Context, blockHashPayload *payl blockID := blockHashPayload.Hash _, err := b.blockClient.GetAcceptedBlock(ctx, blockID) if err != nil { - b.stats.IncBlockSignatureValidationFail() + b.stats.IncBlockValidationFail() return &common.AppError{ Code: VerifyErrCode, Message: fmt.Sprintf("failed to get block %s: %s", blockID, err.Error()), diff --git a/warp/verifier_backend_test.go b/warp/verifier_backend_test.go index 4bf11541b0..a58726aa0f 100644 --- a/warp/verifier_backend_test.go +++ b/warp/verifier_backend_test.go @@ -56,7 +56,7 @@ func TestAddressedCallSignatures(t *testing.T) { }, verifyStats: func(t *testing.T, stats *verifierStats) { require.EqualValues(t, 0, stats.messageParseFail.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureValidationFail.Snapshot().Count()) + require.EqualValues(t, 0, stats.blockValidationFail.Snapshot().Count()) }, }, "offchain message": { @@ -65,7 +65,7 @@ func TestAddressedCallSignatures(t *testing.T) { }, verifyStats: func(t *testing.T, stats *verifierStats) { require.EqualValues(t, 0, stats.messageParseFail.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureValidationFail.Snapshot().Count()) + require.EqualValues(t, 0, stats.blockValidationFail.Snapshot().Count()) }, }, "unknown message": { @@ -78,7 +78,7 @@ func TestAddressedCallSignatures(t *testing.T) { }, verifyStats: func(t *testing.T, stats *verifierStats) { require.EqualValues(t, 1, stats.messageParseFail.Snapshot().Count()) - require.EqualValues(t, 0, stats.blockSignatureValidationFail.Snapshot().Count()) + require.EqualValues(t, 0, stats.blockValidationFail.Snapshot().Count()) }, err: &common.AppError{Code: ParseErrCode}, }, @@ -177,7 +177,7 @@ func TestBlockSignatures(t *testing.T) { return toMessageBytes(knownBlkID), signature[:] }, verifyStats: func(t *testing.T, stats *verifierStats) { - require.EqualValues(t, 0, stats.blockSignatureValidationFail.Snapshot().Count()) + require.EqualValues(t, 0, stats.blockValidationFail.Snapshot().Count()) require.EqualValues(t, 0, stats.messageParseFail.Snapshot().Count()) }, }, @@ -187,7 +187,7 @@ func TestBlockSignatures(t *testing.T) { return toMessageBytes(unknownBlockID), nil }, verifyStats: func(t *testing.T, stats *verifierStats) { - require.EqualValues(t, 1, stats.blockSignatureValidationFail.Snapshot().Count()) + require.EqualValues(t, 1, stats.blockValidationFail.Snapshot().Count()) require.EqualValues(t, 0, stats.messageParseFail.Snapshot().Count()) }, err: &common.AppError{Code: VerifyErrCode}, diff --git a/warp/verifier_stats.go b/warp/verifier_stats.go index 3ee90312d9..980d464429 100644 --- a/warp/verifier_stats.go +++ b/warp/verifier_stats.go @@ -10,18 +10,18 @@ import ( type verifierStats struct { messageParseFail metrics.Counter // BlockRequest metrics - blockSignatureValidationFail metrics.Counter + blockValidationFail metrics.Counter } func newVerifierStats() *verifierStats { return &verifierStats{ - messageParseFail: metrics.NewRegisteredCounter("message_parse_fail", nil), - blockSignatureValidationFail: metrics.NewRegisteredCounter("block_signature_validation_fail", nil), + messageParseFail: metrics.NewRegisteredCounter("warp_backend_message_parse_fail", nil), + blockValidationFail: metrics.NewRegisteredCounter("warp_backend_block_validation_fail", nil), } } -func (h *verifierStats) IncBlockSignatureValidationFail() { - h.blockSignatureValidationFail.Inc(1) +func (h *verifierStats) IncBlockValidationFail() { + h.blockValidationFail.Inc(1) } func (h *verifierStats) IncMessageParseFail() { From e19a2f7efca244fa91c36f5185ebbc68f9ec100e Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 7 Jan 2025 08:26:50 -0800 Subject: [PATCH 19/69] ci verification for go mod tidy (#736) Co-authored-by: Quentin McGaw --- .github/workflows/ci.yml | 4 ++++ go.mod | 2 +- go.sum | 4 ++-- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 48056c04f2..9b180a501d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,6 +84,10 @@ jobs: run: echo "TIMEOUT=1200s" >> "$GITHUB_ENV" - run: go mod download shell: bash + - name: go mod tidy + run: | + go mod tidy + git diff --exit-code - name: Mocks are up to date shell: bash run: | diff --git a/go.mod b/go.mod index 63146cd8d2..0b095d2f54 100644 --- a/go.mod +++ b/go.mod @@ -121,7 +121,7 @@ require ( go.opentelemetry.io/proto/otlp v1.0.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.26.0 // indirect - golang.org/x/mod v0.22.0 // indirect + golang.org/x/mod v0.18.0 // indirect golang.org/x/net v0.33.0 // indirect golang.org/x/term v0.27.0 // indirect gonum.org/v1/gonum v0.11.0 // indirect diff --git a/go.sum b/go.sum index 9391e7bb79..9c19c061be 100644 --- a/go.sum +++ b/go.sum @@ -641,8 +641,8 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4= -golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= +golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0= +golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= From 14e9d30374e4fc4586bbe8f4a0e5a8d01b69250f Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 7 Jan 2025 12:38:21 -0800 Subject: [PATCH 20/69] refactor: Split config package so it doesn't import core, core/vm (#734) Co-authored-by: Quentin McGaw --- plugin/evm/config.go | 21 +++++++++++ plugin/evm/config/config.go | 35 ++++++++++-------- plugin/evm/imports_test.go | 72 +++++++++++++++++++++++++++++++++++++ plugin/evm/vm.go | 4 +-- plugin/evm/vm_test.go | 4 +-- 5 files changed, 118 insertions(+), 18 deletions(-) create mode 100644 plugin/evm/config.go create mode 100644 plugin/evm/imports_test.go diff --git a/plugin/evm/config.go b/plugin/evm/config.go new file mode 100644 index 0000000000..5ad18aa2f2 --- /dev/null +++ b/plugin/evm/config.go @@ -0,0 +1,21 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package evm + +import ( + "github.com/ava-labs/coreth/core/txpool/legacypool" + "github.com/ava-labs/coreth/plugin/evm/config" +) + +// defaultTxPoolConfig uses [legacypool.DefaultConfig] to make a [config.TxPoolConfig] +// that can be passed to [config.Config.SetDefaults]. +var defaultTxPoolConfig = config.TxPoolConfig{ + PriceLimit: legacypool.DefaultConfig.PriceLimit, + PriceBump: legacypool.DefaultConfig.PriceBump, + AccountSlots: legacypool.DefaultConfig.AccountSlots, + GlobalSlots: legacypool.DefaultConfig.GlobalSlots, + AccountQueue: legacypool.DefaultConfig.AccountQueue, + GlobalQueue: legacypool.DefaultConfig.GlobalQueue, + Lifetime: legacypool.DefaultConfig.Lifetime, +} diff --git a/plugin/evm/config/config.go b/plugin/evm/config/config.go index a92405bcb5..f5bf644657 100644 --- a/plugin/evm/config/config.go +++ b/plugin/evm/config/config.go @@ -9,8 +9,6 @@ import ( "time" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/coreth/core/txpool/legacypool" - "github.com/ava-labs/coreth/eth" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/spf13/cast" @@ -224,28 +222,37 @@ type Config struct { HttpBodyLimit uint64 `json:"http-body-limit"` } +// TxPoolConfig contains the transaction pool config to be passed +// to [Config.SetDefaults]. +type TxPoolConfig struct { + PriceLimit uint64 + PriceBump uint64 + AccountSlots uint64 + GlobalSlots uint64 + AccountQueue uint64 + GlobalQueue uint64 + Lifetime time.Duration +} + // EthAPIs returns an array of strings representing the Eth APIs that should be enabled func (c Config) EthAPIs() []string { return c.EnabledEthAPIs } -func (c Config) EthBackendSettings() eth.Settings { - return eth.Settings{MaxBlocksPerRequest: c.MaxBlocksPerRequest} -} - -func (c *Config) SetDefaults() { +func (c *Config) SetDefaults(txPoolConfig TxPoolConfig) { c.EnabledEthAPIs = defaultEnabledAPIs c.RPCGasCap = defaultRpcGasCap c.RPCTxFeeCap = defaultRpcTxFeeCap c.MetricsExpensiveEnabled = defaultMetricsExpensiveEnabled - c.TxPoolPriceLimit = legacypool.DefaultConfig.PriceLimit - c.TxPoolPriceBump = legacypool.DefaultConfig.PriceBump - c.TxPoolAccountSlots = legacypool.DefaultConfig.AccountSlots - c.TxPoolGlobalSlots = legacypool.DefaultConfig.GlobalSlots - c.TxPoolAccountQueue = legacypool.DefaultConfig.AccountQueue - c.TxPoolGlobalQueue = legacypool.DefaultConfig.GlobalQueue - c.TxPoolLifetime.Duration = legacypool.DefaultConfig.Lifetime + // TxPool settings + c.TxPoolPriceLimit = txPoolConfig.PriceLimit + c.TxPoolPriceBump = txPoolConfig.PriceBump + c.TxPoolAccountSlots = txPoolConfig.AccountSlots + c.TxPoolGlobalSlots = txPoolConfig.GlobalSlots + c.TxPoolAccountQueue = txPoolConfig.AccountQueue + c.TxPoolGlobalQueue = txPoolConfig.GlobalQueue + c.TxPoolLifetime.Duration = txPoolConfig.Lifetime c.APIMaxDuration.Duration = defaultApiMaxDuration c.WSCPURefillRate.Duration = defaultWsCpuRefillRate diff --git a/plugin/evm/imports_test.go b/plugin/evm/imports_test.go new file mode 100644 index 0000000000..8b7ac4c4a9 --- /dev/null +++ b/plugin/evm/imports_test.go @@ -0,0 +1,72 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package evm + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" + "golang.org/x/tools/go/packages" +) + +// getDependencies takes a fully qualified package name and returns a map of all +// its recursive package imports (including itself) in the same format. +func getDependencies(packageName string) (map[string]struct{}, error) { + // Configure the load mode to include dependencies + cfg := &packages.Config{Mode: packages.NeedDeps | packages.NeedImports | packages.NeedName | packages.NeedModule} + pkgs, err := packages.Load(cfg, packageName) + if err != nil { + return nil, fmt.Errorf("failed to load package: %v", err) + } + + if len(pkgs) == 0 || pkgs[0].Errors != nil { + return nil, fmt.Errorf("failed to load package %s", packageName) + } + + deps := make(map[string]struct{}) + var collectDeps func(pkg *packages.Package) + collectDeps = func(pkg *packages.Package) { + if _, ok := deps[pkg.PkgPath]; ok { + return // Avoid re-processing the same dependency + } + deps[pkg.PkgPath] = struct{}{} + for _, dep := range pkg.Imports { + collectDeps(dep) + } + } + + // Start collecting dependencies + collectDeps(pkgs[0]) + return deps, nil +} + +func TestMustNotImport(t *testing.T) { + withRepo := func(pkg string) string { + const repo = "github.com/ava-labs/coreth" + return fmt.Sprintf("%s/%s", repo, pkg) + } + mustNotImport := map[string][]string{ + // The following sub-packages of plugin/evm must not import core, core/vm + // so clients (e.g., wallets, e2e tests) can import them without pulling in + // the entire VM logic. + // Importing these packages configures libevm globally and it is not + // possible to do so for both coreth and subnet-evm, where the client may + // wish to connect to multiple chains. + "plugin/evm/atomic": {"core", "core/vm"}, + "plugin/evm/client": {"core", "core/vm"}, + "plugin/evm/config": {"core", "core/vm"}, + } + + for packageName, forbiddenImports := range mustNotImport { + imports, err := getDependencies(withRepo(packageName)) + require.NoError(t, err) + + for _, forbiddenImport := range forbiddenImports { + fullForbiddenImport := withRepo(forbiddenImport) + _, found := imports[fullForbiddenImport] + require.False(t, found, "package %s must not import %s, check output of go list -f '{{ .Deps }}' \"%s\" ", packageName, fullForbiddenImport, withRepo(packageName)) + } + } +} diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 89c8ea4629..eebbd4a7ce 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -339,7 +339,7 @@ func (vm *VM) Initialize( fxs []*commonEng.Fx, appSender commonEng.AppSender, ) error { - vm.config.SetDefaults() + vm.config.SetDefaults(defaultTxPoolConfig) if len(configBytes) > 0 { if err := json.Unmarshal(configBytes, &vm.config); err != nil { return fmt.Errorf("failed to unmarshal config %s: %w", string(configBytes), err) @@ -660,7 +660,7 @@ func (vm *VM) initializeChain(lastAcceptedHash common.Hash) error { &vm.ethConfig, &EthPushGossiper{vm: vm}, vm.chaindb, - vm.config.EthBackendSettings(), + eth.Settings{MaxBlocksPerRequest: vm.config.MaxBlocksPerRequest}, lastAcceptedHash, dummy.NewFakerWithClock(callbacks, &vm.clock), &vm.clock, diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 2a79f3fb6f..507c8d3a94 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -402,7 +402,7 @@ func TestVMConfigDefaults(t *testing.T) { _, vm, _, _, _ := GenesisVM(t, false, "", configJSON, "") var vmConfig config.Config - vmConfig.SetDefaults() + vmConfig.SetDefaults(defaultTxPoolConfig) vmConfig.RPCTxFeeCap = txFeeCap vmConfig.EnabledEthAPIs = enabledEthAPIs require.Equal(t, vmConfig, vm.config, "VM Config should match default with overrides") @@ -414,7 +414,7 @@ func TestVMNilConfig(t *testing.T) { // VM Config should match defaults if no config is passed in var vmConfig config.Config - vmConfig.SetDefaults() + vmConfig.SetDefaults(defaultTxPoolConfig) require.Equal(t, vmConfig, vm.config, "VM Config should match default config") require.NoError(t, vm.Shutdown(context.Background())) } From 24e1459f44700530c0ea9ea5f30b5839843be433 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Thu, 9 Jan 2025 10:13:25 -0800 Subject: [PATCH 21/69] remove currentStateLock (#741) --- core/txpool/legacypool/legacypool.go | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/core/txpool/legacypool/legacypool.go b/core/txpool/legacypool/legacypool.go index f34701da78..51825da9e9 100644 --- a/core/txpool/legacypool/legacypool.go +++ b/core/txpool/legacypool/legacypool.go @@ -227,9 +227,6 @@ type LegacyPool struct { signer types.Signer mu sync.RWMutex - // [currentStateLock] is required to allow concurrent access to address nonces - // and balances during reorgs and gossip handling. - currentStateLock sync.Mutex // closed when the transaction pool is stopped. Any goroutine can listen // to this to be notified if it should shut down. generalShutdownChan chan struct{} @@ -685,9 +682,6 @@ func (pool *LegacyPool) validateTxBasics(tx *types.Transaction, local bool) erro // validateTx checks whether a transaction is valid according to the consensus // rules and adheres to some heuristic limits of the local node (price and size). func (pool *LegacyPool) validateTx(tx *types.Transaction, local bool) error { - pool.currentStateLock.Lock() - defer pool.currentStateLock.Unlock() - opts := &txpool.ValidationOptionsWithState{ State: pool.currentState, Rules: pool.chainconfig.Rules( @@ -1500,9 +1494,7 @@ func (pool *LegacyPool) reset(oldHead, newHead *types.Header) { return } pool.currentHead.Store(newHead) - pool.currentStateLock.Lock() pool.currentState = statedb - pool.currentStateLock.Unlock() pool.pendingNonces = newNoncer(statedb) // Inject any transactions discarded due to reorgs @@ -1515,9 +1507,6 @@ func (pool *LegacyPool) reset(oldHead, newHead *types.Header) { // future queue to the set of pending transactions. During this process, all // invalidated transactions (low nonce, low balance) are deleted. func (pool *LegacyPool) promoteExecutables(accounts []common.Address) []*types.Transaction { - pool.currentStateLock.Lock() - defer pool.currentStateLock.Unlock() - // Track the promoted transactions to broadcast them at once var promoted []*types.Transaction @@ -1724,9 +1713,6 @@ func (pool *LegacyPool) truncateQueue() { // is always explicitly triggered by SetBaseFee and it would be unnecessary and wasteful // to trigger a re-heap is this function func (pool *LegacyPool) demoteUnexecutables() { - pool.currentStateLock.Lock() - defer pool.currentStateLock.Unlock() - // Iterate over all accounts and demote any non-executable transactions gasLimit := pool.currentHead.Load().GasLimit for addr, list := range pool.pending { From b6b4dfbc4bfc7f17e4cfe5f3c0fb44944176c884 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Thu, 9 Jan 2025 10:28:46 -0800 Subject: [PATCH 22/69] atomic syncer: simplify interface (#735) Co-authored-by: Ceyhun Onur --- plugin/evm/atomic_backend.go | 11 ----------- plugin/evm/atomic_syncer.go | 5 ++--- plugin/evm/atomic_syncer_test.go | 4 ++-- plugin/evm/syncervm_client.go | 9 ++++++++- 4 files changed, 12 insertions(+), 17 deletions(-) diff --git a/plugin/evm/atomic_backend.go b/plugin/evm/atomic_backend.go index 2420021d6f..45afa707f2 100644 --- a/plugin/evm/atomic_backend.go +++ b/plugin/evm/atomic_backend.go @@ -17,7 +17,6 @@ import ( "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/coreth/plugin/evm/atomic" - syncclient "github.com/ava-labs/coreth/sync/client" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" ) @@ -57,10 +56,6 @@ type AtomicBackend interface { // will not have been executed on shared memory. MarkApplyToSharedMemoryCursor(previousLastAcceptedHeight uint64) error - // Syncer creates and returns a new Syncer object that can be used to sync the - // state of the atomic trie from peers - Syncer(client syncclient.LeafClient, targetRoot common.Hash, targetHeight uint64, requestSize uint16) (Syncer, error) - // SetLastAccepted is used after state-sync to reset the last accepted block. SetLastAccepted(lastAcceptedHash common.Hash) @@ -356,12 +351,6 @@ func (a *atomicBackend) MarkApplyToSharedMemoryCursor(previousLastAcceptedHeight return database.PutUInt64(a.metadataDB, appliedSharedMemoryCursorKey, previousLastAcceptedHeight+1) } -// Syncer creates and returns a new Syncer object that can be used to sync the -// state of the atomic trie from peers -func (a *atomicBackend) Syncer(client syncclient.LeafClient, targetRoot common.Hash, targetHeight uint64, requestSize uint16) (Syncer, error) { - return newAtomicSyncer(client, a, targetRoot, targetHeight, requestSize) -} - func (a *atomicBackend) GetVerifiedAtomicState(blockHash common.Hash) (AtomicState, error) { if state, ok := a.verifiedRoots[blockHash]; ok { return state, nil diff --git a/plugin/evm/atomic_syncer.go b/plugin/evm/atomic_syncer.go index d68d61d597..8c435690c0 100644 --- a/plugin/evm/atomic_syncer.go +++ b/plugin/evm/atomic_syncer.go @@ -50,8 +50,7 @@ func addZeroes(height uint64) []byte { return packer.Bytes } -func newAtomicSyncer(client syncclient.LeafClient, atomicBackend *atomicBackend, targetRoot common.Hash, targetHeight uint64, requestSize uint16) (*atomicSyncer, error) { - atomicTrie := atomicBackend.AtomicTrie() +func newAtomicSyncer(client syncclient.LeafClient, vdb *versiondb.Database, atomicTrie AtomicTrie, targetRoot common.Hash, targetHeight uint64, requestSize uint16) (*atomicSyncer, error) { lastCommittedRoot, lastCommit := atomicTrie.LastCommitted() trie, err := atomicTrie.OpenTrie(lastCommittedRoot) if err != nil { @@ -59,7 +58,7 @@ func newAtomicSyncer(client syncclient.LeafClient, atomicBackend *atomicBackend, } atomicSyncer := &atomicSyncer{ - db: atomicBackend.db, + db: vdb, atomicTrie: atomicTrie, trie: trie, targetRoot: targetRoot, diff --git a/plugin/evm/atomic_syncer_test.go b/plugin/evm/atomic_syncer_test.go index 86589cc4d8..3feffe444c 100644 --- a/plugin/evm/atomic_syncer_test.go +++ b/plugin/evm/atomic_syncer_test.go @@ -65,7 +65,7 @@ func testAtomicSyncer(t *testing.T, serverTrieDB *triedb.Database, targetHeight // next trie. for i, checkpoint := range checkpoints { // Create syncer targeting the current [syncTrie]. - syncer, err := atomicBackend.Syncer(mockClient, targetRoot, targetHeight, config.DefaultStateSyncRequestSize) + syncer, err := newAtomicSyncer(mockClient, clientDB, atomicBackend.AtomicTrie(), targetRoot, targetHeight, config.DefaultStateSyncRequestSize) if err != nil { t.Fatal(err) } @@ -92,7 +92,7 @@ func testAtomicSyncer(t *testing.T, serverTrieDB *triedb.Database, targetHeight } // Create syncer targeting the current [targetRoot]. - syncer, err := atomicBackend.Syncer(mockClient, targetRoot, targetHeight, config.DefaultStateSyncRequestSize) + syncer, err := newAtomicSyncer(mockClient, clientDB, atomicBackend.AtomicTrie(), targetRoot, targetHeight, config.DefaultStateSyncRequestSize) if err != nil { t.Fatal(err) } diff --git a/plugin/evm/syncervm_client.go b/plugin/evm/syncervm_client.go index 0b704d6233..c25f68c46b 100644 --- a/plugin/evm/syncervm_client.go +++ b/plugin/evm/syncervm_client.go @@ -276,7 +276,14 @@ func (client *stateSyncerClient) syncBlocks(ctx context.Context, fromHash common func (client *stateSyncerClient) syncAtomicTrie(ctx context.Context) error { log.Info("atomic tx: sync starting", "root", client.syncSummary.AtomicRoot) - atomicSyncer, err := client.atomicBackend.Syncer(client.client, client.syncSummary.AtomicRoot, client.syncSummary.BlockNumber, client.stateSyncRequestSize) + atomicSyncer, err := newAtomicSyncer( + client.client, + client.db, + client.atomicBackend.AtomicTrie(), + client.syncSummary.AtomicRoot, + client.syncSummary.BlockNumber, + client.stateSyncRequestSize, + ) if err != nil { return err } From 50138514f84f4b2f2968c84bd498852f6b65a0b0 Mon Sep 17 00:00:00 2001 From: Quentin McGaw Date: Wed, 15 Jan 2025 16:28:22 +0100 Subject: [PATCH 23/69] feat(internal/ethapi)!: reject `eth_getProof` queries for historical blocks (#719) - default behavior for pruning mode to reject blocks before the 32 blocks preceding the last accepted block - default behavior for archive mode to reject blocks before ~24h worth of blocks preceding the last accepted block - archive mode new option `historical-proof-query-window` to customize the blocks window, or set it to 0 to accept any block number --- RELEASES.md | 4 + core/state_manager.go | 6 +- core/state_manager_test.go | 6 +- eth/api_backend.go | 15 + eth/backend.go | 11 +- eth/ethconfig/config.go | 5 + internal/ethapi/api.go | 7 + internal/ethapi/api_extra.go | 39 ++ internal/ethapi/api_extra_test.go | 132 +++++ internal/ethapi/api_test.go | 6 + internal/ethapi/backend.go | 2 + internal/ethapi/mocks_generate_test.go | 3 + internal/ethapi/mocks_test.go | 757 +++++++++++++++++++++++++ plugin/evm/config/config.go | 8 + plugin/evm/vm.go | 1 + 15 files changed, 991 insertions(+), 11 deletions(-) create mode 100644 internal/ethapi/api_extra_test.go create mode 100644 internal/ethapi/mocks_generate_test.go create mode 100644 internal/ethapi/mocks_test.go diff --git a/RELEASES.md b/RELEASES.md index bce253816e..4dd80d2d21 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,6 +1,10 @@ # Release Notes ## [v0.14.1](https://github.com/ava-labs/coreth/releases/tag/v0.14.1) + +- IMPORTANT: `eth_getProof` calls for historical state will be rejected by default. + - On archive nodes (`"pruning-enabled": false`): queries for historical proofs for state older than approximately 24 hours preceding the last accepted block will be rejected by default. This can be adjusted with the new option `historical-proof-query-window` which defines the number of blocks before the last accepted block which should be accepted for state proof queries, or set to `0` to accept any block number state query (previous behavior). + - On `pruning` nodes: queries for proofs past the tip buffer (32 blocks) will be rejected. This is in support of moving to a path based storage scheme, which does not support historical state proofs. - Remove API eth_getAssetBalance that was used to query ANT balances (deprecated since v0.10.0) - Remove legacy gossip handler and metrics (deprecated since v0.10.0) - Refactored trie_prefetcher.go to be structurally similar to [upstream](https://github.com/ethereum/go-ethereum/tree/v1.13.14). diff --git a/core/state_manager.go b/core/state_manager.go index 8fc7de11c3..59447055b7 100644 --- a/core/state_manager.go +++ b/core/state_manager.go @@ -41,12 +41,12 @@ func init() { } const ( - // tipBufferSize is the number of recent accepted tries to keep in the TrieDB + // TipBufferSize is the number of recent accepted tries to keep in the TrieDB // dirties cache at tip (only applicable in [pruning] mode). // // Keeping extra tries around at tip enables clients to query data from // recent trie roots. - tipBufferSize = 32 + TipBufferSize = 32 // flushWindow is the distance to the [commitInterval] when we start // optimistically flushing trie nodes to disk (only applicable in [pruning] @@ -79,7 +79,7 @@ func NewTrieWriter(db TrieDB, config *CacheConfig) TrieWriter { targetCommitSize: common.StorageSize(config.TrieDirtyCommitTarget) * 1024 * 1024, imageCap: 4 * 1024 * 1024, commitInterval: config.CommitInterval, - tipBuffer: NewBoundedBuffer(tipBufferSize, db.Dereference), + tipBuffer: NewBoundedBuffer(TipBufferSize, db.Dereference), } cm.flushStepSize = (cm.memoryCap - cm.targetCommitSize) / common.StorageSize(flushWindow) return cm diff --git a/core/state_manager_test.go b/core/state_manager_test.go index 2fb47add49..cddb0a6dd8 100644 --- a/core/state_manager_test.go +++ b/core/state_manager_test.go @@ -53,10 +53,10 @@ func TestCappedMemoryTrieWriter(t *testing.T) { assert.Equal(common.Hash{}, m.LastCommit, "should not have committed block on insert") w.AcceptTrie(block) - if i <= tipBufferSize { + if i <= TipBufferSize { assert.Equal(common.Hash{}, m.LastDereference, "should not have dereferenced block on accept") } else { - assert.Equal(common.BigToHash(big.NewInt(int64(i-tipBufferSize))), m.LastDereference, "should have dereferenced old block on last accept") + assert.Equal(common.BigToHash(big.NewInt(int64(i-TipBufferSize))), m.LastDereference, "should have dereferenced old block on last accept") m.LastDereference = common.Hash{} } if i < int(cacheConfig.CommitInterval) { @@ -77,7 +77,7 @@ func TestNoPruningTrieWriter(t *testing.T) { m := &MockTrieDB{} w := NewTrieWriter(m, &CacheConfig{}) assert := assert.New(t) - for i := 0; i < tipBufferSize+1; i++ { + for i := 0; i < TipBufferSize+1; i++ { bigI := big.NewInt(int64(i)) block := types.NewBlock( &types.Header{ diff --git a/eth/api_backend.go b/eth/api_backend.go index b66c4b5415..bf6b578780 100644 --- a/eth/api_backend.go +++ b/eth/api_backend.go @@ -60,6 +60,10 @@ type EthAPIBackend struct { allowUnfinalizedQueries bool eth *Ethereum gpo *gasprice.Oracle + + // historicalProofQueryWindow is the number of blocks before the last accepted block to be accepted for + // state queries when running archive mode. + historicalProofQueryWindow uint64 } // ChainConfig returns the active chain configuration. @@ -67,6 +71,17 @@ func (b *EthAPIBackend) ChainConfig() *params.ChainConfig { return b.eth.blockchain.Config() } +// IsArchive returns true if the node is running in archive mode, false otherwise. +func (b *EthAPIBackend) IsArchive() bool { + return !b.eth.config.Pruning +} + +// HistoricalProofQueryWindow returns the number of blocks before the last accepted block to be accepted for state queries. +// It returns 0 to indicate to accept any block number for state queries. +func (b *EthAPIBackend) HistoricalProofQueryWindow() uint64 { + return b.historicalProofQueryWindow +} + func (b *EthAPIBackend) IsAllowUnfinalizedQueries() bool { return b.allowUnfinalizedQueries } diff --git a/eth/backend.go b/eth/backend.go index 480730d5d3..79dce86db3 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -263,11 +263,12 @@ func New( } eth.APIBackend = &EthAPIBackend{ - extRPCEnabled: stack.Config().ExtRPCEnabled(), - allowUnprotectedTxs: config.AllowUnprotectedTxs, - allowUnprotectedTxHashes: allowUnprotectedTxHashes, - allowUnfinalizedQueries: config.AllowUnfinalizedQueries, - eth: eth, + extRPCEnabled: stack.Config().ExtRPCEnabled(), + allowUnprotectedTxs: config.AllowUnprotectedTxs, + allowUnprotectedTxHashes: allowUnprotectedTxHashes, + allowUnfinalizedQueries: config.AllowUnfinalizedQueries, + historicalProofQueryWindow: config.HistoricalProofQueryWindow, + eth: eth, } if config.AllowUnprotectedTxs { log.Info("Unprotected transactions allowed") diff --git a/eth/ethconfig/config.go b/eth/ethconfig/config.go index e82d73d4e2..f7697112ef 100644 --- a/eth/ethconfig/config.go +++ b/eth/ethconfig/config.go @@ -137,6 +137,11 @@ type Config struct { // AllowUnfinalizedQueries allow unfinalized queries AllowUnfinalizedQueries bool + // HistoricalProofQueryWindow is the number of blocks before the last accepted block to be accepted for state queries. + // For archive nodes, it defaults to 43200 and can be set to 0 to indicate to accept any block query. + // For non-archive nodes, it is forcibly set to the value of [core.TipBufferSize]. + HistoricalProofQueryWindow uint64 + // AllowUnprotectedTxs allow unprotected transactions to be locally issued. // Unprotected transactions are transactions that are signed without EIP-155 // replay protection. diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 93aadbe14c..9e7ad54dde 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -676,7 +676,14 @@ func (n *proofList) Delete(key []byte) error { } // GetProof returns the Merkle-proof for a given account and optionally some storage keys. +// If the requested block is part of historical blocks and the node does not accept +// getting proofs for historical blocks, an error is returned. func (s *BlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) { + err := s.stateQueryBlockNumberAllowed(blockNrOrHash) + if err != nil { + return nil, fmt.Errorf("historical proof query not allowed: %s", err) + } + var ( keys = make([]common.Hash, len(storageKeys)) keyLengths = make([]int, len(storageKeys)) diff --git a/internal/ethapi/api_extra.go b/internal/ethapi/api_extra.go index a56830988f..63cf84f48e 100644 --- a/internal/ethapi/api_extra.go +++ b/internal/ethapi/api_extra.go @@ -92,3 +92,42 @@ func (s *BlockChainAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, erro } return results, nil } + +// stateQueryBlockNumberAllowed returns a nil error if: +// - the node is configured to accept any state query (the query window is zero) +// - the block given has its number within the query window before the last accepted block. +// This query window is set to [core.TipBufferSize] when running in a non-archive mode. +// +// Otherwise, it returns a non-nil error containing block number information. +func (s *BlockChainAPI) stateQueryBlockNumberAllowed(blockNumOrHash rpc.BlockNumberOrHash) (err error) { + queryWindow := uint64(core.TipBufferSize) + if s.b.IsArchive() { + queryWindow = s.b.HistoricalProofQueryWindow() + if queryWindow == 0 { + return nil + } + } + + lastAcceptedNumber := s.b.LastAcceptedBlock().NumberU64() + + var number uint64 + if blockNumOrHash.BlockNumber != nil { + number = uint64(blockNumOrHash.BlockNumber.Int64()) + } else { + block, err := s.b.BlockByNumberOrHash(context.Background(), blockNumOrHash) + if err != nil { + return fmt.Errorf("failed to get block from hash: %s", err) + } + number = block.NumberU64() + } + + var oldestAllowed uint64 + if lastAcceptedNumber > queryWindow { + oldestAllowed = lastAcceptedNumber - queryWindow + } + if number >= oldestAllowed { + return nil + } + return fmt.Errorf("block number %d is before the oldest allowed block number %d (window of %d blocks)", + number, oldestAllowed, queryWindow) +} diff --git a/internal/ethapi/api_extra_test.go b/internal/ethapi/api_extra_test.go new file mode 100644 index 0000000000..28843b4cb6 --- /dev/null +++ b/internal/ethapi/api_extra_test.go @@ -0,0 +1,132 @@ +// (c) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package ethapi + +import ( + "fmt" + "math/big" + "testing" + + "github.com/ava-labs/coreth/core/types" + "github.com/ava-labs/coreth/rpc" + "github.com/ethereum/go-ethereum/common" + "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" +) + +func TestBlockChainAPI_stateQueryBlockNumberAllowed(t *testing.T) { + t.Parallel() + + const queryWindow uint64 = 1024 + + makeBlockWithNumber := func(number uint64) *types.Block { + header := &types.Header{ + Number: big.NewInt(int64(number)), + } + return types.NewBlock(header, nil, nil, nil, nil) + } + + testCases := map[string]struct { + blockNumOrHash rpc.BlockNumberOrHash + makeBackend func(ctrl *gomock.Controller) *MockBackend + wantErrMessage string + }{ + "zero_query_window": { + blockNumOrHash: rpc.BlockNumberOrHashWithNumber(rpc.BlockNumber(1000)), + makeBackend: func(ctrl *gomock.Controller) *MockBackend { + backend := NewMockBackend(ctrl) + backend.EXPECT().IsArchive().Return(true) + backend.EXPECT().HistoricalProofQueryWindow().Return(uint64(0)) + return backend + }, + }, + "block_number_allowed_below_window": { + blockNumOrHash: rpc.BlockNumberOrHashWithNumber(rpc.BlockNumber(1000)), + makeBackend: func(ctrl *gomock.Controller) *MockBackend { + backend := NewMockBackend(ctrl) + backend.EXPECT().IsArchive().Return(true) + backend.EXPECT().HistoricalProofQueryWindow().Return(queryWindow) + backend.EXPECT().LastAcceptedBlock().Return(makeBlockWithNumber(1020)) + return backend + }, + }, + "block_number_allowed": { + blockNumOrHash: rpc.BlockNumberOrHashWithNumber(rpc.BlockNumber(2000)), + makeBackend: func(ctrl *gomock.Controller) *MockBackend { + backend := NewMockBackend(ctrl) + backend.EXPECT().IsArchive().Return(true) + backend.EXPECT().HistoricalProofQueryWindow().Return(queryWindow) + backend.EXPECT().LastAcceptedBlock().Return(makeBlockWithNumber(2200)) + return backend + }, + }, + "block_number_allowed_by_hash": { + blockNumOrHash: rpc.BlockNumberOrHashWithHash(common.Hash{99}, false), + makeBackend: func(ctrl *gomock.Controller) *MockBackend { + backend := NewMockBackend(ctrl) + backend.EXPECT().IsArchive().Return(true) + backend.EXPECT().HistoricalProofQueryWindow().Return(queryWindow) + backend.EXPECT().LastAcceptedBlock().Return(makeBlockWithNumber(2200)) + backend.EXPECT(). + BlockByNumberOrHash(gomock.Any(), gomock.Any()). + Return(makeBlockWithNumber(2000), nil) + return backend + }, + }, + "block_number_allowed_by_hash_error": { + blockNumOrHash: rpc.BlockNumberOrHashWithHash(common.Hash{99}, false), + makeBackend: func(ctrl *gomock.Controller) *MockBackend { + backend := NewMockBackend(ctrl) + backend.EXPECT().IsArchive().Return(true) + backend.EXPECT().HistoricalProofQueryWindow().Return(queryWindow) + backend.EXPECT().LastAcceptedBlock().Return(makeBlockWithNumber(2200)) + backend.EXPECT(). + BlockByNumberOrHash(gomock.Any(), gomock.Any()). + Return(nil, fmt.Errorf("test error")) + return backend + }, + wantErrMessage: "failed to get block from hash: test error", + }, + "block_number_out_of_window": { + blockNumOrHash: rpc.BlockNumberOrHashWithNumber(rpc.BlockNumber(1000)), + makeBackend: func(ctrl *gomock.Controller) *MockBackend { + backend := NewMockBackend(ctrl) + backend.EXPECT().IsArchive().Return(true) + backend.EXPECT().HistoricalProofQueryWindow().Return(queryWindow) + backend.EXPECT().LastAcceptedBlock().Return(makeBlockWithNumber(2200)) + return backend + }, + wantErrMessage: "block number 1000 is before the oldest allowed block number 1176 (window of 1024 blocks)", + }, + "block_number_out_of_window_non_archive": { + blockNumOrHash: rpc.BlockNumberOrHashWithNumber(rpc.BlockNumber(1000)), + makeBackend: func(ctrl *gomock.Controller) *MockBackend { + backend := NewMockBackend(ctrl) + backend.EXPECT().IsArchive().Return(false) + // query window is 32 as set to core.TipBufferSize + backend.EXPECT().LastAcceptedBlock().Return(makeBlockWithNumber(1033)) + return backend + }, + wantErrMessage: "block number 1000 is before the oldest allowed block number 1001 (window of 32 blocks)", + }, + } + + for name, testCase := range testCases { + t.Run(name, func(t *testing.T) { + t.Parallel() + ctrl := gomock.NewController(t) + + api := &BlockChainAPI{ + b: testCase.makeBackend(ctrl), + } + + err := api.stateQueryBlockNumberAllowed(testCase.blockNumOrHash) + if testCase.wantErrMessage == "" { + assert.NoError(t, err) + } else { + assert.EqualError(t, err, testCase.wantErrMessage) + } + }) + } +} diff --git a/internal/ethapi/api_test.go b/internal/ethapi/api_test.go index 87a7176026..f76c5dff49 100644 --- a/internal/ethapi/api_test.go +++ b/internal/ethapi/api_test.go @@ -625,6 +625,12 @@ func (b testBackend) LastAcceptedBlock() *types.Block { panic("implement me") } func (b testBackend) SuggestPrice(ctx context.Context) (*big.Int, error) { panic("implement me") } +func (b testBackend) IsArchive() bool { + panic("implement me") +} +func (b testBackend) HistoricalProofQueryWindow() (queryWindow uint64) { + panic("implement me") +} func TestEstimateGas(t *testing.T) { t.Parallel() diff --git a/internal/ethapi/backend.go b/internal/ethapi/backend.go index accfda57aa..473a5eda11 100644 --- a/internal/ethapi/backend.go +++ b/internal/ethapi/backend.go @@ -80,6 +80,8 @@ type Backend interface { SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription BadBlocks() ([]*types.Block, []*core.BadBlockReason) + IsArchive() bool + HistoricalProofQueryWindow() uint64 // Transaction pool API SendTx(ctx context.Context, signedTx *types.Transaction) error diff --git a/internal/ethapi/mocks_generate_test.go b/internal/ethapi/mocks_generate_test.go new file mode 100644 index 0000000000..7784142351 --- /dev/null +++ b/internal/ethapi/mocks_generate_test.go @@ -0,0 +1,3 @@ +package ethapi + +//go:generate go run go.uber.org/mock/mockgen -package=$GOPACKAGE -destination=mocks_test.go . Backend diff --git a/internal/ethapi/mocks_test.go b/internal/ethapi/mocks_test.go new file mode 100644 index 0000000000..95b2ca4985 --- /dev/null +++ b/internal/ethapi/mocks_test.go @@ -0,0 +1,757 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/coreth/internal/ethapi (interfaces: Backend) +// +// Generated by this command: +// +// mockgen -package=ethapi -destination=mocks_test.go . Backend +// + +// Package ethapi is a generated GoMock package. +package ethapi + +import ( + context "context" + big "math/big" + reflect "reflect" + time "time" + + accounts "github.com/ava-labs/coreth/accounts" + consensus "github.com/ava-labs/coreth/consensus" + core "github.com/ava-labs/coreth/core" + bloombits "github.com/ava-labs/coreth/core/bloombits" + state "github.com/ava-labs/coreth/core/state" + types "github.com/ava-labs/coreth/core/types" + vm "github.com/ava-labs/coreth/core/vm" + params "github.com/ava-labs/coreth/params" + rpc "github.com/ava-labs/coreth/rpc" + common "github.com/ethereum/go-ethereum/common" + ethdb "github.com/ethereum/go-ethereum/ethdb" + event "github.com/ethereum/go-ethereum/event" + gomock "go.uber.org/mock/gomock" +) + +// MockBackend is a mock of Backend interface. +type MockBackend struct { + ctrl *gomock.Controller + recorder *MockBackendMockRecorder + isgomock struct{} +} + +// MockBackendMockRecorder is the mock recorder for MockBackend. +type MockBackendMockRecorder struct { + mock *MockBackend +} + +// NewMockBackend creates a new mock instance. +func NewMockBackend(ctrl *gomock.Controller) *MockBackend { + mock := &MockBackend{ctrl: ctrl} + mock.recorder = &MockBackendMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockBackend) EXPECT() *MockBackendMockRecorder { + return m.recorder +} + +// AccountManager mocks base method. +func (m *MockBackend) AccountManager() *accounts.Manager { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AccountManager") + ret0, _ := ret[0].(*accounts.Manager) + return ret0 +} + +// AccountManager indicates an expected call of AccountManager. +func (mr *MockBackendMockRecorder) AccountManager() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AccountManager", reflect.TypeOf((*MockBackend)(nil).AccountManager)) +} + +// BadBlocks mocks base method. +func (m *MockBackend) BadBlocks() ([]*types.Block, []*core.BadBlockReason) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BadBlocks") + ret0, _ := ret[0].([]*types.Block) + ret1, _ := ret[1].([]*core.BadBlockReason) + return ret0, ret1 +} + +// BadBlocks indicates an expected call of BadBlocks. +func (mr *MockBackendMockRecorder) BadBlocks() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BadBlocks", reflect.TypeOf((*MockBackend)(nil).BadBlocks)) +} + +// BlockByHash mocks base method. +func (m *MockBackend) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BlockByHash", ctx, hash) + ret0, _ := ret[0].(*types.Block) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// BlockByHash indicates an expected call of BlockByHash. +func (mr *MockBackendMockRecorder) BlockByHash(ctx, hash any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockByHash", reflect.TypeOf((*MockBackend)(nil).BlockByHash), ctx, hash) +} + +// BlockByNumber mocks base method. +func (m *MockBackend) BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BlockByNumber", ctx, number) + ret0, _ := ret[0].(*types.Block) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// BlockByNumber indicates an expected call of BlockByNumber. +func (mr *MockBackendMockRecorder) BlockByNumber(ctx, number any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockByNumber", reflect.TypeOf((*MockBackend)(nil).BlockByNumber), ctx, number) +} + +// BlockByNumberOrHash mocks base method. +func (m *MockBackend) BlockByNumberOrHash(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (*types.Block, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BlockByNumberOrHash", ctx, blockNrOrHash) + ret0, _ := ret[0].(*types.Block) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// BlockByNumberOrHash indicates an expected call of BlockByNumberOrHash. +func (mr *MockBackendMockRecorder) BlockByNumberOrHash(ctx, blockNrOrHash any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockByNumberOrHash", reflect.TypeOf((*MockBackend)(nil).BlockByNumberOrHash), ctx, blockNrOrHash) +} + +// BloomStatus mocks base method. +func (m *MockBackend) BloomStatus() (uint64, uint64) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BloomStatus") + ret0, _ := ret[0].(uint64) + ret1, _ := ret[1].(uint64) + return ret0, ret1 +} + +// BloomStatus indicates an expected call of BloomStatus. +func (mr *MockBackendMockRecorder) BloomStatus() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BloomStatus", reflect.TypeOf((*MockBackend)(nil).BloomStatus)) +} + +// ChainConfig mocks base method. +func (m *MockBackend) ChainConfig() *params.ChainConfig { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ChainConfig") + ret0, _ := ret[0].(*params.ChainConfig) + return ret0 +} + +// ChainConfig indicates an expected call of ChainConfig. +func (mr *MockBackendMockRecorder) ChainConfig() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ChainConfig", reflect.TypeOf((*MockBackend)(nil).ChainConfig)) +} + +// ChainDb mocks base method. +func (m *MockBackend) ChainDb() ethdb.Database { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ChainDb") + ret0, _ := ret[0].(ethdb.Database) + return ret0 +} + +// ChainDb indicates an expected call of ChainDb. +func (mr *MockBackendMockRecorder) ChainDb() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ChainDb", reflect.TypeOf((*MockBackend)(nil).ChainDb)) +} + +// CurrentBlock mocks base method. +func (m *MockBackend) CurrentBlock() *types.Header { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CurrentBlock") + ret0, _ := ret[0].(*types.Header) + return ret0 +} + +// CurrentBlock indicates an expected call of CurrentBlock. +func (mr *MockBackendMockRecorder) CurrentBlock() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CurrentBlock", reflect.TypeOf((*MockBackend)(nil).CurrentBlock)) +} + +// CurrentHeader mocks base method. +func (m *MockBackend) CurrentHeader() *types.Header { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CurrentHeader") + ret0, _ := ret[0].(*types.Header) + return ret0 +} + +// CurrentHeader indicates an expected call of CurrentHeader. +func (mr *MockBackendMockRecorder) CurrentHeader() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CurrentHeader", reflect.TypeOf((*MockBackend)(nil).CurrentHeader)) +} + +// Engine mocks base method. +func (m *MockBackend) Engine() consensus.Engine { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Engine") + ret0, _ := ret[0].(consensus.Engine) + return ret0 +} + +// Engine indicates an expected call of Engine. +func (mr *MockBackendMockRecorder) Engine() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Engine", reflect.TypeOf((*MockBackend)(nil).Engine)) +} + +// EstimateBaseFee mocks base method. +func (m *MockBackend) EstimateBaseFee(ctx context.Context) (*big.Int, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "EstimateBaseFee", ctx) + ret0, _ := ret[0].(*big.Int) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// EstimateBaseFee indicates an expected call of EstimateBaseFee. +func (mr *MockBackendMockRecorder) EstimateBaseFee(ctx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EstimateBaseFee", reflect.TypeOf((*MockBackend)(nil).EstimateBaseFee), ctx) +} + +// ExtRPCEnabled mocks base method. +func (m *MockBackend) ExtRPCEnabled() bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ExtRPCEnabled") + ret0, _ := ret[0].(bool) + return ret0 +} + +// ExtRPCEnabled indicates an expected call of ExtRPCEnabled. +func (mr *MockBackendMockRecorder) ExtRPCEnabled() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExtRPCEnabled", reflect.TypeOf((*MockBackend)(nil).ExtRPCEnabled)) +} + +// FeeHistory mocks base method. +func (m *MockBackend) FeeHistory(ctx context.Context, blockCount uint64, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*big.Int, [][]*big.Int, []*big.Int, []float64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FeeHistory", ctx, blockCount, lastBlock, rewardPercentiles) + ret0, _ := ret[0].(*big.Int) + ret1, _ := ret[1].([][]*big.Int) + ret2, _ := ret[2].([]*big.Int) + ret3, _ := ret[3].([]float64) + ret4, _ := ret[4].(error) + return ret0, ret1, ret2, ret3, ret4 +} + +// FeeHistory indicates an expected call of FeeHistory. +func (mr *MockBackendMockRecorder) FeeHistory(ctx, blockCount, lastBlock, rewardPercentiles any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FeeHistory", reflect.TypeOf((*MockBackend)(nil).FeeHistory), ctx, blockCount, lastBlock, rewardPercentiles) +} + +// GetBody mocks base method. +func (m *MockBackend) GetBody(ctx context.Context, hash common.Hash, number rpc.BlockNumber) (*types.Body, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetBody", ctx, hash, number) + ret0, _ := ret[0].(*types.Body) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetBody indicates an expected call of GetBody. +func (mr *MockBackendMockRecorder) GetBody(ctx, hash, number any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBody", reflect.TypeOf((*MockBackend)(nil).GetBody), ctx, hash, number) +} + +// GetEVM mocks base method. +func (m *MockBackend) GetEVM(ctx context.Context, msg *core.Message, state *state.StateDB, header *types.Header, vmConfig *vm.Config, blockCtx *vm.BlockContext) *vm.EVM { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetEVM", ctx, msg, state, header, vmConfig, blockCtx) + ret0, _ := ret[0].(*vm.EVM) + return ret0 +} + +// GetEVM indicates an expected call of GetEVM. +func (mr *MockBackendMockRecorder) GetEVM(ctx, msg, state, header, vmConfig, blockCtx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetEVM", reflect.TypeOf((*MockBackend)(nil).GetEVM), ctx, msg, state, header, vmConfig, blockCtx) +} + +// GetLogs mocks base method. +func (m *MockBackend) GetLogs(ctx context.Context, blockHash common.Hash, number uint64) ([][]*types.Log, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetLogs", ctx, blockHash, number) + ret0, _ := ret[0].([][]*types.Log) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetLogs indicates an expected call of GetLogs. +func (mr *MockBackendMockRecorder) GetLogs(ctx, blockHash, number any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLogs", reflect.TypeOf((*MockBackend)(nil).GetLogs), ctx, blockHash, number) +} + +// GetPoolNonce mocks base method. +func (m *MockBackend) GetPoolNonce(ctx context.Context, addr common.Address) (uint64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPoolNonce", ctx, addr) + ret0, _ := ret[0].(uint64) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPoolNonce indicates an expected call of GetPoolNonce. +func (mr *MockBackendMockRecorder) GetPoolNonce(ctx, addr any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPoolNonce", reflect.TypeOf((*MockBackend)(nil).GetPoolNonce), ctx, addr) +} + +// GetPoolTransaction mocks base method. +func (m *MockBackend) GetPoolTransaction(txHash common.Hash) *types.Transaction { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPoolTransaction", txHash) + ret0, _ := ret[0].(*types.Transaction) + return ret0 +} + +// GetPoolTransaction indicates an expected call of GetPoolTransaction. +func (mr *MockBackendMockRecorder) GetPoolTransaction(txHash any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPoolTransaction", reflect.TypeOf((*MockBackend)(nil).GetPoolTransaction), txHash) +} + +// GetPoolTransactions mocks base method. +func (m *MockBackend) GetPoolTransactions() (types.Transactions, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPoolTransactions") + ret0, _ := ret[0].(types.Transactions) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPoolTransactions indicates an expected call of GetPoolTransactions. +func (mr *MockBackendMockRecorder) GetPoolTransactions() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPoolTransactions", reflect.TypeOf((*MockBackend)(nil).GetPoolTransactions)) +} + +// GetReceipts mocks base method. +func (m *MockBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetReceipts", ctx, hash) + ret0, _ := ret[0].(types.Receipts) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetReceipts indicates an expected call of GetReceipts. +func (mr *MockBackendMockRecorder) GetReceipts(ctx, hash any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetReceipts", reflect.TypeOf((*MockBackend)(nil).GetReceipts), ctx, hash) +} + +// GetTransaction mocks base method. +func (m *MockBackend) GetTransaction(ctx context.Context, txHash common.Hash) (bool, *types.Transaction, common.Hash, uint64, uint64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTransaction", ctx, txHash) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(*types.Transaction) + ret2, _ := ret[2].(common.Hash) + ret3, _ := ret[3].(uint64) + ret4, _ := ret[4].(uint64) + ret5, _ := ret[5].(error) + return ret0, ret1, ret2, ret3, ret4, ret5 +} + +// GetTransaction indicates an expected call of GetTransaction. +func (mr *MockBackendMockRecorder) GetTransaction(ctx, txHash any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTransaction", reflect.TypeOf((*MockBackend)(nil).GetTransaction), ctx, txHash) +} + +// HeaderByHash mocks base method. +func (m *MockBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "HeaderByHash", ctx, hash) + ret0, _ := ret[0].(*types.Header) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// HeaderByHash indicates an expected call of HeaderByHash. +func (mr *MockBackendMockRecorder) HeaderByHash(ctx, hash any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HeaderByHash", reflect.TypeOf((*MockBackend)(nil).HeaderByHash), ctx, hash) +} + +// HeaderByNumber mocks base method. +func (m *MockBackend) HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "HeaderByNumber", ctx, number) + ret0, _ := ret[0].(*types.Header) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// HeaderByNumber indicates an expected call of HeaderByNumber. +func (mr *MockBackendMockRecorder) HeaderByNumber(ctx, number any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HeaderByNumber", reflect.TypeOf((*MockBackend)(nil).HeaderByNumber), ctx, number) +} + +// HeaderByNumberOrHash mocks base method. +func (m *MockBackend) HeaderByNumberOrHash(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (*types.Header, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "HeaderByNumberOrHash", ctx, blockNrOrHash) + ret0, _ := ret[0].(*types.Header) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// HeaderByNumberOrHash indicates an expected call of HeaderByNumberOrHash. +func (mr *MockBackendMockRecorder) HeaderByNumberOrHash(ctx, blockNrOrHash any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HeaderByNumberOrHash", reflect.TypeOf((*MockBackend)(nil).HeaderByNumberOrHash), ctx, blockNrOrHash) +} + +// HistoricalProofQueryWindow mocks base method. +func (m *MockBackend) HistoricalProofQueryWindow() uint64 { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "HistoricalProofQueryWindow") + ret0, _ := ret[0].(uint64) + return ret0 +} + +// HistoricalProofQueryWindow indicates an expected call of HistoricalProofQueryWindow. +func (mr *MockBackendMockRecorder) HistoricalProofQueryWindow() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HistoricalProofQueryWindow", reflect.TypeOf((*MockBackend)(nil).HistoricalProofQueryWindow)) +} + +// IsArchive mocks base method. +func (m *MockBackend) IsArchive() bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "IsArchive") + ret0, _ := ret[0].(bool) + return ret0 +} + +// IsArchive indicates an expected call of IsArchive. +func (mr *MockBackendMockRecorder) IsArchive() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsArchive", reflect.TypeOf((*MockBackend)(nil).IsArchive)) +} + +// LastAcceptedBlock mocks base method. +func (m *MockBackend) LastAcceptedBlock() *types.Block { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "LastAcceptedBlock") + ret0, _ := ret[0].(*types.Block) + return ret0 +} + +// LastAcceptedBlock indicates an expected call of LastAcceptedBlock. +func (mr *MockBackendMockRecorder) LastAcceptedBlock() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastAcceptedBlock", reflect.TypeOf((*MockBackend)(nil).LastAcceptedBlock)) +} + +// RPCEVMTimeout mocks base method. +func (m *MockBackend) RPCEVMTimeout() time.Duration { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RPCEVMTimeout") + ret0, _ := ret[0].(time.Duration) + return ret0 +} + +// RPCEVMTimeout indicates an expected call of RPCEVMTimeout. +func (mr *MockBackendMockRecorder) RPCEVMTimeout() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RPCEVMTimeout", reflect.TypeOf((*MockBackend)(nil).RPCEVMTimeout)) +} + +// RPCGasCap mocks base method. +func (m *MockBackend) RPCGasCap() uint64 { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RPCGasCap") + ret0, _ := ret[0].(uint64) + return ret0 +} + +// RPCGasCap indicates an expected call of RPCGasCap. +func (mr *MockBackendMockRecorder) RPCGasCap() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RPCGasCap", reflect.TypeOf((*MockBackend)(nil).RPCGasCap)) +} + +// RPCTxFeeCap mocks base method. +func (m *MockBackend) RPCTxFeeCap() float64 { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RPCTxFeeCap") + ret0, _ := ret[0].(float64) + return ret0 +} + +// RPCTxFeeCap indicates an expected call of RPCTxFeeCap. +func (mr *MockBackendMockRecorder) RPCTxFeeCap() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RPCTxFeeCap", reflect.TypeOf((*MockBackend)(nil).RPCTxFeeCap)) +} + +// SendTx mocks base method. +func (m *MockBackend) SendTx(ctx context.Context, signedTx *types.Transaction) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SendTx", ctx, signedTx) + ret0, _ := ret[0].(error) + return ret0 +} + +// SendTx indicates an expected call of SendTx. +func (mr *MockBackendMockRecorder) SendTx(ctx, signedTx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendTx", reflect.TypeOf((*MockBackend)(nil).SendTx), ctx, signedTx) +} + +// ServiceFilter mocks base method. +func (m *MockBackend) ServiceFilter(ctx context.Context, session *bloombits.MatcherSession) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "ServiceFilter", ctx, session) +} + +// ServiceFilter indicates an expected call of ServiceFilter. +func (mr *MockBackendMockRecorder) ServiceFilter(ctx, session any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServiceFilter", reflect.TypeOf((*MockBackend)(nil).ServiceFilter), ctx, session) +} + +// StateAndHeaderByNumber mocks base method. +func (m *MockBackend) StateAndHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*state.StateDB, *types.Header, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "StateAndHeaderByNumber", ctx, number) + ret0, _ := ret[0].(*state.StateDB) + ret1, _ := ret[1].(*types.Header) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// StateAndHeaderByNumber indicates an expected call of StateAndHeaderByNumber. +func (mr *MockBackendMockRecorder) StateAndHeaderByNumber(ctx, number any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StateAndHeaderByNumber", reflect.TypeOf((*MockBackend)(nil).StateAndHeaderByNumber), ctx, number) +} + +// StateAndHeaderByNumberOrHash mocks base method. +func (m *MockBackend) StateAndHeaderByNumberOrHash(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) (*state.StateDB, *types.Header, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "StateAndHeaderByNumberOrHash", ctx, blockNrOrHash) + ret0, _ := ret[0].(*state.StateDB) + ret1, _ := ret[1].(*types.Header) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// StateAndHeaderByNumberOrHash indicates an expected call of StateAndHeaderByNumberOrHash. +func (mr *MockBackendMockRecorder) StateAndHeaderByNumberOrHash(ctx, blockNrOrHash any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StateAndHeaderByNumberOrHash", reflect.TypeOf((*MockBackend)(nil).StateAndHeaderByNumberOrHash), ctx, blockNrOrHash) +} + +// Stats mocks base method. +func (m *MockBackend) Stats() (int, int) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Stats") + ret0, _ := ret[0].(int) + ret1, _ := ret[1].(int) + return ret0, ret1 +} + +// Stats indicates an expected call of Stats. +func (mr *MockBackendMockRecorder) Stats() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stats", reflect.TypeOf((*MockBackend)(nil).Stats)) +} + +// SubscribeChainEvent mocks base method. +func (m *MockBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SubscribeChainEvent", ch) + ret0, _ := ret[0].(event.Subscription) + return ret0 +} + +// SubscribeChainEvent indicates an expected call of SubscribeChainEvent. +func (mr *MockBackendMockRecorder) SubscribeChainEvent(ch any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubscribeChainEvent", reflect.TypeOf((*MockBackend)(nil).SubscribeChainEvent), ch) +} + +// SubscribeChainHeadEvent mocks base method. +func (m *MockBackend) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SubscribeChainHeadEvent", ch) + ret0, _ := ret[0].(event.Subscription) + return ret0 +} + +// SubscribeChainHeadEvent indicates an expected call of SubscribeChainHeadEvent. +func (mr *MockBackendMockRecorder) SubscribeChainHeadEvent(ch any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubscribeChainHeadEvent", reflect.TypeOf((*MockBackend)(nil).SubscribeChainHeadEvent), ch) +} + +// SubscribeChainSideEvent mocks base method. +func (m *MockBackend) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SubscribeChainSideEvent", ch) + ret0, _ := ret[0].(event.Subscription) + return ret0 +} + +// SubscribeChainSideEvent indicates an expected call of SubscribeChainSideEvent. +func (mr *MockBackendMockRecorder) SubscribeChainSideEvent(ch any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubscribeChainSideEvent", reflect.TypeOf((*MockBackend)(nil).SubscribeChainSideEvent), ch) +} + +// SubscribeLogsEvent mocks base method. +func (m *MockBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SubscribeLogsEvent", ch) + ret0, _ := ret[0].(event.Subscription) + return ret0 +} + +// SubscribeLogsEvent indicates an expected call of SubscribeLogsEvent. +func (mr *MockBackendMockRecorder) SubscribeLogsEvent(ch any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubscribeLogsEvent", reflect.TypeOf((*MockBackend)(nil).SubscribeLogsEvent), ch) +} + +// SubscribeNewTxsEvent mocks base method. +func (m *MockBackend) SubscribeNewTxsEvent(arg0 chan<- core.NewTxsEvent) event.Subscription { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SubscribeNewTxsEvent", arg0) + ret0, _ := ret[0].(event.Subscription) + return ret0 +} + +// SubscribeNewTxsEvent indicates an expected call of SubscribeNewTxsEvent. +func (mr *MockBackendMockRecorder) SubscribeNewTxsEvent(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubscribeNewTxsEvent", reflect.TypeOf((*MockBackend)(nil).SubscribeNewTxsEvent), arg0) +} + +// SubscribePendingLogsEvent mocks base method. +func (m *MockBackend) SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SubscribePendingLogsEvent", ch) + ret0, _ := ret[0].(event.Subscription) + return ret0 +} + +// SubscribePendingLogsEvent indicates an expected call of SubscribePendingLogsEvent. +func (mr *MockBackendMockRecorder) SubscribePendingLogsEvent(ch any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubscribePendingLogsEvent", reflect.TypeOf((*MockBackend)(nil).SubscribePendingLogsEvent), ch) +} + +// SubscribeRemovedLogsEvent mocks base method. +func (m *MockBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SubscribeRemovedLogsEvent", ch) + ret0, _ := ret[0].(event.Subscription) + return ret0 +} + +// SubscribeRemovedLogsEvent indicates an expected call of SubscribeRemovedLogsEvent. +func (mr *MockBackendMockRecorder) SubscribeRemovedLogsEvent(ch any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubscribeRemovedLogsEvent", reflect.TypeOf((*MockBackend)(nil).SubscribeRemovedLogsEvent), ch) +} + +// SuggestGasTipCap mocks base method. +func (m *MockBackend) SuggestGasTipCap(ctx context.Context) (*big.Int, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SuggestGasTipCap", ctx) + ret0, _ := ret[0].(*big.Int) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// SuggestGasTipCap indicates an expected call of SuggestGasTipCap. +func (mr *MockBackendMockRecorder) SuggestGasTipCap(ctx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SuggestGasTipCap", reflect.TypeOf((*MockBackend)(nil).SuggestGasTipCap), ctx) +} + +// SuggestPrice mocks base method. +func (m *MockBackend) SuggestPrice(ctx context.Context) (*big.Int, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SuggestPrice", ctx) + ret0, _ := ret[0].(*big.Int) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// SuggestPrice indicates an expected call of SuggestPrice. +func (mr *MockBackendMockRecorder) SuggestPrice(ctx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SuggestPrice", reflect.TypeOf((*MockBackend)(nil).SuggestPrice), ctx) +} + +// TxPoolContent mocks base method. +func (m *MockBackend) TxPoolContent() (map[common.Address][]*types.Transaction, map[common.Address][]*types.Transaction) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "TxPoolContent") + ret0, _ := ret[0].(map[common.Address][]*types.Transaction) + ret1, _ := ret[1].(map[common.Address][]*types.Transaction) + return ret0, ret1 +} + +// TxPoolContent indicates an expected call of TxPoolContent. +func (mr *MockBackendMockRecorder) TxPoolContent() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TxPoolContent", reflect.TypeOf((*MockBackend)(nil).TxPoolContent)) +} + +// TxPoolContentFrom mocks base method. +func (m *MockBackend) TxPoolContentFrom(addr common.Address) ([]*types.Transaction, []*types.Transaction) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "TxPoolContentFrom", addr) + ret0, _ := ret[0].([]*types.Transaction) + ret1, _ := ret[1].([]*types.Transaction) + return ret0, ret1 +} + +// TxPoolContentFrom indicates an expected call of TxPoolContentFrom. +func (mr *MockBackendMockRecorder) TxPoolContentFrom(addr any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TxPoolContentFrom", reflect.TypeOf((*MockBackend)(nil).TxPoolContentFrom), addr) +} + +// UnprotectedAllowed mocks base method. +func (m *MockBackend) UnprotectedAllowed(tx *types.Transaction) bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UnprotectedAllowed", tx) + ret0, _ := ret[0].(bool) + return ret0 +} + +// UnprotectedAllowed indicates an expected call of UnprotectedAllowed. +func (mr *MockBackendMockRecorder) UnprotectedAllowed(tx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnprotectedAllowed", reflect.TypeOf((*MockBackend)(nil).UnprotectedAllowed), tx) +} diff --git a/plugin/evm/config/config.go b/plugin/evm/config/config.go index f5bf644657..3104b0faa9 100644 --- a/plugin/evm/config/config.go +++ b/plugin/evm/config/config.go @@ -59,6 +59,9 @@ const ( // - state sync time: ~6 hrs. defaultStateSyncMinBlocks = 300_000 DefaultStateSyncRequestSize = 1024 // the number of key/values to ask peers for per request + + estimatedBlockAcceptPeriod = 2 * time.Second + defaultHistoricalProofQueryWindow = uint64(24 * time.Hour / estimatedBlockAcceptPeriod) ) var ( @@ -124,6 +127,10 @@ type Config struct { PopulateMissingTriesParallelism int `json:"populate-missing-tries-parallelism"` // Number of concurrent readers to use when re-populating missing tries on startup. PruneWarpDB bool `json:"prune-warp-db-enabled"` // Determines if the warpDB should be cleared on startup + // HistoricalProofQueryWindow is, when running in archive mode only, the number of blocks before the + // last accepted block to be accepted for proof state queries. + HistoricalProofQueryWindow uint64 `json:"historical-proof-query-window,omitempty"` + // Metric Settings MetricsExpensiveEnabled bool `json:"metrics-expensive-enabled"` // Debug-level metrics that might impact runtime performance @@ -288,6 +295,7 @@ func (c *Config) SetDefaults(txPoolConfig TxPoolConfig) { c.StateSyncRequestSize = DefaultStateSyncRequestSize c.AllowUnprotectedTxHashes = defaultAllowUnprotectedTxHashes c.AcceptedCacheSize = defaultAcceptedCacheSize + c.HistoricalProofQueryWindow = defaultHistoricalProofQueryWindow } func (d *Duration) UnmarshalJSON(data []byte) (err error) { diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index eebbd4a7ce..879cb8988e 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -495,6 +495,7 @@ func (vm *VM) Initialize( vm.ethConfig.SnapshotDelayInit = vm.stateSyncEnabled(lastAcceptedHeight) vm.ethConfig.SnapshotWait = vm.config.SnapshotWait vm.ethConfig.SnapshotVerify = vm.config.SnapshotVerify + vm.ethConfig.HistoricalProofQueryWindow = vm.config.HistoricalProofQueryWindow vm.ethConfig.OfflinePruning = vm.config.OfflinePruning vm.ethConfig.OfflinePruningBloomFilterSize = vm.config.OfflinePruningBloomFilterSize vm.ethConfig.OfflinePruningDataDirectory = vm.config.OfflinePruningDataDirectory From be859c90f068f8fddb34005ef59822212bbe71de Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Thu, 16 Jan 2025 11:20:29 +0300 Subject: [PATCH 24/69] remove keystore and related APIs (#748) --- RELEASES.md | 4 + plugin/evm/api.go | 211 +-------------------- plugin/evm/client/client.go | 141 -------------- plugin/evm/client/client_interface_test.go | 17 -- plugin/evm/user.go | 137 ------------- plugin/evm/vm.go | 17 -- plugin/evm/vm_test.go | 10 - 7 files changed, 7 insertions(+), 530 deletions(-) delete mode 100644 plugin/evm/client/client_interface_test.go delete mode 100644 plugin/evm/user.go diff --git a/RELEASES.md b/RELEASES.md index 4dd80d2d21..d2072b75b8 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,5 +1,9 @@ # Release Notes +## Pending Release + +- Removed deprecated `ExportKey`, `ExportAVAX`, `Export`, `ImportKey`, `ImportAVAX`, `Import` APIs + ## [v0.14.1](https://github.com/ava-labs/coreth/releases/tag/v0.14.1) - IMPORTANT: `eth_getProof` calls for historical state will be rejected by default. diff --git a/plugin/evm/api.go b/plugin/evm/api.go index 49ad2a895f..12791d4e08 100644 --- a/plugin/evm/api.go +++ b/plugin/evm/api.go @@ -19,7 +19,6 @@ import ( "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/plugin/evm/client" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/log" ) @@ -33,10 +32,9 @@ const ( ) var ( - errNoAddresses = errors.New("no addresses provided") - errNoSourceChain = errors.New("no source chain provided") - errNilTxID = errors.New("nil transaction ID") - errMissingPrivateKey = errors.New("argument 'privateKey' not given") + errNoAddresses = errors.New("no addresses provided") + errNoSourceChain = errors.New("no source chain provided") + errNilTxID = errors.New("nil transaction ID") initialBaseFee = big.NewInt(params.ApricotPhase3InitialBaseFee) ) @@ -71,17 +69,6 @@ func (api *SnowmanAPI) IssueBlock(ctx context.Context) error { // AvaxAPI offers Avalanche network related API methods type AvaxAPI struct{ vm *VM } -// parseAssetID parses an assetID string into an ID -func (service *AvaxAPI) parseAssetID(assetID string) (ids.ID, error) { - if assetID == "" { - return ids.ID{}, fmt.Errorf("assetID is required") - } else if assetID == "AVAX" { - return service.vm.ctx.AVAXAssetID, nil - } else { - return ids.FromString(assetID) - } -} - type VersionReply struct { Version string `json:"version"` } @@ -92,198 +79,6 @@ func (service *AvaxAPI) Version(r *http.Request, _ *struct{}, reply *VersionRepl return nil } -// ExportKey returns a private key from the provided user -func (service *AvaxAPI) ExportKey(r *http.Request, args *client.ExportKeyArgs, reply *client.ExportKeyReply) error { - log.Info("EVM: ExportKey called") - - address, err := client.ParseEthAddress(args.Address) - if err != nil { - return fmt.Errorf("couldn't parse %s to address: %s", args.Address, err) - } - - service.vm.ctx.Lock.Lock() - defer service.vm.ctx.Lock.Unlock() - - db, err := service.vm.ctx.Keystore.GetDatabase(args.Username, args.Password) - if err != nil { - return fmt.Errorf("problem retrieving user '%s': %w", args.Username, err) - } - defer db.Close() - - user := user{db: db} - reply.PrivateKey, err = user.getKey(address) - if err != nil { - return fmt.Errorf("problem retrieving private key: %w", err) - } - reply.PrivateKeyHex = hexutil.Encode(reply.PrivateKey.Bytes()) - return nil -} - -// ImportKey adds a private key to the provided user -func (service *AvaxAPI) ImportKey(r *http.Request, args *client.ImportKeyArgs, reply *api.JSONAddress) error { - log.Info("EVM: ImportKey called", "username", args.Username) - - if args.PrivateKey == nil { - return errMissingPrivateKey - } - - reply.Address = args.PrivateKey.EthAddress().Hex() - - service.vm.ctx.Lock.Lock() - defer service.vm.ctx.Lock.Unlock() - - db, err := service.vm.ctx.Keystore.GetDatabase(args.Username, args.Password) - if err != nil { - return fmt.Errorf("problem retrieving data: %w", err) - } - defer db.Close() - - user := user{db: db} - if err := user.putAddress(args.PrivateKey); err != nil { - return fmt.Errorf("problem saving key %w", err) - } - return nil -} - -// ImportAVAX is a deprecated name for Import. -func (service *AvaxAPI) ImportAVAX(_ *http.Request, args *client.ImportArgs, response *api.JSONTxID) error { - return service.Import(nil, args, response) -} - -// Import issues a transaction to import AVAX from the X-chain. The AVAX -// must have already been exported from the X-Chain. -func (service *AvaxAPI) Import(_ *http.Request, args *client.ImportArgs, response *api.JSONTxID) error { - log.Info("EVM: ImportAVAX called") - - chainID, err := service.vm.ctx.BCLookup.Lookup(args.SourceChain) - if err != nil { - return fmt.Errorf("problem parsing chainID %q: %w", args.SourceChain, err) - } - - service.vm.ctx.Lock.Lock() - defer service.vm.ctx.Lock.Unlock() - - // Get the user's info - db, err := service.vm.ctx.Keystore.GetDatabase(args.Username, args.Password) - if err != nil { - return fmt.Errorf("couldn't get user '%s': %w", args.Username, err) - } - defer db.Close() - - user := user{db: db} - privKeys, err := user.getKeys() - if err != nil { // Get keys - return fmt.Errorf("couldn't get keys controlled by the user: %w", err) - } - - var baseFee *big.Int - if args.BaseFee == nil { - // Get the base fee to use - baseFee, err = service.vm.estimateBaseFee(context.Background()) - if err != nil { - return err - } - } else { - baseFee = args.BaseFee.ToInt() - } - - tx, err := service.vm.newImportTx(chainID, args.To, baseFee, privKeys) - if err != nil { - return err - } - - response.TxID = tx.ID() - if err := service.vm.mempool.AddLocalTx(tx); err != nil { - return err - } - service.vm.atomicTxPushGossiper.Add(&atomic.GossipAtomicTx{Tx: tx}) - return nil -} - -// ExportAVAX exports AVAX from the C-Chain to the X-Chain -// It must be imported on the X-Chain to complete the transfer -func (service *AvaxAPI) ExportAVAX(_ *http.Request, args *client.ExportAVAXArgs, response *api.JSONTxID) error { - return service.Export(nil, &client.ExportArgs{ - ExportAVAXArgs: *args, - AssetID: service.vm.ctx.AVAXAssetID.String(), - }, response) -} - -// Export exports an asset from the C-Chain to the X-Chain -// It must be imported on the X-Chain to complete the transfer -func (service *AvaxAPI) Export(_ *http.Request, args *client.ExportArgs, response *api.JSONTxID) error { - log.Info("EVM: Export called") - - assetID, err := service.parseAssetID(args.AssetID) - if err != nil { - return err - } - - if args.Amount == 0 { - return errors.New("argument 'amount' must be > 0") - } - - // Get the chainID and parse the to address - chainID, to, err := service.vm.ParseAddress(args.To) - if err != nil { - chainID, err = service.vm.ctx.BCLookup.Lookup(args.TargetChain) - if err != nil { - return err - } - to, err = ids.ShortFromString(args.To) - if err != nil { - return err - } - } - - service.vm.ctx.Lock.Lock() - defer service.vm.ctx.Lock.Unlock() - - // Get this user's data - db, err := service.vm.ctx.Keystore.GetDatabase(args.Username, args.Password) - if err != nil { - return fmt.Errorf("problem retrieving user '%s': %w", args.Username, err) - } - defer db.Close() - - user := user{db: db} - privKeys, err := user.getKeys() - if err != nil { - return fmt.Errorf("couldn't get addresses controlled by the user: %w", err) - } - - var baseFee *big.Int - if args.BaseFee == nil { - // Get the base fee to use - baseFee, err = service.vm.estimateBaseFee(context.Background()) - if err != nil { - return err - } - } else { - baseFee = args.BaseFee.ToInt() - } - - // Create the transaction - tx, err := service.vm.newExportTx( - assetID, // AssetID - uint64(args.Amount), // Amount - chainID, // ID of the chain to send the funds to - to, // Address - baseFee, - privKeys, // Private keys - ) - if err != nil { - return fmt.Errorf("couldn't create tx: %w", err) - } - - response.TxID = tx.ID() - if err := service.vm.mempool.AddLocalTx(tx); err != nil { - return err - } - service.vm.atomicTxPushGossiper.Add(&atomic.GossipAtomicTx{Tx: tx}) - return nil -} - // GetUTXOs gets all utxos for passed in addresses func (service *AvaxAPI) GetUTXOs(r *http.Request, args *api.GetUTXOsArgs, reply *api.GetUTXOsReply) error { log.Info("EVM: GetUTXOs called", "Addresses", args.Addresses) diff --git a/plugin/evm/client/client.go b/plugin/evm/client/client.go index a6716b4b27..b507342405 100644 --- a/plugin/evm/client/client.go +++ b/plugin/evm/client/client.go @@ -8,13 +8,10 @@ import ( "errors" "fmt" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" "golang.org/x/exp/slog" "github.com/ava-labs/avalanchego/api" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/formatting" "github.com/ava-labs/avalanchego/utils/formatting/address" "github.com/ava-labs/avalanchego/utils/json" @@ -34,11 +31,6 @@ type Client interface { GetAtomicTxStatus(ctx context.Context, txID ids.ID, options ...rpc.Option) (atomic.Status, error) GetAtomicTx(ctx context.Context, txID ids.ID, options ...rpc.Option) ([]byte, error) GetAtomicUTXOs(ctx context.Context, addrs []ids.ShortID, sourceChain string, limit uint32, startAddress ids.ShortID, startUTXOID ids.ID, options ...rpc.Option) ([][]byte, ids.ShortID, ids.ID, error) - ExportKey(ctx context.Context, userPass api.UserPass, addr common.Address, options ...rpc.Option) (*secp256k1.PrivateKey, string, error) - ImportKey(ctx context.Context, userPass api.UserPass, privateKey *secp256k1.PrivateKey, options ...rpc.Option) (common.Address, error) - Import(ctx context.Context, userPass api.UserPass, to common.Address, sourceChain string, options ...rpc.Option) (ids.ID, error) - ExportAVAX(ctx context.Context, userPass api.UserPass, amount uint64, to ids.ShortID, targetChain string, options ...rpc.Option) (ids.ID, error) - Export(ctx context.Context, userPass api.UserPass, amount uint64, to ids.ShortID, targetChain string, assetID string, options ...rpc.Option) (ids.ID, error) StartCPUProfiler(ctx context.Context, options ...rpc.Option) error StopCPUProfiler(ctx context.Context, options ...rpc.Option) error MemoryProfile(ctx context.Context, options ...rpc.Option) error @@ -143,139 +135,6 @@ func (c *client) GetAtomicUTXOs(ctx context.Context, addrs []ids.ShortID, source return utxos, endAddr, endUTXOID, err } -// ExportKeyArgs are arguments for ExportKey -type ExportKeyArgs struct { - api.UserPass - Address string `json:"address"` -} - -// ExportKeyReply is the response for ExportKey -type ExportKeyReply struct { - // The decrypted PrivateKey for the Address provided in the arguments - PrivateKey *secp256k1.PrivateKey `json:"privateKey"` - PrivateKeyHex string `json:"privateKeyHex"` -} - -// ExportKey returns the private key corresponding to [addr] controlled by [user] -// in both Avalanche standard format and hex format -func (c *client) ExportKey(ctx context.Context, user api.UserPass, addr common.Address, options ...rpc.Option) (*secp256k1.PrivateKey, string, error) { - res := &ExportKeyReply{} - err := c.requester.SendRequest(ctx, "avax.exportKey", &ExportKeyArgs{ - UserPass: user, - Address: addr.Hex(), - }, res, options...) - return res.PrivateKey, res.PrivateKeyHex, err -} - -// ImportKeyArgs are arguments for ImportKey -type ImportKeyArgs struct { - api.UserPass - PrivateKey *secp256k1.PrivateKey `json:"privateKey"` -} - -// ImportKey imports [privateKey] to [user] -func (c *client) ImportKey(ctx context.Context, user api.UserPass, privateKey *secp256k1.PrivateKey, options ...rpc.Option) (common.Address, error) { - res := &api.JSONAddress{} - err := c.requester.SendRequest(ctx, "avax.importKey", &ImportKeyArgs{ - UserPass: user, - PrivateKey: privateKey, - }, res, options...) - if err != nil { - return common.Address{}, err - } - return ParseEthAddress(res.Address) -} - -// ImportArgs are arguments for passing into Import requests -type ImportArgs struct { - api.UserPass - - // Fee that should be used when creating the tx - BaseFee *hexutil.Big `json:"baseFee"` - - // Chain the funds are coming from - SourceChain string `json:"sourceChain"` - - // The address that will receive the imported funds - To common.Address `json:"to"` -} - -// Import sends an import transaction to import funds from [sourceChain] and -// returns the ID of the newly created transaction -func (c *client) Import(ctx context.Context, user api.UserPass, to common.Address, sourceChain string, options ...rpc.Option) (ids.ID, error) { - res := &api.JSONTxID{} - err := c.requester.SendRequest(ctx, "avax.import", &ImportArgs{ - UserPass: user, - To: to, - SourceChain: sourceChain, - }, res, options...) - return res.TxID, err -} - -// ExportAVAX sends AVAX from this chain to the address specified by [to]. -// Returns the ID of the newly created atomic transaction -func (c *client) ExportAVAX( - ctx context.Context, - user api.UserPass, - amount uint64, - to ids.ShortID, - targetChain string, - options ...rpc.Option, -) (ids.ID, error) { - return c.Export(ctx, user, amount, to, targetChain, "AVAX", options...) -} - -// ExportAVAXArgs are the arguments to ExportAVAX -type ExportAVAXArgs struct { - api.UserPass - - // Fee that should be used when creating the tx - BaseFee *hexutil.Big `json:"baseFee"` - - // Amount of asset to send - Amount json.Uint64 `json:"amount"` - - // Chain the funds are going to. Optional. Used if To address does not - // include the chainID. - TargetChain string `json:"targetChain"` - - // ID of the address that will receive the AVAX. This address may include - // the chainID, which is used to determine what the destination chain is. - To string `json:"to"` -} - -// ExportArgs are the arguments to Export -type ExportArgs struct { - ExportAVAXArgs - // AssetID of the tokens - AssetID string `json:"assetID"` -} - -// Export sends an asset from this chain to the P/C-Chain. -// After this tx is accepted, the AVAX must be imported to the P/C-chain with an importTx. -// Returns the ID of the newly created atomic transaction -func (c *client) Export( - ctx context.Context, - user api.UserPass, - amount uint64, - to ids.ShortID, - targetChain string, - assetID string, - options ...rpc.Option, -) (ids.ID, error) { - res := &api.JSONTxID{} - err := c.requester.SendRequest(ctx, "avax.export", &ExportArgs{ - ExportAVAXArgs: ExportAVAXArgs{ - UserPass: user, - Amount: json.Uint64(amount), - TargetChain: targetChain, - To: to.String(), - }, - AssetID: assetID, - }, res, options...) - return res.TxID, err -} - func (c *client) StartCPUProfiler(ctx context.Context, options ...rpc.Option) error { return c.adminRequester.SendRequest(ctx, "admin.startCPUProfiler", struct{}{}, &api.EmptyReply{}, options...) } diff --git a/plugin/evm/client/client_interface_test.go b/plugin/evm/client/client_interface_test.go deleted file mode 100644 index 332bb8bcf4..0000000000 --- a/plugin/evm/client/client_interface_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package client - -import ( - "reflect" - "testing" -) - -func TestInterfaceStructOneToOne(t *testing.T) { - // checks struct provides at least the methods signatures in the interface - var _ Client = (*client)(nil) - // checks interface and struct have the same number of methods - clientType := reflect.TypeOf(&client{}) - ClientType := reflect.TypeOf((*Client)(nil)).Elem() - if clientType.NumMethod() != ClientType.NumMethod() { - t.Fatalf("no 1 to 1 compliance between struct methods (%v) and interface methods (%v)", clientType.NumMethod(), ClientType.NumMethod()) - } -} diff --git a/plugin/evm/user.go b/plugin/evm/user.go deleted file mode 100644 index 8cb3f73f34..0000000000 --- a/plugin/evm/user.go +++ /dev/null @@ -1,137 +0,0 @@ -// (c) 2019-2020, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package evm - -import ( - "errors" - - "github.com/ava-labs/avalanchego/database/encdb" - "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" - "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ethereum/go-ethereum/common" -) - -// Key in the database whose corresponding value is the list of -// addresses this user controls -var addressesKey = ids.Empty[:] - -var ( - errDBNil = errors.New("db uninitialized") - errKeyNil = errors.New("key uninitialized") -) - -type user struct { - // This user's database, acquired from the keystore - db *encdb.Database -} - -// Get the addresses controlled by this user -func (u *user) getAddresses() ([]common.Address, error) { - if u.db == nil { - return nil, errDBNil - } - - // If user has no addresses, return empty list - hasAddresses, err := u.db.Has(addressesKey) - if err != nil { - return nil, err - } - if !hasAddresses { - return nil, nil - } - - // User has addresses. Get them. - bytes, err := u.db.Get(addressesKey) - if err != nil { - return nil, err - } - addresses := []common.Address{} - if _, err := atomic.Codec.Unmarshal(bytes, &addresses); err != nil { - return nil, err - } - return addresses, nil -} - -// controlsAddress returns true iff this user controls the given address -func (u *user) controlsAddress(address common.Address) (bool, error) { - if u.db == nil { - return false, errDBNil - //} else if address.IsZero() { - // return false, errEmptyAddress - } - return u.db.Has(address.Bytes()) -} - -// putAddress persists that this user controls address controlled by [privKey] -func (u *user) putAddress(privKey *secp256k1.PrivateKey) error { - if privKey == nil { - return errKeyNil - } - - address := privKey.EthAddress() // address the privKey controls - controlsAddress, err := u.controlsAddress(address) - if err != nil { - return err - } - if controlsAddress { // user already controls this address. Do nothing. - return nil - } - - if err := u.db.Put(address.Bytes(), privKey.Bytes()); err != nil { // Address --> private key - return err - } - - addresses := make([]common.Address, 0) // Add address to list of addresses user controls - userHasAddresses, err := u.db.Has(addressesKey) - if err != nil { - return err - } - if userHasAddresses { // Get addresses this user already controls, if they exist - if addresses, err = u.getAddresses(); err != nil { - return err - } - } - addresses = append(addresses, address) - bytes, err := atomic.Codec.Marshal(atomic.CodecVersion, addresses) - if err != nil { - return err - } - if err := u.db.Put(addressesKey, bytes); err != nil { - return err - } - return nil -} - -// Key returns the private key that controls the given address -func (u *user) getKey(address common.Address) (*secp256k1.PrivateKey, error) { - if u.db == nil { - return nil, errDBNil - //} else if address.IsZero() { - // return nil, errEmptyAddress - } - - bytes, err := u.db.Get(address.Bytes()) - if err != nil { - return nil, err - } - return secp256k1.ToPrivateKey(bytes) -} - -// Return all private keys controlled by this user -func (u *user) getKeys() ([]*secp256k1.PrivateKey, error) { - addrs, err := u.getAddresses() - if err != nil { - return nil, err - } - keys := make([]*secp256k1.PrivateKey, len(addrs)) - for i, addr := range addrs { - key, err := u.getKey(addr) - if err != nil { - return nil, err - } - keys[i] = key - } - return keys, nil -} diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 879cb8988e..e85dad52d4 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -1731,23 +1731,6 @@ func (vm *VM) startContinuousProfiler() { <-vm.shutdownChan } -func (vm *VM) estimateBaseFee(ctx context.Context) (*big.Int, error) { - // Get the base fee to use - baseFee, err := vm.eth.APIBackend.EstimateBaseFee(ctx) - if err != nil { - return nil, err - } - if baseFee == nil { - baseFee = initialBaseFee - } else { - // give some breathing room - baseFee.Mul(baseFee, big.NewInt(11)) - baseFee.Div(baseFee, big.NewInt(10)) - } - - return baseFee, nil -} - // readLastAccepted reads the last accepted hash from [acceptedBlockDB] and returns the // last accepted block hash and height by reading directly from [vm.chaindb] instead of relying // on [chain]. diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 507c8d3a94..340b946896 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -32,7 +32,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/api/keystore" avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/memdb" @@ -46,7 +45,6 @@ import ( "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/formatting" "github.com/ava-labs/avalanchego/utils/hashing" - "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" @@ -78,8 +76,6 @@ var ( testEthAddrs []common.Address // testEthAddrs[i] corresponds to testKeys[i] testShortIDAddrs []ids.ShortID testAvaxAssetID = ids.ID{1, 2, 3} - username = "Johns" - password = "CjasdjhiPeirbSenfeI13" // #nosec G101 genesisJSON = func(cfg *params.ChainConfig) string { g := new(core.Genesis) @@ -260,12 +256,6 @@ func setupGenesis( // The caller of this function is responsible for unlocking. ctx.Lock.Lock() - userKeystore := keystore.New(logging.NoLog{}, memdb.New()) - if err := userKeystore.CreateUser(username, password); err != nil { - t.Fatal(err) - } - ctx.Keystore = userKeystore.NewBlockchainKeyStore(ctx.ChainID) - issuer := make(chan commonEng.Message, 1) prefixedDB := prefixdb.New([]byte{1}, baseDB) return ctx, prefixedDB, genesisBytes, issuer, atomicMemory From 4765329f1050930af5b22c8f4701280256c89ecf Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Thu, 16 Jan 2025 11:32:26 -0800 Subject: [PATCH 25/69] bump avalanchego in preparation for tagging rc (#751) --- RELEASES.md | 3 +-- go.mod | 2 +- go.sum | 4 ++-- scripts/versions.sh | 2 +- 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index d2072b75b8..628e454843 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -2,10 +2,9 @@ ## Pending Release -- Removed deprecated `ExportKey`, `ExportAVAX`, `Export`, `ImportKey`, `ImportAVAX`, `Import` APIs - ## [v0.14.1](https://github.com/ava-labs/coreth/releases/tag/v0.14.1) +- Removed deprecated `ExportKey`, `ExportAVAX`, `Export`, `ImportKey`, `ImportAVAX`, `Import` APIs - IMPORTANT: `eth_getProof` calls for historical state will be rejected by default. - On archive nodes (`"pruning-enabled": false`): queries for historical proofs for state older than approximately 24 hours preceding the last accepted block will be rejected by default. This can be adjusted with the new option `historical-proof-query-window` which defines the number of blocks before the last accepted block which should be accepted for state proof queries, or set to `0` to accept any block number state query (previous behavior). - On `pruning` nodes: queries for proofs past the tip buffer (32 blocks) will be rejected. This is in support of moving to a path based storage scheme, which does not support historical state proofs. diff --git a/go.mod b/go.mod index 0b095d2f54..9e8a97ed02 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.22.8 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.12.2-0.20250106102004-902377d447ba + github.com/ava-labs/avalanchego v1.12.2-0.20250116172728-54d8b06b8625 github.com/cespare/cp v0.1.0 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 diff --git a/go.sum b/go.sum index 9c19c061be..2090275d01 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,8 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/avalanchego v1.12.2-0.20250106102004-902377d447ba h1:7t2ORGM53sqdsczNZGFQIK99of9yeetCld90keJ47Os= -github.com/ava-labs/avalanchego v1.12.2-0.20250106102004-902377d447ba/go.mod h1:oK/C7ZGo5cAEayBKBoawh2EpOo3E9gD1rpd9NAM0RkQ= +github.com/ava-labs/avalanchego v1.12.2-0.20250116172728-54d8b06b8625 h1:sbmfwhpetCKI7Unzw9jJ+2HWLRFM7vq7th0pH2LclCQ= +github.com/ava-labs/avalanchego v1.12.2-0.20250116172728-54d8b06b8625/go.mod h1:oK/C7ZGo5cAEayBKBoawh2EpOo3E9gD1rpd9NAM0RkQ= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/scripts/versions.sh b/scripts/versions.sh index ba63c1148c..42e3dcf479 100644 --- a/scripts/versions.sh +++ b/scripts/versions.sh @@ -6,4 +6,4 @@ set -euo pipefail # Don't export them as they're used in the context of other calls -AVALANCHE_VERSION=${AVALANCHE_VERSION:-'902377d447ba'} +AVALANCHE_VERSION=${AVALANCHE_VERSION:-'54d8b06b'} From d00d1db11a6f051cc54a2a23d552dd7fe3134e28 Mon Sep 17 00:00:00 2001 From: Radovenchyk Date: Fri, 17 Jan 2025 18:58:39 +0200 Subject: [PATCH 26/69] chore: changed the link to the documentation (#755) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 40cd3a8407..08ea17aa62 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Coreth and the C-Chain -[Avalanche](https://docs.avax.network/intro) is a network composed of multiple blockchains. +[Avalanche](https://www.avax.network/) is a network composed of multiple blockchains. Each blockchain is an instance of a Virtual Machine (VM), much like an object in an object-oriented language is an instance of a class. That is, the VM defines the behavior of the blockchain. Coreth (from core Ethereum) is the [Virtual Machine (VM)](https://docs.avax.network/learn/virtual-machines) that defines the Contract Chain (C-Chain). @@ -39,7 +39,7 @@ Full documentation for the C-Chain's API can be found [here.](https://docs.avax. ## Compatibility -The C-Chain is compatible with almost all Ethereum tooling, including [Core,](https://docs.avax.network/build/dapp/launch-dapp#through-core) [Metamask,](https://docs.avax.network/build/dapp/launch-dapp#through-metamask) [Remix](https://docs.avax.network/build/tutorials/smart-contracts/deploy-a-smart-contract-on-avalanche-using-remix-and-metamask) and [Truffle.](https://docs.avax.network/build/tutorials/smart-contracts/using-truffle-with-the-avalanche-c-chain) +The C-Chain is compatible with almost all Ethereum tooling, including [Core,](https://docs.avax.network/build/dapp/launch-dapp#through-core) [Metamask,](https://docs.avax.network/build/dapp/launch-dapp#through-metamask) [Remix](https://docs.avax.network/dapps/smart-contract-dev/deploy-with-remix-ide) and [Truffle.](https://docs.avax.network/build/tutorials/smart-contracts/using-truffle-with-the-avalanche-c-chain) ## Differences Between Avalanche C-Chain and Ethereum From a087e40bbcd742230c47bac4213cfd3253b183e9 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Wed, 22 Jan 2025 06:51:00 -0800 Subject: [PATCH 27/69] restore TestReorgReInsert (#762) --- core/test_blockchain.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/core/test_blockchain.go b/core/test_blockchain.go index 9c22ff0338..1aa82ccb7b 100644 --- a/core/test_blockchain.go +++ b/core/test_blockchain.go @@ -67,6 +67,10 @@ var tests = []ChainTest{ "EmptyBlocks", TestEmptyBlocks, }, + { + "ReorgReInsert", + TestReorgReInsert, + }, { "AcceptBlockIdenticalStateRoot", TestAcceptBlockIdenticalStateRoot, @@ -880,9 +884,6 @@ func TestReorgReInsert(t *testing.T, create func(db ethdb.Database, gspec *Genes key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a") addr1 = crypto.PubkeyToAddress(key1.PublicKey) addr2 = crypto.PubkeyToAddress(key2.PublicKey) - // We use two separate databases since GenerateChain commits the state roots to its underlying - // database. - genDB = rawdb.NewMemoryDatabase() chainDB = rawdb.NewMemoryDatabase() ) @@ -892,7 +893,6 @@ func TestReorgReInsert(t *testing.T, create func(db ethdb.Database, gspec *Genes Config: ¶ms.ChainConfig{HomesteadBlock: new(big.Int)}, Alloc: types.GenesisAlloc{addr1: {Balance: genesisBalance}}, } - genesis := gspec.ToBlock() blockchain, err := create(chainDB, gspec, common.Hash{}) if err != nil { @@ -902,7 +902,7 @@ func TestReorgReInsert(t *testing.T, create func(db ethdb.Database, gspec *Genes signer := types.HomesteadSigner{} numBlocks := 3 - chain, _, err := GenerateChain(gspec.Config, genesis, blockchain.engine, genDB, numBlocks, 10, func(i int, gen *BlockGen) { + _, chain, _, err := GenerateChainWithGenesis(gspec, blockchain.engine, numBlocks, 10, func(i int, gen *BlockGen) { // Generate a transaction to create a unique block tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil), signer, key1) gen.AddTx(tx) From 9e729ab76cf15cdba734c09530cb4651136260c8 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Mon, 27 Jan 2025 08:47:51 -0800 Subject: [PATCH 28/69] Apply upstream fixes (up to d3cc618) (#766) Co-authored-by: maskpp Co-authored-by: Aaron Chen Co-authored-by: Shiming Zhang Co-authored-by: Felix Lange Co-authored-by: Nathan Co-authored-by: Eric <45141191+zlacfzy@users.noreply.github.com> --- core/state/snapshot/snapshot.go | 4 +++- core/state/statedb.go | 27 +++++++-------------------- eth/gasprice/feehistory.go | 7 +++++++ rpc/http.go | 2 +- 4 files changed, 18 insertions(+), 22 deletions(-) diff --git a/core/state/snapshot/snapshot.go b/core/state/snapshot/snapshot.go index abb3051762..bda0e97988 100644 --- a/core/state/snapshot/snapshot.go +++ b/core/state/snapshot/snapshot.go @@ -891,6 +891,8 @@ func (t *Tree) disklayer() *diskLayer { case *diskLayer: return layer case *diffLayer: + layer.lock.RLock() + defer layer.lock.RUnlock() return layer.origin default: panic(fmt.Sprintf("%T: undefined layer", snap)) @@ -922,7 +924,7 @@ func (t *Tree) generating() (bool, error) { return layer.genMarker != nil, nil } -// DiskRoot is a external helper function to return the disk layer root. +// DiskRoot is an external helper function to return the disk layer root. func (t *Tree) DiskRoot() common.Hash { t.lock.Lock() defer t.lock.Unlock() diff --git a/core/state/statedb.go b/core/state/statedb.go index 0dccd28bf8..e84e2d13d0 100644 --- a/core/state/statedb.go +++ b/core/state/statedb.go @@ -29,6 +29,7 @@ package state import ( "fmt" + "maps" "math/big" "sort" "time" @@ -820,18 +821,18 @@ func (s *StateDB) Copy() *StateDB { db: s.db, trie: s.db.CopyTrie(s.trie), originalRoot: s.originalRoot, - accounts: make(map[common.Hash][]byte), - storages: make(map[common.Hash]map[common.Hash][]byte), - accountsOrigin: make(map[common.Address][]byte), - storagesOrigin: make(map[common.Address]map[common.Hash][]byte), + accounts: copySet(s.accounts), + storages: copy2DSet(s.storages), + accountsOrigin: copySet(s.accountsOrigin), + storagesOrigin: copy2DSet(s.storagesOrigin), stateObjects: make(map[common.Address]*stateObject, len(s.journal.dirties)), stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)), stateObjectsDirty: make(map[common.Address]struct{}, len(s.journal.dirties)), - stateObjectsDestruct: make(map[common.Address]*types.StateAccount, len(s.stateObjectsDestruct)), + stateObjectsDestruct: maps.Clone(s.stateObjectsDestruct), refund: s.refund, logs: make(map[common.Hash][]*types.Log, len(s.logs)), logSize: s.logSize, - preimages: make(map[common.Hash][]byte, len(s.preimages)), + preimages: maps.Clone(s.preimages), journal: newJournal(), hasher: crypto.NewKeccakState(), @@ -873,16 +874,6 @@ func (s *StateDB) Copy() *StateDB { } state.stateObjectsDirty[addr] = struct{}{} } - // Deep copy the destruction markers. - for addr, value := range s.stateObjectsDestruct { - state.stateObjectsDestruct[addr] = value - } - // Deep copy the state changes made in the scope of block - // along with their original values. - state.accounts = copySet(s.accounts) - state.storages = copy2DSet(s.storages) - state.accountsOrigin = copySet(state.accountsOrigin) - state.storagesOrigin = copy2DSet(state.storagesOrigin) // Deep copy the logs occurred in the scope of block for hash, logs := range s.logs { @@ -893,10 +884,6 @@ func (s *StateDB) Copy() *StateDB { } state.logs[hash] = cpy } - // Deep copy the preimages occurred in the scope of block - for hash, preimage := range s.preimages { - state.preimages[hash] = preimage - } // Do we need to copy the access list and transient storage? // In practice: No. At the start of a transaction, these two lists are empty. // In practice, we only ever copy state _between_ transactions/blocks, never diff --git a/eth/gasprice/feehistory.go b/eth/gasprice/feehistory.go index 448c2a69db..d86121c003 100644 --- a/eth/gasprice/feehistory.go +++ b/eth/gasprice/feehistory.go @@ -45,6 +45,10 @@ var ( errBeyondHistoricalLimit = errors.New("request beyond historical limit") ) +const ( + maxQueryLimit = 100 +) + // txGasAndReward is sorted in ascending order based on reward type txGasAndReward struct { gasUsed uint64 @@ -173,6 +177,9 @@ func (oracle *Oracle) FeeHistory(ctx context.Context, blocks uint64, unresolvedL if blocks < 1 { return common.Big0, nil, nil, nil, nil // returning with no data and no error means there are no retrievable blocks } + if len(rewardPercentiles) > maxQueryLimit { + return common.Big0, nil, nil, nil, fmt.Errorf("%w: over the query limit %d", errInvalidPercentile, maxQueryLimit) + } if blocks > oracle.maxCallBlockHistory { log.Warn("Sanitizing fee history length", "requested", blocks, "truncated", oracle.maxCallBlockHistory) blocks = oracle.maxCallBlockHistory diff --git a/rpc/http.go b/rpc/http.go index b8670a9df8..8b18ed3895 100644 --- a/rpc/http.go +++ b/rpc/http.go @@ -250,7 +250,7 @@ func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadClos if _, err := buf.ReadFrom(resp.Body); err == nil { body = buf.Bytes() } - + resp.Body.Close() return nil, HTTPError{ Status: resp.Status, StatusCode: resp.StatusCode, From 3148809c874a8e3fe53d874d62d2f7e158ea3d87 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Mon, 27 Jan 2025 09:17:00 -0800 Subject: [PATCH 29/69] fix panic if config duration is set to 0 (#765) --- plugin/evm/gossip.go | 2 +- plugin/evm/validators.go | 19 ++++++++++++++ plugin/evm/vm.go | 55 +++++++++++++++++++++++++--------------- 3 files changed, 55 insertions(+), 21 deletions(-) create mode 100644 plugin/evm/validators.go diff --git a/plugin/evm/gossip.go b/plugin/evm/gossip.go index 16d632bd94..e1bf58b0fc 100644 --- a/plugin/evm/gossip.go +++ b/plugin/evm/gossip.go @@ -49,7 +49,7 @@ func newTxGossipHandler[T gossip.Gossipable]( maxMessageSize int, throttlingPeriod time.Duration, throttlingLimit int, - validators *p2p.Validators, + validators p2p.ValidatorSet, ) txGossipHandler { // push gossip messages can be handled from any peer handler := gossip.NewHandler( diff --git a/plugin/evm/validators.go b/plugin/evm/validators.go new file mode 100644 index 0000000000..44c5560267 --- /dev/null +++ b/plugin/evm/validators.go @@ -0,0 +1,19 @@ +// (c) 2019-2020, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package evm + +import ( + "context" + + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/set" +) + +type validatorSet struct { + set set.Set[ids.NodeID] +} + +func (v *validatorSet) Has(ctx context.Context, nodeID ids.NodeID) bool { + return v.set.Contains(nodeID) +} diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index e85dad52d4..e955358909 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -1120,6 +1120,11 @@ func (vm *VM) initBlockBuilding() error { vm.builder = vm.NewBlockBuilder(vm.toEngine) vm.builder.awaitSubmittedTxs() + var p2pValidators p2p.ValidatorSet = &validatorSet{} + if vm.config.PullGossipFrequency.Duration > 0 { + p2pValidators = vm.p2pValidators + } + if vm.ethTxGossipHandler == nil { vm.ethTxGossipHandler = newTxGossipHandler[*GossipEthTx]( vm.ctx.Log, @@ -1129,7 +1134,7 @@ func (vm *VM) initBlockBuilding() error { txGossipTargetMessageSize, txGossipThrottlingPeriod, txGossipThrottlingLimit, - vm.p2pValidators, + p2pValidators, ) } @@ -1146,7 +1151,7 @@ func (vm *VM) initBlockBuilding() error { txGossipTargetMessageSize, txGossipThrottlingPeriod, txGossipThrottlingLimit, - vm.p2pValidators, + p2pValidators, ) } @@ -1171,15 +1176,20 @@ func (vm *VM) initBlockBuilding() error { } } - vm.shutdownWg.Add(2) - go func() { - gossip.Every(ctx, vm.ctx.Log, ethTxPushGossiper, vm.config.PushGossipFrequency.Duration) - vm.shutdownWg.Done() - }() - go func() { - gossip.Every(ctx, vm.ctx.Log, vm.ethTxPullGossiper, vm.config.PullGossipFrequency.Duration) - vm.shutdownWg.Done() - }() + if vm.config.PushGossipFrequency.Duration > 0 { + vm.shutdownWg.Add(1) + go func() { + gossip.Every(ctx, vm.ctx.Log, ethTxPushGossiper, vm.config.PushGossipFrequency.Duration) + vm.shutdownWg.Done() + }() + } + if vm.config.PullGossipFrequency.Duration > 0 { + vm.shutdownWg.Add(1) + go func() { + gossip.Every(ctx, vm.ctx.Log, vm.ethTxPullGossiper, vm.config.PullGossipFrequency.Duration) + vm.shutdownWg.Done() + }() + } if vm.atomicTxPullGossiper == nil { atomicTxPullGossiper := gossip.NewPullGossiper[*atomic.GossipAtomicTx]( @@ -1198,15 +1208,20 @@ func (vm *VM) initBlockBuilding() error { } } - vm.shutdownWg.Add(2) - go func() { - gossip.Every(ctx, vm.ctx.Log, vm.atomicTxPushGossiper, vm.config.PushGossipFrequency.Duration) - vm.shutdownWg.Done() - }() - go func() { - gossip.Every(ctx, vm.ctx.Log, vm.atomicTxPullGossiper, vm.config.PullGossipFrequency.Duration) - vm.shutdownWg.Done() - }() + if vm.config.PushGossipFrequency.Duration > 0 { + vm.shutdownWg.Add(1) + go func() { + gossip.Every(ctx, vm.ctx.Log, vm.atomicTxPushGossiper, vm.config.PushGossipFrequency.Duration) + vm.shutdownWg.Done() + }() + } + if vm.config.PullGossipFrequency.Duration > 0 { + vm.shutdownWg.Add(1) + go func() { + gossip.Every(ctx, vm.ctx.Log, vm.atomicTxPullGossiper, vm.config.PullGossipFrequency.Duration) + vm.shutdownWg.Done() + }() + } return nil } From 8b6a54e8215f52fd27008fc332d388cad24bd59f Mon Sep 17 00:00:00 2001 From: Ashutosh Tripathi <39340292+ashucoder9@users.noreply.github.com> Date: Tue, 28 Jan 2025 20:22:01 +0530 Subject: [PATCH 30/69] update: readme changes for 9000 upgrade (#761) Co-authored-by: Darioush Jalali Co-authored-by: Quentin McGaw --- precompile/contracts/warp/README.md | 32 ++++++++++++++--------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/precompile/contracts/warp/README.md b/precompile/contracts/warp/README.md index 73ca165224..5a3b79a486 100644 --- a/precompile/contracts/warp/README.md +++ b/precompile/contracts/warp/README.md @@ -1,6 +1,6 @@ # Integrating Avalanche Warp Messaging into the EVM -Avalanche Warp Messaging offers a basic primitive to enable Cross-Subnet communication on the Avalanche Network. +Avalanche Warp Messaging offers a basic primitive to enable Cross-L1 communication on the Avalanche Network. It is intended to allow communication between arbitrary Custom Virtual Machines (including, but not limited to Subnet-EVM and Coreth). @@ -8,7 +8,7 @@ It is intended to allow communication between arbitrary Custom Virtual Machines Avalanche Warp Messaging uses BLS Multi-Signatures with Public-Key Aggregation where every Avalanche validator registers a public key alongside its NodeID on the Avalanche P-Chain. -Every node tracking a Subnet has read access to the Avalanche P-Chain. This provides weighted sets of BLS Public Keys that correspond to the validator sets of each Subnet on the Avalanche Network. Avalanche Warp Messaging provides a basic primitive for signing and verifying messages between Subnets: the receiving network can verify whether an aggregation of signatures from a set of source Subnet validators represents a threshold of stake large enough for the receiving network to process the message. +Every node tracking an Avalanche L1 has read access to the Avalanche P-Chain. This provides weighted sets of BLS Public Keys that correspond to the validator sets of each L1 on the Avalanche Network. Avalanche Warp Messaging provides a basic primitive for signing and verifying messages between L1s: the receiving network can verify whether an aggregation of signatures from a set of source L1 validators represents a threshold of stake large enough for the receiving network to process the message. For more details on Avalanche Warp Messaging, see the AvalancheGo [Warp README](https://docs.avax.network/build/cross-chain/awm/deep-dive). @@ -77,27 +77,25 @@ Since the predicate is encoded into the [Transaction Access List](https://eips.e Therefore, we use the [Predicate Utils](https://github.com/ava-labs/coreth/blob/master/predicate/Predicate.md) package to encode the actual byte slice of size N into the access list. -### Performance Optimization: C-Chain to Subnet +### Performance Optimization: C-Chain to Avalanche L1 -To support C-Chain to Subnet communication, or more generally Primary Network to Subnet communication, we special case the C-Chain for two reasons: +For communication between the C-Chain and an L1, as well as broader interactions between the Primary Network and Avalanche L1s, we have implemented special handling for the C-Chain. -1. Every Subnet validator validates the C-Chain -2. The Primary Network has the largest possible number of validators +The Primary Network has a large validator set, which creates a unique challenge for Avalanche Warp messages. To reach the required stake threshold, numerous signatures would need to be collected and verifying messages from the Primary Network would be computationally costly. However, we have developed a more efficient solution. -Since the Primary Network has the largest possible number of validators for any Subnet on Avalanche, it would also be the most expensive Subnet to receive and verify Avalanche Warp Messages from as it reaching a threshold of stake on the primary network would require many signatures. Luckily, we can do something much smarter. +When an Avalanche L1 receives a message from a blockchain on the Primary Network, we use the validator set of the receiving L1 instead of the entire network when validating the message. Note this is NOT possible if an L1 does not validate the Primary Network, in which case the Warp precompile must be configured with `requirePrimaryNetworkSigners`. -When a Subnet receives a message from a blockchain on the Primary Network, we use the validator set of the receiving Subnet instead of the entire network when validating the message. This means that the C-Chain sending a message can be the exact same as Subnet to Subnet communication. +Sending messages from the C-Chain remains unchanged. +However, when L1 XYZ receives a message from the C-Chain, it changes the semantics to the following: -However, when Subnet B receives a message from the C-Chain, it changes the semantics to the following: +1. Read the `SourceChainID` of the signed message (C-Chain) +2. Look up the `SubnetID` that validates C-Chain: Primary Network +3. Look up the validator set of L1 XYZ (instead of the Primary Network) and the registered BLS Public Keys of L1 XYZ at the P-Chain height specified by the ProposerVM header +4. Continue Warp Message verification using the validator set of L1 XYZ instead of the Primary Network -1. Read the SourceChainID of the signed message (C-Chain) -2. Look up the SubnetID that validates C-Chain: Primary Network -3. Look up the validator set of Subnet B (instead of the Primary Network) and the registered BLS Public Keys of Subnet B at the P-Chain height specified by the ProposerVM header -4. Continue Warp Message verification using the validator set of Subnet B instead of the Primary Network +This means that C-Chain to L1 communication only requires a threshold of stake on the receiving L1 to sign the message instead of a threshold of stake for the entire Primary Network. -This means that C-Chain to Subnet communication only requires a threshold of stake on the receiving subnet to sign the message instead of a threshold of stake for the entire Primary Network. - -This assumes that the security of Subnet B already depends on the validators of Subnet B to behave virtuously. Therefore, requiring a threshold of stake from the receiving Subnet's validator set instead of the whole Primary Network does not meaningfully change security of the receiving Subnet. +This assumes that the security of L1 XYZ already depends on the validators of L1 XYZ to behave virtuously. Therefore, requiring a threshold of stake from the receiving L1's validator set instead of the whole Primary Network does not meaningfully change security of the receiving L1. Note: this special case is ONLY applied during Warp Message verification. The message sent by the Primary Network will still contain the Avalanche C-Chain's blockchainID as the sourceChainID and signatures will be served by querying the C-Chain directly. @@ -107,7 +105,7 @@ Note: this special case is ONLY applied during Warp Message verification. The me Avalanche Warp Messaging depends on the Avalanche P-Chain state at the P-Chain height specified by the ProposerVM block header. -Verifying a message requires looking up the validator set of the source subnet on the P-Chain. To support this, Avalanche Warp Messaging uses the ProposerVM header, which includes the P-Chain height it was issued at as the canonical point to lookup the source subnet's validator set. +Verifying a message requires looking up the validator set of the source L1 on the P-Chain. To support this, Avalanche Warp Messaging uses the ProposerVM header, which includes the P-Chain height it was issued at as the canonical point to lookup the source L1's validator set. This means verifying the Warp Message and therefore the state transition on a block depends on state that is external to the blockchain itself: the P-Chain. From 1d2185080716e0d1832f884b702920d90328006c Mon Sep 17 00:00:00 2001 From: Richard Pringle Date: Wed, 29 Jan 2025 12:03:17 -0500 Subject: [PATCH 31/69] chore: use new avalanchego `utils/crypto/bls/signers/local` package (#716) Co-authored-by: Ceyhun Onur --- go.mod | 3 +-- go.sum | 6 ++---- plugin/evm/vm_test.go | 4 ++-- plugin/evm/vm_warp_test.go | 7 ++++--- precompile/contracts/warp/predicate_test.go | 3 ++- scripts/versions.sh | 2 +- utils/snow.go | 4 ++-- warp/aggregator/aggregator_test.go | 5 +++-- warp/backend_test.go | 12 ++++++------ warp/handlers/signature_request_test.go | 5 +++-- warp/verifier_backend_test.go | 6 +++--- 11 files changed, 29 insertions(+), 28 deletions(-) diff --git a/go.mod b/go.mod index 9e8a97ed02..b4bd03102a 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.22.8 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.12.2-0.20250116172728-54d8b06b8625 + github.com/ava-labs/avalanchego v1.12.3-0.20250128183416-7d2fd6ad37f4 github.com/cespare/cp v0.1.0 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 @@ -92,7 +92,6 @@ require ( github.com/mitchellh/pointerstructure v1.2.0 // indirect github.com/mmcloughlin/addchain v0.4.0 // indirect github.com/mr-tron/base58 v1.2.0 // indirect - github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d // indirect github.com/pelletier/go-toml v1.9.5 // indirect github.com/pelletier/go-toml/v2 v2.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect diff --git a/go.sum b/go.sum index 2090275d01..7f684d73b4 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,8 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/avalanchego v1.12.2-0.20250116172728-54d8b06b8625 h1:sbmfwhpetCKI7Unzw9jJ+2HWLRFM7vq7th0pH2LclCQ= -github.com/ava-labs/avalanchego v1.12.2-0.20250116172728-54d8b06b8625/go.mod h1:oK/C7ZGo5cAEayBKBoawh2EpOo3E9gD1rpd9NAM0RkQ= +github.com/ava-labs/avalanchego v1.12.3-0.20250128183416-7d2fd6ad37f4 h1:twEyoj604JLd0pmMktRjVixtdjxiYuTvQ5nHmP/BVzg= +github.com/ava-labs/avalanchego v1.12.3-0.20250128183416-7d2fd6ad37f4/go.mod h1:B7l4fA/BZL6VMC1HCtaHt1RpkC2HWxjAXxTZbc+n3ZI= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= @@ -416,8 +416,6 @@ github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5Vgl github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= -github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d h1:AREM5mwr4u1ORQBMvzfzBgpsctsbQikCVpvC+tX285E= -github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d/go.mod h1:o96djdrsSGy3AWPyBgZMAGfxZNfgntdJG+11KU4QvbU= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 340b946896..d1e1faa154 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -41,7 +41,7 @@ import ( "github.com/ava-labs/avalanchego/snow/validators/validatorstest" "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/avalanchego/utils/cb58" - "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/utils/crypto/bls/signer/localsigner" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/formatting" "github.com/ava-labs/avalanchego/utils/hashing" @@ -220,7 +220,7 @@ func NewContext() *snow.Context { return subnetID, nil }, } - blsSecretKey, err := bls.NewSigner() + blsSecretKey, err := localsigner.New() if err != nil { panic(err) } diff --git a/plugin/evm/vm_warp_test.go b/plugin/evm/vm_warp_test.go index e44f5ba606..79e82865a8 100644 --- a/plugin/evm/vm_warp_test.go +++ b/plugin/evm/vm_warp_test.go @@ -22,6 +22,7 @@ import ( avagoUtils "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/utils/crypto/bls/signer/localsigner" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/vms/components/chain" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" @@ -265,13 +266,13 @@ func testWarpVMTransaction(t *testing.T, unsignedMessage *avalancheWarp.Unsigned defer logsSub.Unsubscribe() nodeID1 := ids.GenerateTestNodeID() - blsSecretKey1, err := bls.NewSigner() + blsSecretKey1, err := localsigner.New() require.NoError(err) blsPublicKey1 := blsSecretKey1.PublicKey() blsSignature1 := blsSecretKey1.Sign(unsignedMessage.Bytes()) nodeID2 := ids.GenerateTestNodeID() - blsSecretKey2, err := bls.NewSigner() + blsSecretKey2, err := localsigner.New() require.NoError(err) blsPublicKey2 := blsSecretKey2.PublicKey() blsSignature2 := blsSecretKey2.Sign(unsignedMessage.Bytes()) @@ -528,7 +529,7 @@ func testReceiveWarpMessage( weight uint64 } newSigner := func(networkID ids.ID, weight uint64) signer { - secret, err := bls.NewSigner() + secret, err := localsigner.New() require.NoError(err) return signer{ networkID: networkID, diff --git a/precompile/contracts/warp/predicate_test.go b/precompile/contracts/warp/predicate_test.go index a5fe8265b7..17d0740796 100644 --- a/precompile/contracts/warp/predicate_test.go +++ b/precompile/contracts/warp/predicate_test.go @@ -17,6 +17,7 @@ import ( agoUtils "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/utils/crypto/bls/signer/localsigner" "github.com/ava-labs/avalanchego/utils/set" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" @@ -111,7 +112,7 @@ func (v *testValidator) Compare(o *testValidator) int { } func newTestValidator() *testValidator { - sk, err := bls.NewSigner() + sk, err := localsigner.New() if err != nil { panic(err) } diff --git a/scripts/versions.sh b/scripts/versions.sh index 42e3dcf479..fa2a939bc2 100644 --- a/scripts/versions.sh +++ b/scripts/versions.sh @@ -6,4 +6,4 @@ set -euo pipefail # Don't export them as they're used in the context of other calls -AVALANCHE_VERSION=${AVALANCHE_VERSION:-'54d8b06b'} +AVALANCHE_VERSION=${AVALANCHE_VERSION:-'7d2fd6ad3'} diff --git a/utils/snow.go b/utils/snow.go index 36b9b7b7fb..51498ef141 100644 --- a/utils/snow.go +++ b/utils/snow.go @@ -13,7 +13,7 @@ import ( "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/snow/validators/validatorstest" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/utils/crypto/bls/signer/localsigner" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/vms/platformvm/warp" ) @@ -25,7 +25,7 @@ var ( ) func TestSnowContext() *snow.Context { - sk, err := bls.NewSigner() + sk, err := localsigner.New() if err != nil { panic(err) } diff --git a/warp/aggregator/aggregator_test.go b/warp/aggregator/aggregator_test.go index 055d3edfa8..397e39553d 100644 --- a/warp/aggregator/aggregator_test.go +++ b/warp/aggregator/aggregator_test.go @@ -14,11 +14,12 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/utils/crypto/bls/signer/localsigner" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" ) func newValidator(t testing.TB, weight uint64) (bls.Signer, *avalancheWarp.Validator) { - sk, err := bls.NewSigner() + sk, err := localsigner.New() require.NoError(t, err) pk := sk.PublicKey() return sk, &avalancheWarp.Validator{ @@ -51,7 +52,7 @@ func TestAggregateSignatures(t *testing.T) { vdr2: sig2, vdr3: sig3, } - nonVdrSk, err := bls.NewSigner() + nonVdrSk, err := localsigner.New() require.NoError(t, err) nonVdrSig := nonVdrSk.Sign(unsignedMsg.Bytes()) vdrs := []*avalancheWarp.Validator{ diff --git a/warp/backend_test.go b/warp/backend_test.go index cd7aa1ea76..9b3de02cd5 100644 --- a/warp/backend_test.go +++ b/warp/backend_test.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils" - "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/utils/crypto/bls/signer/localsigner" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" "github.com/ava-labs/coreth/warp/warptest" @@ -41,7 +41,7 @@ func init() { func TestAddAndGetValidMessage(t *testing.T) { db := memdb.New() - sk, err := bls.NewSigner() + sk, err := localsigner.New() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 500} @@ -64,7 +64,7 @@ func TestAddAndGetValidMessage(t *testing.T) { func TestAddAndGetUnknownMessage(t *testing.T) { db := memdb.New() - sk, err := bls.NewSigner() + sk, err := localsigner.New() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 500} @@ -83,7 +83,7 @@ func TestGetBlockSignature(t *testing.T) { blockClient := warptest.MakeBlockClient(blkID) db := memdb.New() - sk, err := bls.NewSigner() + sk, err := localsigner.New() require.NoError(err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) messageSignatureCache := &cache.LRU[ids.ID, []byte]{Size: 500} @@ -108,7 +108,7 @@ func TestGetBlockSignature(t *testing.T) { func TestZeroSizedCache(t *testing.T) { db := memdb.New() - sk, err := bls.NewSigner() + sk, err := localsigner.New() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) @@ -136,7 +136,7 @@ func TestOffChainMessages(t *testing.T) { check func(require *require.Assertions, b Backend) err error } - sk, err := bls.NewSigner() + sk, err := localsigner.New() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(sk, networkID, sourceChainID) diff --git a/warp/handlers/signature_request_test.go b/warp/handlers/signature_request_test.go index 77a4af087e..0688809ed9 100644 --- a/warp/handlers/signature_request_test.go +++ b/warp/handlers/signature_request_test.go @@ -11,6 +11,7 @@ import ( "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/utils/crypto/bls/signer/localsigner" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" "github.com/ava-labs/coreth/plugin/evm/message" @@ -23,7 +24,7 @@ import ( func TestMessageSignatureHandler(t *testing.T) { database := memdb.New() snowCtx := utils.TestSnowContext() - blsSecretKey, err := bls.NewSigner() + blsSecretKey, err := localsigner.New() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) @@ -127,7 +128,7 @@ func TestMessageSignatureHandler(t *testing.T) { func TestBlockSignatureHandler(t *testing.T) { database := memdb.New() snowCtx := utils.TestSnowContext() - blsSecretKey, err := bls.NewSigner() + blsSecretKey, err := localsigner.New() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) diff --git a/warp/verifier_backend_test.go b/warp/verifier_backend_test.go index a58726aa0f..4f6564cf36 100644 --- a/warp/verifier_backend_test.go +++ b/warp/verifier_backend_test.go @@ -14,7 +14,7 @@ import ( "github.com/ava-labs/avalanchego/network/p2p/acp118" "github.com/ava-labs/avalanchego/proto/pb/sdk" "github.com/ava-labs/avalanchego/snow/engine/common" - "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/utils/crypto/bls/signer/localsigner" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" "github.com/ava-labs/coreth/utils" @@ -26,7 +26,7 @@ import ( func TestAddressedCallSignatures(t *testing.T) { database := memdb.New() snowCtx := utils.TestSnowContext() - blsSecretKey, err := bls.NewSigner() + blsSecretKey, err := localsigner.New() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) @@ -140,7 +140,7 @@ func TestAddressedCallSignatures(t *testing.T) { func TestBlockSignatures(t *testing.T) { database := memdb.New() snowCtx := utils.TestSnowContext() - blsSecretKey, err := bls.NewSigner() + blsSecretKey, err := localsigner.New() require.NoError(t, err) warpSigner := avalancheWarp.NewSigner(blsSecretKey, snowCtx.NetworkID, snowCtx.ChainID) From 584302d6627325344447c2e7bc68f97173cee62d Mon Sep 17 00:00:00 2001 From: Tsachi Herman <24438559+tsachiherman@users.noreply.github.com> Date: Wed, 29 Jan 2025 12:20:39 -0500 Subject: [PATCH 32/69] Update wrap.Verify interface changes (#769) --- go.mod | 2 +- go.sum | 4 +- precompile/contracts/warp/config.go | 38 +++++++----- precompile/contracts/warp/contract_test.go | 5 +- .../warp/signature_verification_test.go | 59 +++++++++++-------- scripts/versions.sh | 2 +- warp/service.go | 10 ++-- 7 files changed, 69 insertions(+), 51 deletions(-) diff --git a/go.mod b/go.mod index b4bd03102a..92e69d503f 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.22.8 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.12.3-0.20250128183416-7d2fd6ad37f4 + github.com/ava-labs/avalanchego v1.12.3-warp-verify4 github.com/cespare/cp v0.1.0 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 diff --git a/go.sum b/go.sum index 7f684d73b4..168caf4a40 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,8 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/avalanchego v1.12.3-0.20250128183416-7d2fd6ad37f4 h1:twEyoj604JLd0pmMktRjVixtdjxiYuTvQ5nHmP/BVzg= -github.com/ava-labs/avalanchego v1.12.3-0.20250128183416-7d2fd6ad37f4/go.mod h1:B7l4fA/BZL6VMC1HCtaHt1RpkC2HWxjAXxTZbc+n3ZI= +github.com/ava-labs/avalanchego v1.12.3-warp-verify4 h1:8YsFAZUC7PyvgZVpZe+kwpHBa7p1e3pDedS8/NeXQhU= +github.com/ava-labs/avalanchego v1.12.3-warp-verify4/go.mod h1:Er2qCyxI4qQKDlNjwwWdOa+/cxCbuEy/z8WgxtXy0N0= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/precompile/contracts/warp/config.go b/precompile/contracts/warp/config.go index ce90cf282c..23b3bbdbe3 100644 --- a/precompile/contracts/warp/config.go +++ b/precompile/contracts/warp/config.go @@ -31,16 +31,17 @@ var ( ) var ( - errOverflowSignersGasCost = errors.New("overflow calculating warp signers gas cost") - errInvalidPredicateBytes = errors.New("cannot unpack predicate bytes") - errInvalidWarpMsg = errors.New("cannot unpack warp message") - errCannotParseWarpMsg = errors.New("cannot parse warp message") - errInvalidWarpMsgPayload = errors.New("cannot unpack warp message payload") - errInvalidAddressedPayload = errors.New("cannot unpack addressed payload") - errInvalidBlockHashPayload = errors.New("cannot unpack block hash payload") - errCannotGetNumSigners = errors.New("cannot fetch num signers from warp message") - errWarpCannotBeActivated = errors.New("warp cannot be activated before Durango") - errFailedVerification = errors.New("cannot verify warp signature") + errOverflowSignersGasCost = errors.New("overflow calculating warp signers gas cost") + errInvalidPredicateBytes = errors.New("cannot unpack predicate bytes") + errInvalidWarpMsg = errors.New("cannot unpack warp message") + errCannotParseWarpMsg = errors.New("cannot parse warp message") + errInvalidWarpMsgPayload = errors.New("cannot unpack warp message payload") + errInvalidAddressedPayload = errors.New("cannot unpack addressed payload") + errInvalidBlockHashPayload = errors.New("cannot unpack block hash payload") + errCannotGetNumSigners = errors.New("cannot fetch num signers from warp message") + errWarpCannotBeActivated = errors.New("warp cannot be activated before Durango") + errFailedVerification = errors.New("cannot verify warp signature") + errCannotRetrieveValidatorSet = errors.New("cannot retrieve validator set") ) // Config implements the precompileconfig.Config interface and @@ -208,16 +209,25 @@ func (c *Config) VerifyPredicate(predicateContext *precompileconfig.PredicateCon warpMsg.SourceChainID, c.RequirePrimaryNetworkSigners, ) - err = warpMsg.Signature.Verify( + + validatorSet, err := warp.GetCanonicalValidatorSetFromChainID( context.Background(), - &warpMsg.UnsignedMessage, - predicateContext.SnowCtx.NetworkID, state, predicateContext.ProposerVMBlockCtx.PChainHeight, + warpMsg.UnsignedMessage.SourceChainID, + ) + if err != nil { + log.Debug("failed to retrieve canonical validator set", "msgID", warpMsg.ID(), "err", err) + return fmt.Errorf("%w: %w", errCannotRetrieveValidatorSet, err) + } + + err = warpMsg.Signature.Verify( + &warpMsg.UnsignedMessage, + predicateContext.SnowCtx.NetworkID, + validatorSet, quorumNumerator, WarpQuorumDenominator, ) - if err != nil { log.Debug("failed to verify warp signature", "msgID", warpMsg.ID(), "err", err) return fmt.Errorf("%w: %w", errFailedVerification, err) diff --git a/precompile/contracts/warp/contract_test.go b/precompile/contracts/warp/contract_test.go index 7650d5953a..a3bb563b3b 100644 --- a/precompile/contracts/warp/contract_test.go +++ b/precompile/contracts/warp/contract_test.go @@ -11,7 +11,6 @@ import ( "github.com/ava-labs/avalanchego/ids" agoUtils "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/set" - "github.com/ava-labs/avalanchego/vms/platformvm/warp" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" "github.com/ava-labs/coreth/core/state" @@ -96,7 +95,7 @@ func TestSendWarpMessage(t *testing.T) { sendWarpMessagePayload, ) require.NoError(t, err) - unsignedWarpMessage, err := warp.NewUnsignedMessage( + unsignedWarpMessage, err := avalancheWarp.NewUnsignedMessage( defaultSnowCtx.NetworkID, blockchainID, sendWarpMessageAddressedPayload.Bytes(), @@ -747,7 +746,7 @@ func TestPackEvents(t *testing.T) { ) require.NoError(t, err) - unsignedWarpMessage, err := warp.NewUnsignedMessage( + unsignedWarpMessage, err := avalancheWarp.NewUnsignedMessage( networkID, sourceChainID, addressedPayload.Bytes(), diff --git a/precompile/contracts/warp/signature_verification_test.go b/precompile/contracts/warp/signature_verification_test.go index d52f0a0f89..90ee808f91 100644 --- a/precompile/contracts/warp/signature_verification_test.go +++ b/precompile/contracts/warp/signature_verification_test.go @@ -19,12 +19,13 @@ import ( ) type signatureTest struct { - name string - stateF func(*gomock.Controller) validators.State - quorumNum uint64 - quorumDen uint64 - msgF func(*require.Assertions) *avalancheWarp.Message - err error + name string + stateF func(*gomock.Controller) validators.State + quorumNum uint64 + quorumDen uint64 + msgF func(*require.Assertions) *avalancheWarp.Message + verifyErr error + canonicalErr error } // This test copies the test coverage from https://github.com/ava-labs/avalanchego/blob/0117ab96/vms/platformvm/warp/signature_test.go#L137. @@ -55,7 +56,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: errTest, + canonicalErr: errTest, }, { name: "can't get validator set", @@ -82,7 +83,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: errTest, + canonicalErr: errTest, }, { name: "weight overflow", @@ -122,7 +123,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: avalancheWarp.ErrWeightOverflow, + canonicalErr: avalancheWarp.ErrWeightOverflow, }, { name: "invalid bit set index", @@ -152,7 +153,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: avalancheWarp.ErrInvalidBitSet, + verifyErr: avalancheWarp.ErrInvalidBitSet, }, { name: "unknown index", @@ -185,7 +186,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: avalancheWarp.ErrUnknownValidator, + verifyErr: avalancheWarp.ErrUnknownValidator, }, { name: "insufficient weight", @@ -229,7 +230,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: avalancheWarp.ErrInsufficientWeight, + verifyErr: avalancheWarp.ErrInsufficientWeight, }, { name: "can't parse sig", @@ -263,7 +264,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: avalancheWarp.ErrParseSignature, + verifyErr: avalancheWarp.ErrParseSignature, }, { name: "no validators", @@ -298,7 +299,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: bls.ErrNoPublicKeys, + verifyErr: bls.ErrNoPublicKeys, }, { name: "invalid signature (substitute)", @@ -342,7 +343,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: avalancheWarp.ErrInvalidSignature, + verifyErr: avalancheWarp.ErrInvalidSignature, }, { name: "invalid signature (missing one)", @@ -382,7 +383,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: avalancheWarp.ErrInvalidSignature, + verifyErr: avalancheWarp.ErrInvalidSignature, }, { name: "invalid signature (extra one)", @@ -427,7 +428,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: avalancheWarp.ErrInvalidSignature, + verifyErr: avalancheWarp.ErrInvalidSignature, }, { name: "valid signature", @@ -471,7 +472,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: nil, + verifyErr: nil, }, { name: "valid signature (boundary)", @@ -515,7 +516,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: nil, + verifyErr: nil, }, { name: "valid signature (missing key)", @@ -576,7 +577,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: nil, + verifyErr: nil, }, { name: "valid signature (duplicate key)", @@ -635,7 +636,7 @@ func TestSignatureVerification(t *testing.T) { require.NoError(err) return msg }, - err: nil, + verifyErr: nil, }, } @@ -648,16 +649,24 @@ func TestSignatureVerification(t *testing.T) { msg := tt.msgF(require) pChainState := tt.stateF(ctrl) - err := msg.Signature.Verify( + validatorSet, err := avalancheWarp.GetCanonicalValidatorSetFromChainID( context.Background(), - &msg.UnsignedMessage, - networkID, pChainState, pChainHeight, + msg.UnsignedMessage.SourceChainID, + ) + require.ErrorIs(err, tt.canonicalErr) + if err != nil { + return + } + err = msg.Signature.Verify( + &msg.UnsignedMessage, + networkID, + validatorSet, tt.quorumNum, tt.quorumDen, ) - require.ErrorIs(err, tt.err) + require.ErrorIs(err, tt.verifyErr) }) } } diff --git a/scripts/versions.sh b/scripts/versions.sh index fa2a939bc2..12aed7d162 100644 --- a/scripts/versions.sh +++ b/scripts/versions.sh @@ -6,4 +6,4 @@ set -euo pipefail # Don't export them as they're used in the context of other calls -AVALANCHE_VERSION=${AVALANCHE_VERSION:-'7d2fd6ad3'} +AVALANCHE_VERSION=${AVALANCHE_VERSION:-'2eea9338'} diff --git a/warp/service.go b/warp/service.go index 610fc85a91..01123950ff 100644 --- a/warp/service.go +++ b/warp/service.go @@ -112,22 +112,22 @@ func (a *API) aggregateSignatures(ctx context.Context, unsignedMessage *warp.Uns } state := warpValidators.NewState(a.state, a.sourceSubnetID, a.sourceChainID, a.requirePrimaryNetworkSigners()) - validators, totalWeight, err := warp.GetCanonicalValidatorSet(ctx, state, pChainHeight, subnetID) + validatorSet, err := warp.GetCanonicalValidatorSetFromSubnetID(ctx, state, pChainHeight, subnetID) if err != nil { return nil, fmt.Errorf("failed to get validator set: %w", err) } - if len(validators) == 0 { + if len(validatorSet.Validators) == 0 { return nil, fmt.Errorf("%w (SubnetID: %s, Height: %d)", errNoValidators, subnetID, pChainHeight) } log.Debug("Fetching signature", "sourceSubnetID", subnetID, "height", pChainHeight, - "numValidators", len(validators), - "totalWeight", totalWeight, + "numValidators", len(validatorSet.Validators), + "totalWeight", validatorSet.TotalWeight, ) - agg := aggregator.New(aggregator.NewSignatureGetter(a.client), validators, totalWeight) + agg := aggregator.New(aggregator.NewSignatureGetter(a.client), validatorSet.Validators, validatorSet.TotalWeight) signatureResult, err := agg.AggregateSignatures(ctx, unsignedMessage, quorumNum) if err != nil { return nil, err From 39ec874505b42a44e452b8809a2cc6d09098e84e Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Wed, 29 Jan 2025 14:17:39 -0500 Subject: [PATCH 33/69] Reduce magic numbers in dynamic fees (#773) --- consensus/dummy/dynamic_fees.go | 11 +++++------ params/avalanche_params.go | 5 +++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/consensus/dummy/dynamic_fees.go b/consensus/dummy/dynamic_fees.go index de273fbbb5..185c074074 100644 --- a/consensus/dummy/dynamic_fees.go +++ b/consensus/dummy/dynamic_fees.go @@ -32,7 +32,6 @@ var ( ApricotPhase4BlockGasCostStep = big.NewInt(50_000) ApricotPhase4TargetBlockRate uint64 = 2 // in seconds ApricotPhase5BlockGasCostStep = big.NewInt(200_000) - rollupWindow uint64 = 10 ) // CalcBaseFee takes the previous header and the timestamp of its child block @@ -87,7 +86,7 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin // Add in the gas used by the parent block in the correct place // If the parent consumed gas within the rollup window, add the consumed // gas in. - if roll < rollupWindow { + if roll < params.RollupWindow { var blockGasCost, parentExtraStateGasUsed uint64 switch { case isApricotPhase5: @@ -133,13 +132,13 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin } } - slot := rollupWindow - 1 - roll + slot := params.RollupWindow - 1 - roll start := slot * wrappers.LongLen updateLongWindow(newRollupWindow, start, addedGas) } // Calculate the amount of gas consumed within the rollup window. - totalGas := sumLongWindow(newRollupWindow, int(rollupWindow)) + totalGas := sumLongWindow(newRollupWindow, params.RollupWindow) if totalGas == parentGasTarget { return newRollupWindow, baseFee, nil @@ -167,9 +166,9 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin // for the interval during which no blocks were produced. // We use roll/rollupWindow, so that the transition is applied for every [rollupWindow] seconds // that has elapsed between the parent and this block. - if roll > rollupWindow { + if roll > params.RollupWindow { // Note: roll/rollupWindow must be greater than 1 since we've checked that roll > rollupWindow - baseFeeDelta = new(big.Int).Mul(baseFeeDelta, new(big.Int).SetUint64(roll/rollupWindow)) + baseFeeDelta = new(big.Int).Mul(baseFeeDelta, new(big.Int).SetUint64(roll/params.RollupWindow)) } baseFee.Sub(baseFee, baseFeeDelta) } diff --git a/params/avalanche_params.go b/params/avalanche_params.go index 897fb318f2..0d23acf765 100644 --- a/params/avalanche_params.go +++ b/params/avalanche_params.go @@ -7,6 +7,7 @@ import ( "math/big" "github.com/ava-labs/avalanchego/utils/units" + "github.com/ava-labs/avalanchego/utils/wrappers" ) // Minimum Gas Price @@ -32,8 +33,8 @@ const ( ApricotPhase5BaseFeeChangeDenominator uint64 = 36 EtnaMinBaseFee int64 = GWei - DynamicFeeExtraDataSize = 80 - RollupWindow uint64 = 10 + RollupWindow = 10 // in seconds + DynamicFeeExtraDataSize = wrappers.LongLen * RollupWindow // The base cost to charge per atomic transaction. Added in Apricot Phase 5. AtomicTxBaseCost uint64 = 10_000 From 2718ad14cf1adac5109c806bf032d04ce324968f Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Thu, 30 Jan 2025 11:27:32 -0500 Subject: [PATCH 34/69] Add F-Upgrade upgrades.Config support (#770) --- eth/tracers/api.go | 4 ++++ params/config.go | 49 ++++++++++++++++++++++++++++++++++++++ params/network_upgrades.go | 19 ++++++++++++++- plugin/evm/vm_test.go | 3 ++- 4 files changed, 73 insertions(+), 2 deletions(-) diff --git a/eth/tracers/api.go b/eth/tracers/api.go index 605a2495fe..f54727953f 100644 --- a/eth/tracers/api.go +++ b/eth/tracers/api.go @@ -1105,6 +1105,10 @@ func overrideConfig(original *params.ChainConfig, override *params.ChainConfig) copy.EtnaTimestamp = timestamp canon = false } + if timestamp := override.FUpgradeTimestamp; timestamp != nil { + copy.FUpgradeTimestamp = timestamp + canon = false + } if timestamp := override.CancunTime; timestamp != nil { copy.CancunTime = timestamp canon = false diff --git a/params/config.go b/params/config.go index c8211685d4..f95a815ef4 100644 --- a/params/config.go +++ b/params/config.go @@ -77,6 +77,7 @@ var ( CortinaBlockTimestamp: utils.NewUint64(0), DurangoBlockTimestamp: utils.NewUint64(0), EtnaTimestamp: utils.NewUint64(0), + FUpgradeTimestamp: utils.NewUint64(0), }, } @@ -107,6 +108,7 @@ var ( CortinaBlockTimestamp: nil, DurangoBlockTimestamp: nil, EtnaTimestamp: nil, + FUpgradeTimestamp: nil, }, } @@ -137,6 +139,7 @@ var ( CortinaBlockTimestamp: nil, DurangoBlockTimestamp: nil, EtnaTimestamp: nil, + FUpgradeTimestamp: nil, }, } @@ -168,6 +171,7 @@ var ( CortinaBlockTimestamp: nil, DurangoBlockTimestamp: nil, EtnaTimestamp: nil, + FUpgradeTimestamp: nil, }, } @@ -200,6 +204,7 @@ var ( CortinaBlockTimestamp: nil, DurangoBlockTimestamp: nil, EtnaTimestamp: nil, + FUpgradeTimestamp: nil, }, } @@ -232,6 +237,7 @@ var ( CortinaBlockTimestamp: nil, DurangoBlockTimestamp: nil, EtnaTimestamp: nil, + FUpgradeTimestamp: nil, }, } @@ -264,6 +270,7 @@ var ( CortinaBlockTimestamp: nil, DurangoBlockTimestamp: nil, EtnaTimestamp: nil, + FUpgradeTimestamp: nil, }, } @@ -296,6 +303,7 @@ var ( CortinaBlockTimestamp: nil, DurangoBlockTimestamp: nil, EtnaTimestamp: nil, + FUpgradeTimestamp: nil, }, } @@ -328,6 +336,7 @@ var ( CortinaBlockTimestamp: nil, DurangoBlockTimestamp: nil, EtnaTimestamp: nil, + FUpgradeTimestamp: nil, }, } @@ -360,6 +369,7 @@ var ( CortinaBlockTimestamp: nil, DurangoBlockTimestamp: nil, EtnaTimestamp: nil, + FUpgradeTimestamp: nil, }, } @@ -392,6 +402,7 @@ var ( CortinaBlockTimestamp: nil, DurangoBlockTimestamp: nil, EtnaTimestamp: nil, + FUpgradeTimestamp: nil, }, } @@ -424,6 +435,7 @@ var ( CortinaBlockTimestamp: utils.NewUint64(0), DurangoBlockTimestamp: nil, EtnaTimestamp: nil, + FUpgradeTimestamp: nil, }, } @@ -457,6 +469,7 @@ var ( CortinaBlockTimestamp: utils.NewUint64(0), DurangoBlockTimestamp: utils.NewUint64(0), EtnaTimestamp: nil, + FUpgradeTimestamp: nil, }, } @@ -491,6 +504,42 @@ var ( CortinaBlockTimestamp: utils.NewUint64(0), DurangoBlockTimestamp: utils.NewUint64(0), EtnaTimestamp: utils.NewUint64(0), + FUpgradeTimestamp: nil, + }, + } + + TestFUpgradeChainConfig = &ChainConfig{ + AvalancheContext: AvalancheContext{utils.TestSnowContext()}, + ChainID: big.NewInt(1), + HomesteadBlock: big.NewInt(0), + DAOForkBlock: nil, + DAOForkSupport: false, + EIP150Block: big.NewInt(0), + EIP155Block: big.NewInt(0), + EIP158Block: big.NewInt(0), + ByzantiumBlock: big.NewInt(0), + ConstantinopleBlock: big.NewInt(0), + PetersburgBlock: big.NewInt(0), + IstanbulBlock: big.NewInt(0), + MuirGlacierBlock: big.NewInt(0), + BerlinBlock: big.NewInt(0), + LondonBlock: big.NewInt(0), + ShanghaiTime: utils.NewUint64(0), + CancunTime: utils.NewUint64(0), + NetworkUpgrades: NetworkUpgrades{ + ApricotPhase1BlockTimestamp: utils.NewUint64(0), + ApricotPhase2BlockTimestamp: utils.NewUint64(0), + ApricotPhase3BlockTimestamp: utils.NewUint64(0), + ApricotPhase4BlockTimestamp: utils.NewUint64(0), + ApricotPhase5BlockTimestamp: utils.NewUint64(0), + ApricotPhasePre6BlockTimestamp: utils.NewUint64(0), + ApricotPhase6BlockTimestamp: utils.NewUint64(0), + ApricotPhasePost6BlockTimestamp: utils.NewUint64(0), + BanffBlockTimestamp: utils.NewUint64(0), + CortinaBlockTimestamp: utils.NewUint64(0), + DurangoBlockTimestamp: utils.NewUint64(0), + EtnaTimestamp: utils.NewUint64(0), + FUpgradeTimestamp: utils.NewUint64(0), }, } diff --git a/params/network_upgrades.go b/params/network_upgrades.go index 6af886b093..c01b1e084c 100644 --- a/params/network_upgrades.go +++ b/params/network_upgrades.go @@ -41,6 +41,9 @@ type NetworkUpgrades struct { // Note: EIP-4844 BlobTxs are not enabled in the mempool and blocks are not // allowed to contain them. For details see https://github.com/avalanche-foundation/ACPs/pull/131 EtnaTimestamp *uint64 `json:"etnaTimestamp,omitempty"` + // FUpgrade is a placeholder for the next upgrade. + // (nil = no fork, 0 = already activated) + FUpgradeTimestamp *uint64 `json:"fUpgradeTimestamp,omitempty"` } func (n *NetworkUpgrades) Equal(other *NetworkUpgrades) bool { @@ -84,6 +87,9 @@ func (n *NetworkUpgrades) CheckNetworkUpgradesCompatible(newcfg *NetworkUpgrades if isForkTimestampIncompatible(n.EtnaTimestamp, newcfg.EtnaTimestamp, time) { return newTimestampCompatError("Etna fork block timestamp", n.EtnaTimestamp, newcfg.EtnaTimestamp) } + if isForkTimestampIncompatible(n.FUpgradeTimestamp, newcfg.FUpgradeTimestamp, time) { + return newTimestampCompatError("F-Upgrade fork block timestamp", n.FUpgradeTimestamp, newcfg.FUpgradeTimestamp) + } return nil } @@ -102,6 +108,7 @@ func (n *NetworkUpgrades) forkOrder() []fork { {name: "cortinaBlockTimestamp", timestamp: n.CortinaBlockTimestamp}, {name: "durangoBlockTimestamp", timestamp: n.DurangoBlockTimestamp}, {name: "etnaTimestamp", timestamp: n.EtnaTimestamp}, + {name: "fUpgradeTimestamp", timestamp: n.FUpgradeTimestamp}, } } @@ -177,6 +184,12 @@ func (n *NetworkUpgrades) IsEtna(time uint64) bool { return isTimestampForked(n.EtnaTimestamp, time) } +// IsFUpgrade returns whether [time] represents a block +// with a timestamp after the F upgrade time. +func (n *NetworkUpgrades) IsFUpgrade(time uint64) bool { + return isTimestampForked(n.FUpgradeTimestamp, time) +} + func (n *NetworkUpgrades) Description() string { var banner string banner += fmt.Sprintf(" - Apricot Phase 1 Timestamp: @%-10v (https://github.com/ava-labs/avalanchego/releases/tag/v1.3.0)\n", ptrToString(n.ApricotPhase1BlockTimestamp)) @@ -190,7 +203,8 @@ func (n *NetworkUpgrades) Description() string { banner += fmt.Sprintf(" - Banff Timestamp: @%-10v (https://github.com/ava-labs/avalanchego/releases/tag/v1.9.0)\n", ptrToString(n.BanffBlockTimestamp)) banner += fmt.Sprintf(" - Cortina Timestamp: @%-10v (https://github.com/ava-labs/avalanchego/releases/tag/v1.10.0)\n", ptrToString(n.CortinaBlockTimestamp)) banner += fmt.Sprintf(" - Durango Timestamp: @%-10v (https://github.com/ava-labs/avalanchego/releases/tag/v1.11.0)\n", ptrToString(n.DurangoBlockTimestamp)) - banner += fmt.Sprintf(" - Etna Timestamp: @%-10v (https://github.com/ava-labs/avalanchego/releases/tag/v1.12.0)\n", ptrToString(n.EtnaTimestamp)) + banner += fmt.Sprintf(" - Etna Timestamp: @%-10v (https://github.com/ava-labs/avalanchego/releases/tag/v1.12.0)\n", ptrToString(n.EtnaTimestamp)) + banner += fmt.Sprintf(" - F-Upgrade Timestamp: @%-10v (Unscheduled)\n", ptrToString(n.FUpgradeTimestamp)) return banner } @@ -208,6 +222,7 @@ func getNetworkUpgrades(agoUpgrade upgrade.Config) NetworkUpgrades { CortinaBlockTimestamp: utils.TimeToNewUint64(agoUpgrade.CortinaTime), DurangoBlockTimestamp: utils.TimeToNewUint64(agoUpgrade.DurangoTime), EtnaTimestamp: utils.TimeToNewUint64(agoUpgrade.EtnaTime), + FUpgradeTimestamp: utils.TimeToNewUint64(agoUpgrade.FUpgradeTime), } } @@ -218,6 +233,7 @@ type AvalancheRules struct { IsCortina bool IsDurango bool IsEtna bool + IsFUpgrade bool } func (n *NetworkUpgrades) GetAvalancheRules(timestamp uint64) AvalancheRules { @@ -234,5 +250,6 @@ func (n *NetworkUpgrades) GetAvalancheRules(timestamp uint64) AvalancheRules { IsCortina: n.IsCortina(timestamp), IsDurango: n.IsDurango(timestamp), IsEtna: n.IsEtna(timestamp), + IsFUpgrade: n.IsFUpgrade(timestamp), } } diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index d1e1faa154..9acc363533 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -126,7 +126,8 @@ var ( genesisJSONCortina = genesisJSON(params.TestCortinaChainConfig) genesisJSONDurango = genesisJSON(params.TestDurangoChainConfig) genesisJSONEtna = genesisJSON(params.TestEtnaChainConfig) - genesisJSONLatest = genesisJSONEtna + genesisJSONFUpgrade = genesisJSON(params.TestFUpgradeChainConfig) + genesisJSONLatest = genesisJSONFUpgrade genesisJSONCancun = genesisJSON(activateCancun(params.TestChainConfig)) From 235e9a5d04ed31f43b22a1ac7598b14e6ba85ba0 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Fri, 31 Jan 2025 14:31:05 -0500 Subject: [PATCH 35/69] Cleanup dynamic fee windower logic (#774) --- consensus/dummy/dynamic_fee_window.go | 88 ++++++++ consensus/dummy/dynamic_fee_window_test.go | 246 +++++++++++++++++++++ consensus/dummy/dynamic_fees.go | 182 ++++----------- consensus/dummy/dynamic_fees_test.go | 125 ----------- 4 files changed, 378 insertions(+), 263 deletions(-) create mode 100644 consensus/dummy/dynamic_fee_window.go create mode 100644 consensus/dummy/dynamic_fee_window_test.go diff --git a/consensus/dummy/dynamic_fee_window.go b/consensus/dummy/dynamic_fee_window.go new file mode 100644 index 0000000000..8c56ba3a29 --- /dev/null +++ b/consensus/dummy/dynamic_fee_window.go @@ -0,0 +1,88 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package dummy + +import ( + "encoding/binary" + "errors" + "fmt" + + "github.com/ava-labs/avalanchego/utils/wrappers" + "github.com/ava-labs/coreth/params" + "github.com/ethereum/go-ethereum/common/math" +) + +var ErrDynamicFeeWindowInsufficientLength = errors.New("insufficient length for dynamic fee window") + +// DynamicFeeWindow is a window of the last [params.RollupWindow] seconds of gas +// usage. +// +// Index 0 is the oldest entry, and [params.RollupWindow]-1 is the current +// entry. +type DynamicFeeWindow [params.RollupWindow]uint64 + +func ParseDynamicFeeWindow(bytes []byte) (DynamicFeeWindow, error) { + if len(bytes) < params.DynamicFeeExtraDataSize { + return DynamicFeeWindow{}, fmt.Errorf("%w: expected at least %d bytes but got %d bytes", + ErrDynamicFeeWindowInsufficientLength, + params.DynamicFeeExtraDataSize, + len(bytes), + ) + } + + var window DynamicFeeWindow + for i := range window { + offset := i * wrappers.LongLen + window[i] = binary.BigEndian.Uint64(bytes[offset:]) + } + return window, nil +} + +// Add adds the amounts to the most recent entry in the window. +// +// If the most recent entry overflows, it is set to [math.MaxUint64]. +func (w *DynamicFeeWindow) Add(amounts ...uint64) { + const lastIndex uint = params.RollupWindow - 1 + w[lastIndex] = add(w[lastIndex], amounts...) +} + +// Shift removes the oldest n entries from the window and adds n new empty +// entries. +func (w *DynamicFeeWindow) Shift(n uint64) { + if n >= params.RollupWindow { + *w = DynamicFeeWindow{} + return + } + + var newWindow DynamicFeeWindow + copy(newWindow[:], w[n:]) + *w = newWindow +} + +// Sum returns the sum of all the entries in the window. +// +// If the sum overflows, [math.MaxUint64] is returned. +func (w *DynamicFeeWindow) Sum() uint64 { + return add(0, w[:]...) +} + +func (w *DynamicFeeWindow) Bytes() []byte { + bytes := make([]byte, params.DynamicFeeExtraDataSize) + for i, v := range w { + offset := i * wrappers.LongLen + binary.BigEndian.PutUint64(bytes[offset:], v) + } + return bytes +} + +func add(sum uint64, values ...uint64) uint64 { + var overflow bool + for _, v := range values { + sum, overflow = math.SafeAdd(sum, v) + if overflow { + return math.MaxUint64 + } + } + return sum +} diff --git a/consensus/dummy/dynamic_fee_window_test.go b/consensus/dummy/dynamic_fee_window_test.go new file mode 100644 index 0000000000..b3ec2297e6 --- /dev/null +++ b/consensus/dummy/dynamic_fee_window_test.go @@ -0,0 +1,246 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package dummy + +import ( + "strconv" + "testing" + + "github.com/ava-labs/coreth/params" + "github.com/ethereum/go-ethereum/common/math" + "github.com/stretchr/testify/require" +) + +func TestDynamicFeeWindow_Add(t *testing.T) { + tests := []struct { + name string + window DynamicFeeWindow + amount uint64 + expected DynamicFeeWindow + }{ + { + name: "normal_addition", + window: DynamicFeeWindow{ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + }, + amount: 5, + expected: DynamicFeeWindow{ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 15, + }, + }, + { + name: "amount_overflow", + window: DynamicFeeWindow{ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + }, + amount: math.MaxUint64, + expected: DynamicFeeWindow{ + 1, 2, 3, 4, 5, 6, 7, 8, 9, math.MaxUint64, + }, + }, + { + name: "window_overflow", + window: DynamicFeeWindow{ + 1, 2, 3, 4, 5, 6, 7, 8, 9, math.MaxUint64, + }, + amount: 5, + expected: DynamicFeeWindow{ + 1, 2, 3, 4, 5, 6, 7, 8, 9, math.MaxUint64, + }, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + test.window.Add(test.amount) + require.Equal(t, test.expected, test.window) + }) + } +} + +func TestDynamicFeeWindow_Shift(t *testing.T) { + window := DynamicFeeWindow{ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + } + tests := []struct { + n uint64 + expected DynamicFeeWindow + }{ + { + n: 0, + expected: window, + }, + { + n: 1, + expected: DynamicFeeWindow{ + 2, 3, 4, 5, 6, 7, 8, 9, 10, + }, + }, + { + n: 2, + expected: DynamicFeeWindow{ + 3, 4, 5, 6, 7, 8, 9, 10, + }, + }, + { + n: 3, + expected: DynamicFeeWindow{ + 4, 5, 6, 7, 8, 9, 10, + }, + }, + { + n: 4, + expected: DynamicFeeWindow{ + 5, 6, 7, 8, 9, 10, + }, + }, + { + n: 5, + expected: DynamicFeeWindow{ + 6, 7, 8, 9, 10, + }, + }, + { + n: 6, + expected: DynamicFeeWindow{ + 7, 8, 9, 10, + }, + }, + { + n: 7, + expected: DynamicFeeWindow{ + 8, 9, 10, + }, + }, + { + n: 8, + expected: DynamicFeeWindow{ + 9, 10, + }, + }, + { + n: 9, + expected: DynamicFeeWindow{ + 10, + }, + }, + { + n: 10, + expected: DynamicFeeWindow{}, + }, + { + n: 100, + expected: DynamicFeeWindow{}, + }, + } + for _, test := range tests { + t.Run(strconv.FormatUint(test.n, 10), func(t *testing.T) { + window := window + window.Shift(test.n) + require.Equal(t, test.expected, window) + }) + } +} + +func TestDynamicFeeWindow_Sum(t *testing.T) { + tests := []struct { + name string + window DynamicFeeWindow + expected uint64 + }{ + { + name: "empty", + window: DynamicFeeWindow{}, + expected: 0, + }, + { + name: "full", + window: DynamicFeeWindow{ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + }, + expected: 55, + }, + { + name: "overflow", + window: DynamicFeeWindow{ + math.MaxUint64, 2, 3, 4, 5, 6, 7, 8, 9, 10, + }, + expected: math.MaxUint64, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require.Equal(t, test.expected, test.window.Sum()) + }) + } +} + +func TestDynamicFeeWindow_Bytes(t *testing.T) { + tests := []struct { + name string + bytes []byte + window DynamicFeeWindow + parseErr error + }{ + { + name: "insufficient_length", + bytes: make([]byte, params.DynamicFeeExtraDataSize-1), + parseErr: ErrDynamicFeeWindowInsufficientLength, + }, + { + name: "zero_window", + bytes: make([]byte, params.DynamicFeeExtraDataSize), + window: DynamicFeeWindow{}, + }, + { + name: "truncate_bytes", + bytes: []byte{ + params.DynamicFeeExtraDataSize: 1, + }, + window: DynamicFeeWindow{}, + }, + { + name: "endianess", + bytes: []byte{ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, + 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, + 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, + 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, + 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, + }, + window: DynamicFeeWindow{ + 0x0102030405060708, + 0x1112131415161718, + 0x2122232425262728, + 0x3132333435363738, + 0x4142434445464748, + 0x5152535455565758, + 0x6162636465666768, + 0x7172737475767778, + 0x8182838485868788, + 0x9192939495969798, + }, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require := require.New(t) + + window, err := ParseDynamicFeeWindow(test.bytes) + require.Equal(test.window, window) + require.ErrorIs(err, test.parseErr) + if test.parseErr != nil { + return + } + + expectedBytes := test.bytes[:params.DynamicFeeExtraDataSize] + bytes := window.Bytes() + require.Equal(expectedBytes, bytes) + }) + } +} diff --git a/consensus/dummy/dynamic_fees.go b/consensus/dummy/dynamic_fees.go index 185c074074..7402195b9e 100644 --- a/consensus/dummy/dynamic_fees.go +++ b/consensus/dummy/dynamic_fees.go @@ -4,11 +4,9 @@ package dummy import ( - "encoding/binary" "fmt" "math/big" - "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ethereum/go-ethereum/common" @@ -48,29 +46,17 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin isEtna = config.IsEtna(parent.Time) ) if !isApricotPhase3 || parent.Number.Cmp(common.Big0) == 0 { - initialSlice := make([]byte, params.DynamicFeeExtraDataSize) + initialSlice := (&DynamicFeeWindow{}).Bytes() initialBaseFee := big.NewInt(params.ApricotPhase3InitialBaseFee) return initialSlice, initialBaseFee, nil } - if uint64(len(parent.Extra)) < params.DynamicFeeExtraDataSize { - return nil, nil, fmt.Errorf("expected length of parent extra data to be %d, but found %d", params.DynamicFeeExtraDataSize, len(parent.Extra)) - } - dynamicFeeWindow := parent.Extra[:params.DynamicFeeExtraDataSize] - - if timestamp < parent.Time { - return nil, nil, fmt.Errorf("cannot calculate base fee for timestamp (%d) prior to parent timestamp (%d)", timestamp, parent.Time) - } - roll := timestamp - parent.Time - - // roll the window over by the difference between the timestamps to generate - // the new rollup window. - newRollupWindow, err := rollLongWindow(dynamicFeeWindow, int(roll)) + dynamicFeeWindow, err := ParseDynamicFeeWindow(parent.Extra) if err != nil { return nil, nil, err } - // If AP5, use a less responsive [BaseFeeChangeDenominator] and a higher gas + // If AP5, use a less responsive BaseFeeChangeDenominator and a higher gas // block limit var ( baseFee = new(big.Int).Set(parent.BaseFee) @@ -83,65 +69,55 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin } parentGasTargetBig := new(big.Int).SetUint64(parentGasTarget) - // Add in the gas used by the parent block in the correct place - // If the parent consumed gas within the rollup window, add the consumed - // gas in. - if roll < params.RollupWindow { - var blockGasCost, parentExtraStateGasUsed uint64 - switch { - case isApricotPhase5: - // [blockGasCost] has been removed in AP5, so it is left as 0. - - // At the start of a new network, the parent - // may not have a populated [ExtDataGasUsed]. - if parent.ExtDataGasUsed != nil { - parentExtraStateGasUsed = parent.ExtDataGasUsed.Uint64() - } - case isApricotPhase4: - // The [blockGasCost] is paid by the effective tips in the block using - // the block's value of [baseFee]. - blockGasCost = calcBlockGasCost( - ApricotPhase4TargetBlockRate, - ApricotPhase4MinBlockGasCost, - ApricotPhase4MaxBlockGasCost, - ApricotPhase4BlockGasCostStep, - parent.BlockGasCost, - parent.Time, timestamp, - ).Uint64() + // Add in parent's consumed gas + var blockGasCost, parentExtraStateGasUsed uint64 + switch { + case isApricotPhase5: + // blockGasCost has been removed in AP5, so it is left as 0. - // On the boundary of AP3 and AP4 or at the start of a new network, the parent - // may not have a populated [ExtDataGasUsed]. - if parent.ExtDataGasUsed != nil { - parentExtraStateGasUsed = parent.ExtDataGasUsed.Uint64() - } - default: - blockGasCost = ApricotPhase3BlockGasFee + // At the start of a new network, the parent + // may not have a populated ExtDataGasUsed. + if parent.ExtDataGasUsed != nil { + parentExtraStateGasUsed = parent.ExtDataGasUsed.Uint64() } - - // Compute the new state of the gas rolling window. - addedGas, overflow := math.SafeAdd(parent.GasUsed, parentExtraStateGasUsed) - if overflow { - addedGas = math.MaxUint64 + case isApricotPhase4: + // The blockGasCost is paid by the effective tips in the block using + // the block's value of baseFee. + blockGasCost = calcBlockGasCost( + ApricotPhase4TargetBlockRate, + ApricotPhase4MinBlockGasCost, + ApricotPhase4MaxBlockGasCost, + ApricotPhase4BlockGasCostStep, + parent.BlockGasCost, + parent.Time, timestamp, + ).Uint64() + + // On the boundary of AP3 and AP4 or at the start of a new network, the + // parent may not have a populated ExtDataGasUsed. + if parent.ExtDataGasUsed != nil { + parentExtraStateGasUsed = parent.ExtDataGasUsed.Uint64() } + default: + blockGasCost = ApricotPhase3BlockGasFee + } - // Only add the [blockGasCost] to the gas used if it isn't AP5 - if !isApricotPhase5 { - addedGas, overflow = math.SafeAdd(addedGas, blockGasCost) - if overflow { - addedGas = math.MaxUint64 - } - } + // Compute the new state of the gas rolling window. + dynamicFeeWindow.Add(parent.GasUsed, parentExtraStateGasUsed, blockGasCost) - slot := params.RollupWindow - 1 - roll - start := slot * wrappers.LongLen - updateLongWindow(newRollupWindow, start, addedGas) + if timestamp < parent.Time { + return nil, nil, fmt.Errorf("cannot calculate base fee for timestamp %d prior to parent timestamp %d", timestamp, parent.Time) } + roll := timestamp - parent.Time - // Calculate the amount of gas consumed within the rollup window. - totalGas := sumLongWindow(newRollupWindow, params.RollupWindow) + // roll the window over by the difference between the timestamps to generate + // the new rollup window. + dynamicFeeWindow.Shift(roll) + dynamicFeeWindowBytes := dynamicFeeWindow.Bytes() + // Calculate the amount of gas consumed within the rollup window. + totalGas := dynamicFeeWindow.Sum() if totalGas == parentGasTarget { - return newRollupWindow, baseFee, nil + return dynamicFeeWindowBytes, baseFee, nil } num := new(big.Int) @@ -185,7 +161,7 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin baseFee = selectBigWithinBounds(ApricotPhase3MinBaseFee, baseFee, ApricotPhase3MaxBaseFee) } - return newRollupWindow, baseFee, nil + return dynamicFeeWindowBytes, baseFee, nil } // EstimateNextBaseFee attempts to estimate the next base fee based on a block with [parent] being built at @@ -214,76 +190,6 @@ func selectBigWithinBounds(lowerBound, value, upperBound *big.Int) *big.Int { } } -// rollWindow rolls the longs within [consumptionWindow] over by [roll] places. -// For example, if there are 4 longs encoded in a 32 byte slice, rollWindow would -// have the following effect: -// Original: -// [1, 2, 3, 4] -// Roll = 0 -// [1, 2, 3, 4] -// Roll = 1 -// [2, 3, 4, 0] -// Roll = 2 -// [3, 4, 0, 0] -// Roll = 3 -// [4, 0, 0, 0] -// Roll >= 4 -// [0, 0, 0, 0] -// Assumes that [roll] is greater than or equal to 0 -func rollWindow(consumptionWindow []byte, size, roll int) ([]byte, error) { - if len(consumptionWindow)%size != 0 { - return nil, fmt.Errorf("expected consumption window length (%d) to be a multiple of size (%d)", len(consumptionWindow), size) - } - - // Note: make allocates a zeroed array, so we are guaranteed - // that what we do not copy into, will be set to 0 - res := make([]byte, len(consumptionWindow)) - bound := roll * size - if bound > len(consumptionWindow) { - return res, nil - } - copy(res[:], consumptionWindow[roll*size:]) - return res, nil -} - -func rollLongWindow(consumptionWindow []byte, roll int) ([]byte, error) { - // Passes in [wrappers.LongLen] as the size of the individual value to be rolled over - // so that it can be used to roll an array of long values. - return rollWindow(consumptionWindow, wrappers.LongLen, roll) -} - -// sumLongWindow sums [numLongs] encoded in [window]. Assumes that the length of [window] -// is sufficient to contain [numLongs] or else this function panics. -// If an overflow occurs, while summing the contents, the maximum uint64 value is returned. -func sumLongWindow(window []byte, numLongs int) uint64 { - var ( - sum uint64 = 0 - overflow bool - ) - for i := 0; i < numLongs; i++ { - // If an overflow occurs while summing the elements of the window, return the maximum - // uint64 value immediately. - sum, overflow = math.SafeAdd(sum, binary.BigEndian.Uint64(window[wrappers.LongLen*i:])) - if overflow { - return math.MaxUint64 - } - } - return sum -} - -// updateLongWindow adds [gasConsumed] in at index within [window]. -// Assumes that [index] has already been validated. -// If an overflow occurs, the maximum uint64 value is used. -func updateLongWindow(window []byte, start uint64, gasConsumed uint64) { - prevGasConsumed := binary.BigEndian.Uint64(window[start:]) - - totalGasConsumed, overflow := math.SafeAdd(prevGasConsumed, gasConsumed) - if overflow { - totalGasConsumed = math.MaxUint64 - } - binary.BigEndian.PutUint64(window[start:], totalGasConsumed) -} - // calcBlockGasCost calculates the required block gas cost. If [parentTime] // > [currentTime], the timeElapsed will be treated as 0. func calcBlockGasCost( diff --git a/consensus/dummy/dynamic_fees_test.go b/consensus/dummy/dynamic_fees_test.go index c86daf0ffb..6207c01ed6 100644 --- a/consensus/dummy/dynamic_fees_test.go +++ b/consensus/dummy/dynamic_fees_test.go @@ -4,7 +4,6 @@ package dummy import ( - "encoding/binary" "math/big" "testing" @@ -17,83 +16,6 @@ import ( "github.com/stretchr/testify/require" ) -func testRollup(t *testing.T, longs []uint64, roll int) { - slice := make([]byte, len(longs)*8) - numLongs := len(longs) - for i := 0; i < numLongs; i++ { - binary.BigEndian.PutUint64(slice[8*i:], longs[i]) - } - - newSlice, err := rollLongWindow(slice, roll) - if err != nil { - t.Fatal(err) - } - // numCopies is the number of longs that should have been copied over from the previous - // slice as opposed to being left empty. - numCopies := numLongs - roll - for i := 0; i < numLongs; i++ { - // Extract the long value that is encoded at position [i] in [newSlice] - num := binary.BigEndian.Uint64(newSlice[8*i:]) - // If the current index is past the point where we should have copied the value - // over from the previous slice, assert that the value encoded in [newSlice] - // is 0 - if i >= numCopies { - if num != 0 { - t.Errorf("Expected num encoded in newSlice at position %d to be 0, but found %d", i, num) - } - } else { - // Otherwise, check that the value was copied over correctly - prevIndex := i + roll - prevNum := longs[prevIndex] - if prevNum != num { - t.Errorf("Expected num encoded in new slice at position %d to be %d, but found %d", i, prevNum, num) - } - } - } -} - -func TestRollupWindow(t *testing.T) { - type test struct { - longs []uint64 - roll int - } - - var tests []test = []test{ - { - []uint64{1, 2, 3, 4}, - 0, - }, - { - []uint64{1, 2, 3, 4}, - 1, - }, - { - []uint64{1, 2, 3, 4}, - 2, - }, - { - []uint64{1, 2, 3, 4}, - 3, - }, - { - []uint64{1, 2, 3, 4}, - 4, - }, - { - []uint64{1, 2, 3, 4}, - 5, - }, - { - []uint64{121, 232, 432}, - 2, - }, - } - - for _, test := range tests { - testRollup(t, test.longs, test.roll) - } -} - type blockDefinition struct { timestamp uint64 gasUsed uint64 @@ -227,53 +149,6 @@ func testDynamicFeesStaysWithinRange(t *testing.T, test test) { } } -func TestLongWindow(t *testing.T) { - longs := []uint64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - sumLongs := uint64(0) - longWindow := make([]byte, 10*8) - for i, long := range longs { - sumLongs = sumLongs + long - binary.BigEndian.PutUint64(longWindow[i*8:], long) - } - - sum := sumLongWindow(longWindow, 10) - if sum != sumLongs { - t.Fatalf("Expected sum to be %d but found %d", sumLongs, sum) - } - - for i := uint64(0); i < 10; i++ { - updateLongWindow(longWindow, i*8, i) - sum = sumLongWindow(longWindow, 10) - sumLongs += i - - if sum != sumLongs { - t.Fatalf("Expected sum to be %d but found %d (iteration: %d)", sumLongs, sum, i) - } - } -} - -func TestLongWindowOverflow(t *testing.T) { - longs := []uint64{0, 0, 0, 0, 0, 0, 0, 0, 2, math.MaxUint64 - 1} - longWindow := make([]byte, 10*8) - for i, long := range longs { - binary.BigEndian.PutUint64(longWindow[i*8:], long) - } - - sum := sumLongWindow(longWindow, 10) - if sum != math.MaxUint64 { - t.Fatalf("Expected sum to be maxUint64 (%d), but found %d", uint64(math.MaxUint64), sum) - } - - for i := uint64(0); i < 10; i++ { - updateLongWindow(longWindow, i*8, i) - sum = sumLongWindow(longWindow, 10) - - if sum != math.MaxUint64 { - t.Fatalf("Expected sum to be maxUint64 (%d), but found %d", uint64(math.MaxUint64), sum) - } - } -} - func TestSelectBigWithinBounds(t *testing.T) { type test struct { lower, value, upper, expected *big.Int From 4b33be03bea98acf7163ca5c3873e2c162daea91 Mon Sep 17 00:00:00 2001 From: Quentin McGaw Date: Mon, 10 Feb 2025 08:39:45 +0100 Subject: [PATCH 36/69] chore(plugin/evm): remove `core.BoundedBuffer` from `atomicTrie` (#767) - Bounded buffer of length 1 can be replaced with a single field - Remove the atomic trie dependency on the `core` package --- plugin/evm/atomic_trie.go | 19 ++-- plugin/evm/atomic_trie_test.go | 171 +++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+), 11 deletions(-) diff --git a/plugin/evm/atomic_trie.go b/plugin/evm/atomic_trie.go index f6add46623..2ef09a7f32 100644 --- a/plugin/evm/atomic_trie.go +++ b/plugin/evm/atomic_trie.go @@ -14,7 +14,6 @@ import ( "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/plugin/evm/atomic" @@ -33,8 +32,7 @@ const ( atomicKeyLength = wrappers.LongLen + common.HashLength sharedMemoryApplyBatchSize = 10_000 // specifies the number of atomic operations to batch progress updates - atomicTrieTipBufferSize = 1 // No need to support a buffer of previously accepted tries for the atomic trie - atomicTrieMemoryCap = 64 * units.MiB + atomicTrieMemoryCap = 64 * units.MiB ) var ( @@ -126,7 +124,6 @@ type atomicTrie struct { lastAcceptedRoot common.Hash // most recent trie root passed to accept trie or the root of the atomic trie on intialization. codec codec.Manager memoryCap common.StorageSize - tipBuffer *core.BoundedBuffer[common.Hash] } // newAtomicTrie returns a new instance of a atomicTrie with a configurable commitHeightInterval, used in testing. @@ -169,7 +166,6 @@ func newAtomicTrie( codec: codec, lastCommittedRoot: root, lastCommittedHeight: height, - tipBuffer: core.NewBoundedBuffer(atomicTrieTipBufferSize, trieDB.Dereference), memoryCap: atomicTrieMemoryCap, // Initialize lastAcceptedRoot to the last committed root. // If there were further blocks processed (ahead of the commit interval), @@ -354,12 +350,6 @@ func (a *atomicTrie) AcceptTrie(height uint64, root common.Hash) (bool, error) { hasCommitted = true } - // Attempt to dereference roots at least [tipBufferSize] old - // - // Note: It is safe to dereference roots that have been committed to disk - // (they are no-ops). - a.tipBuffer.Insert(root) - // Commit this root if we have reached the [commitInterval]. if height%a.commitInterval == 0 { if err := a.commit(height, root); err != nil { @@ -368,6 +358,13 @@ func (a *atomicTrie) AcceptTrie(height uint64, root common.Hash) (bool, error) { hasCommitted = true } + // The following dereferences, if any, the previously inserted root. + // This one can be dereferenced whether it has been: + // - committed, in which case the dereference is a no-op + // - not committted, in which case the current root we are inserting contains + // references to all the relevant data from the previous root, so the previous + // root can be dereferenced. + a.trieDB.Dereference(a.lastAcceptedRoot) a.lastAcceptedRoot = root return hasCommitted, nil } diff --git a/plugin/evm/atomic_trie_test.go b/plugin/evm/atomic_trie_test.go index 2a82964e94..71d62ef7ca 100644 --- a/plugin/evm/atomic_trie_test.go +++ b/plugin/evm/atomic_trie_test.go @@ -5,23 +5,29 @@ package evm import ( "encoding/binary" + "encoding/hex" "testing" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/leveldb" "github.com/ava-labs/avalanchego/database/memdb" + "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/wrappers" + "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/plugin/evm/atomic" + "github.com/ava-labs/coreth/trie/trienode" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/rlp" ) const testCommitInterval = 100 @@ -591,6 +597,171 @@ func TestApplyToSharedMemory(t *testing.T) { } } +func TestAtomicTrie_AcceptTrie(t *testing.T) { + t.Parallel() + + testCases := map[string]struct { + lastAcceptedRoot common.Hash + lastCommittedRoot common.Hash + lastCommittedHeight uint64 + commitInterval uint64 + height uint64 + root common.Hash + wantHasCommitted bool + wantLastCommittedHeight uint64 + wantLastCommittedRoot common.Hash + wantLastAcceptedRoot common.Hash + wantTipBufferRoot common.Hash + wantMetadataDBKVs map[string]string // hex to hex + }{ + "no_committing": { + lastAcceptedRoot: types.EmptyRootHash, + lastCommittedRoot: common.Hash{2}, + lastCommittedHeight: 100, + commitInterval: 10, + height: 105, + root: common.Hash{3}, + wantLastCommittedHeight: 100, + wantLastCommittedRoot: common.Hash{2}, + wantLastAcceptedRoot: common.Hash{3}, + wantTipBufferRoot: common.Hash{3}, + wantMetadataDBKVs: map[string]string{ + "0000000000000064": hex.EncodeToString(common.Hash{2}.Bytes()), // height 100 + hex.EncodeToString(lastCommittedKey): "0000000000000064", // height 100 + }, + }, + "no_committing_with_previous_root": { + lastAcceptedRoot: common.Hash{1}, + lastCommittedRoot: common.Hash{2}, + lastCommittedHeight: 100, + commitInterval: 10, + height: 105, + root: common.Hash{3}, + wantLastCommittedHeight: 100, + wantLastCommittedRoot: common.Hash{2}, + wantLastAcceptedRoot: common.Hash{3}, + wantTipBufferRoot: common.Hash{3}, + wantMetadataDBKVs: map[string]string{ + "0000000000000064": hex.EncodeToString(common.Hash{2}.Bytes()), // height 100 + hex.EncodeToString(lastCommittedKey): "0000000000000064", // height 100 + }, + }, + "commit_all_up_to_height_without_height": { + lastAcceptedRoot: types.EmptyRootHash, + lastCommittedRoot: common.Hash{2}, + lastCommittedHeight: 60, + commitInterval: 10, + height: 105, + root: common.Hash{3}, + wantHasCommitted: true, + wantLastCommittedHeight: 100, + wantLastCommittedRoot: types.EmptyRootHash, + wantLastAcceptedRoot: common.Hash{3}, + wantTipBufferRoot: common.Hash{3}, + wantMetadataDBKVs: map[string]string{ + "000000000000003c": hex.EncodeToString(common.Hash{2}.Bytes()), // height 60 + "0000000000000046": hex.EncodeToString(types.EmptyRootHash[:]), // height 70 + "0000000000000050": hex.EncodeToString(types.EmptyRootHash[:]), // height 80 + "000000000000005a": hex.EncodeToString(types.EmptyRootHash[:]), // height 90 + "0000000000000064": hex.EncodeToString(types.EmptyRootHash[:]), // height 100 + hex.EncodeToString(lastCommittedKey): "0000000000000064", // height 100 + }, + }, + "commit_root": { + lastAcceptedRoot: types.EmptyRootHash, + lastCommittedRoot: common.Hash{2}, + lastCommittedHeight: 100, + commitInterval: 10, + height: 110, + root: common.Hash{3}, + wantHasCommitted: true, + wantLastCommittedHeight: 110, + wantLastCommittedRoot: common.Hash{3}, + wantLastAcceptedRoot: common.Hash{3}, + wantTipBufferRoot: common.Hash{3}, + wantMetadataDBKVs: map[string]string{ + "0000000000000064": hex.EncodeToString(common.Hash{2}.Bytes()), // height 100 + "000000000000006e": hex.EncodeToString(common.Hash{3}.Bytes()), // height 110 + hex.EncodeToString(lastCommittedKey): "000000000000006e", // height 110 + }, + }, + "commit_root_with_previous_root": { + lastAcceptedRoot: common.Hash{1}, + lastCommittedRoot: common.Hash{2}, + lastCommittedHeight: 100, + commitInterval: 10, + height: 110, + root: common.Hash{3}, + wantHasCommitted: true, + wantLastCommittedHeight: 110, + wantLastCommittedRoot: common.Hash{3}, + wantLastAcceptedRoot: common.Hash{3}, + wantTipBufferRoot: common.Hash{3}, + wantMetadataDBKVs: map[string]string{ + "0000000000000064": hex.EncodeToString(common.Hash{2}.Bytes()), // height 100 + "000000000000006e": hex.EncodeToString(common.Hash{3}.Bytes()), // height 110 + hex.EncodeToString(lastCommittedKey): "000000000000006e", // height 110 + }, + }, + } + + for name, testCase := range testCases { + testCase := testCase // capture range variable for running tests with Go < 1.22 + t.Run(name, func(t *testing.T) { + t.Parallel() + + versionDB := versiondb.New(memdb.New()) + atomicTrieDB := prefixdb.New(atomicTrieDBPrefix, versionDB) + metadataDB := prefixdb.New(atomicTrieMetaDBPrefix, versionDB) + const lastAcceptedHeight = 0 // no effect + atomicTrie, err := newAtomicTrie(atomicTrieDB, metadataDB, atomic.TestTxCodec, + lastAcceptedHeight, testCase.commitInterval) + require.NoError(t, err) + atomicTrie.lastAcceptedRoot = testCase.lastAcceptedRoot + if testCase.lastAcceptedRoot != types.EmptyRootHash { + // Generate trie node test blob + encoder := rlp.NewEncoderBuffer(nil) + offset := encoder.List() + encoder.WriteBytes([]byte{1}) // key + encoder.WriteBytes(make([]byte, 32)) // value + encoder.ListEnd(offset) + testBlob := encoder.ToBytes() + err := encoder.Flush() + require.NoError(t, err) + + nodeSet := trienode.NewNodeSet(testCase.lastAcceptedRoot) + nodeSet.AddNode([]byte("any"), trienode.New(testCase.lastAcceptedRoot, testBlob)) // dirty node + err = atomicTrie.InsertTrie(nodeSet, testCase.lastAcceptedRoot) + require.NoError(t, err) + + _, storageSize, _ := atomicTrie.trieDB.Size() + require.NotZero(t, storageSize, "there should be a dirty node taking up storage space") + } + atomicTrie.updateLastCommitted(testCase.lastCommittedRoot, testCase.lastCommittedHeight) + + hasCommitted, err := atomicTrie.AcceptTrie(testCase.height, testCase.root) + require.NoError(t, err) + + assert.Equal(t, testCase.wantHasCommitted, hasCommitted) + assert.Equal(t, testCase.wantLastCommittedHeight, atomicTrie.lastCommittedHeight) + assert.Equal(t, testCase.wantLastCommittedRoot, atomicTrie.lastCommittedRoot) + assert.Equal(t, testCase.wantLastAcceptedRoot, atomicTrie.lastAcceptedRoot) + + // Check dereferencing previous dirty root inserted occurred + _, storageSize, _ := atomicTrie.trieDB.Size() + assert.Zerof(t, storageSize, "storage size should be zero after accepting the trie due to the dirty nodes derefencing but is %s", storageSize) + + for wantKeyHex, wantValueHex := range testCase.wantMetadataDBKVs { + wantKey, err := hex.DecodeString(wantKeyHex) + require.NoError(t, err) + value, err := metadataDB.Get(wantKey) + assert.NoErrorf(t, err, "getting key %s from metadata database", wantKeyHex) + assert.Equalf(t, wantValueHex, hex.EncodeToString(value), "value for key %s", wantKeyHex) + } + }) + } +} + func BenchmarkAtomicTrieInit(b *testing.B) { db := versiondb.New(memdb.New()) codec := atomic.TestTxCodec From 66c1a92104ec1b59ba2d0820a2d1bb5ea292afa2 Mon Sep 17 00:00:00 2001 From: Quentin McGaw Date: Mon, 10 Feb 2025 08:56:01 +0100 Subject: [PATCH 37/69] chore(metrics): use geth metrics package and delete local metrics (#745) - file kept and refactored `metrics/prometheus/prometheus.go` with the `Gatherer` implementation we use - file kept and refactored `metrics/prometheus/prometheus_test.go` - new file `metrics/prometheus/interfaces.go` added for refactoring - geth global variable `metrics.Enabled` is set to true in `plugin/evm.VM.initializeMetrics` --- core/blockchain.go | 2 +- core/main_test.go | 2 +- core/rawdb/schema.go | 2 +- core/state/metrics.go | 2 +- core/state/snapshot/snapshot.go | 2 +- core/state/state_object.go | 2 +- core/state/statedb.go | 2 +- core/state/trie_prefetcher.go | 2 +- core/state/trie_prefetcher_extra_test.go | 2 +- core/txpool/blobpool/blobpool.go | 2 +- core/txpool/blobpool/metrics.go | 2 +- core/txpool/legacypool/legacypool.go | 2 +- core/txpool/txpool.go | 2 +- go.mod | 4 +- metrics/FORK.md | 1 - metrics/LICENSE | 29 -- metrics/README.md | 102 ----- metrics/config.go | 43 -- metrics/counter.go | 112 ----- metrics/counter_float64.go | 126 ------ metrics/counter_float_64_test.go | 99 ----- metrics/counter_test.go | 77 ---- metrics/cpu.go | 35 -- metrics/cpu_disabled.go | 34 -- metrics/cpu_enabled.go | 54 --- metrics/cputime_nop.go | 36 -- metrics/cputime_unix.go | 46 -- metrics/debug.go | 76 ---- metrics/debug_test.go | 48 --- metrics/disk.go | 35 -- metrics/disk_linux.go | 82 ---- metrics/disk_nop.go | 37 -- metrics/ewma.go | 111 ----- metrics/ewma_test.go | 89 ---- metrics/gauge.go | 98 ----- metrics/gauge_float64.go | 73 ---- metrics/gauge_float64_test.go | 51 --- metrics/gauge_info.go | 84 ---- metrics/gauge_info_test.go | 36 -- metrics/gauge_test.go | 31 -- metrics/graphite.go | 117 ----- metrics/graphite_test.go | 22 - metrics/healthcheck.go | 61 --- metrics/histogram.go | 73 ---- metrics/histogram_test.go | 95 ----- metrics/inactive.go | 48 --- metrics/init_test.go | 5 - metrics/json.go | 31 -- metrics/json_test.go | 28 -- metrics/log.go | 86 ---- metrics/memory.md | 285 ------------- metrics/meter.go | 189 --------- metrics/meter_test.go | 89 ---- metrics/metrics.go | 18 - metrics/metrics_test.go | 99 ----- metrics/opentsdb.go | 128 ------ metrics/opentsdb_test.go | 67 --- metrics/prometheus/interfaces.go | 12 + metrics/prometheus/prometheus.go | 325 +++++++------- metrics/prometheus/prometheus_test.go | 100 +++-- metrics/prometheus/testdata/prometheus.want | 70 --- metrics/registry.go | 372 ---------------- metrics/registry_test.go | 335 --------------- metrics/resetting_sample.go | 24 -- metrics/resetting_timer.go | 171 -------- metrics/resetting_timer_test.go | 197 --------- metrics/sample.go | 446 -------------------- metrics/sample_test.go | 360 ---------------- metrics/syslog.go | 83 ---- metrics/testdata/opentsb.want | 23 - metrics/timer.go | 182 -------- metrics/timer_test.go | 114 ----- metrics/validate.sh | 10 - metrics/writer.go | 100 ----- metrics/writer_test.go | 23 - peer/peer_tracker.go | 2 +- peer/stats/stats.go | 2 +- plugin/evm/atomic/mempool.go | 2 +- plugin/evm/network_handler.go | 2 +- plugin/evm/syncervm_test.go | 12 +- plugin/evm/testutils/metrics.go | 20 + plugin/evm/vm.go | 12 +- plugin/evm/vm_test.go | 16 +- rpc/handler.go | 2 +- rpc/metrics.go | 2 +- scripts/geth-allowed-packages.txt | 1 + scripts/lint_allowed_geth_imports.sh | 2 +- sync/client/stats/stats.go | 2 +- sync/handlers/stats/stats.go | 2 +- sync/statesync/trie_sync_stats.go | 2 +- sync/statesync/trie_sync_stats_test.go | 2 +- trie/stacktrie.go | 2 +- trie/utils/verkle.go | 2 +- triedb/hashdb/database.go | 2 +- triedb/pathdb/metrics.go | 2 +- utils/metered_cache.go | 2 +- warp/handlers/signature_request_test.go | 5 + warp/handlers/stats.go | 2 +- warp/verifier_backend_test.go | 5 + warp/verifier_stats.go | 2 +- 100 files changed, 314 insertions(+), 5856 deletions(-) delete mode 100644 metrics/FORK.md delete mode 100644 metrics/LICENSE delete mode 100644 metrics/README.md delete mode 100644 metrics/config.go delete mode 100644 metrics/counter.go delete mode 100644 metrics/counter_float64.go delete mode 100644 metrics/counter_float_64_test.go delete mode 100644 metrics/counter_test.go delete mode 100644 metrics/cpu.go delete mode 100644 metrics/cpu_disabled.go delete mode 100644 metrics/cpu_enabled.go delete mode 100644 metrics/cputime_nop.go delete mode 100644 metrics/cputime_unix.go delete mode 100644 metrics/debug.go delete mode 100644 metrics/debug_test.go delete mode 100644 metrics/disk.go delete mode 100644 metrics/disk_linux.go delete mode 100644 metrics/disk_nop.go delete mode 100644 metrics/ewma.go delete mode 100644 metrics/ewma_test.go delete mode 100644 metrics/gauge.go delete mode 100644 metrics/gauge_float64.go delete mode 100644 metrics/gauge_float64_test.go delete mode 100644 metrics/gauge_info.go delete mode 100644 metrics/gauge_info_test.go delete mode 100644 metrics/gauge_test.go delete mode 100644 metrics/graphite.go delete mode 100644 metrics/graphite_test.go delete mode 100644 metrics/healthcheck.go delete mode 100644 metrics/histogram.go delete mode 100644 metrics/histogram_test.go delete mode 100644 metrics/inactive.go delete mode 100644 metrics/init_test.go delete mode 100644 metrics/json.go delete mode 100644 metrics/json_test.go delete mode 100644 metrics/log.go delete mode 100644 metrics/memory.md delete mode 100644 metrics/meter.go delete mode 100644 metrics/meter_test.go delete mode 100644 metrics/metrics.go delete mode 100644 metrics/metrics_test.go delete mode 100644 metrics/opentsdb.go delete mode 100644 metrics/opentsdb_test.go create mode 100644 metrics/prometheus/interfaces.go delete mode 100644 metrics/prometheus/testdata/prometheus.want delete mode 100644 metrics/registry.go delete mode 100644 metrics/registry_test.go delete mode 100644 metrics/resetting_sample.go delete mode 100644 metrics/resetting_timer.go delete mode 100644 metrics/resetting_timer_test.go delete mode 100644 metrics/sample.go delete mode 100644 metrics/sample_test.go delete mode 100644 metrics/syslog.go delete mode 100644 metrics/testdata/opentsb.want delete mode 100644 metrics/timer.go delete mode 100644 metrics/timer_test.go delete mode 100755 metrics/validate.sh delete mode 100644 metrics/writer.go delete mode 100644 metrics/writer_test.go create mode 100644 plugin/evm/testutils/metrics.go diff --git a/core/blockchain.go b/core/blockchain.go index 0199ceaf8a..77b15fad49 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -47,7 +47,6 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/core/vm" "github.com/ava-labs/coreth/internal/version" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/trie" "github.com/ava-labs/coreth/triedb" @@ -58,6 +57,7 @@ import ( "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" ) var ( diff --git a/core/main_test.go b/core/main_test.go index 1d0e299f4a..db4ccc8652 100644 --- a/core/main_test.go +++ b/core/main_test.go @@ -15,7 +15,7 @@ func TestMain(m *testing.M) { opts := []goleak.Option{ // No good way to shut down these goroutines: goleak.IgnoreTopFunction("github.com/ava-labs/coreth/core/state/snapshot.(*diskLayer).generate"), - goleak.IgnoreTopFunction("github.com/ava-labs/coreth/metrics.(*meterArbiter).tick"), + goleak.IgnoreTopFunction("github.com/ethereum/go-ethereum/metrics.(*meterArbiter).tick"), goleak.IgnoreTopFunction("github.com/syndtr/goleveldb/leveldb.(*DB).mpoolDrain"), } goleak.VerifyTestMain(m, opts...) diff --git a/core/rawdb/schema.go b/core/rawdb/schema.go index 71dff23127..53fe9ac15f 100644 --- a/core/rawdb/schema.go +++ b/core/rawdb/schema.go @@ -32,9 +32,9 @@ import ( "encoding/binary" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ava-labs/coreth/metrics" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/metrics" ) // The fields below define the low level database schema prefixing. diff --git a/core/state/metrics.go b/core/state/metrics.go index 5e2f060c3a..096bfe504f 100644 --- a/core/state/metrics.go +++ b/core/state/metrics.go @@ -26,7 +26,7 @@ package state -import "github.com/ava-labs/coreth/metrics" +import "github.com/ethereum/go-ethereum/metrics" var ( accountUpdatedMeter = metrics.NewRegisteredMeter("state/update/account", nil) diff --git a/core/state/snapshot/snapshot.go b/core/state/snapshot/snapshot.go index bda0e97988..9c9b2f08ea 100644 --- a/core/state/snapshot/snapshot.go +++ b/core/state/snapshot/snapshot.go @@ -36,11 +36,11 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/triedb" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" ) const ( diff --git a/core/state/state_object.go b/core/state/state_object.go index 8f0493ed3d..36aff41ba6 100644 --- a/core/state/state_object.go +++ b/core/state/state_object.go @@ -34,10 +34,10 @@ import ( "time" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/trie/trienode" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/rlp" "github.com/holiman/uint256" ) diff --git a/core/state/statedb.go b/core/state/statedb.go index e84e2d13d0..26e4f28ccd 100644 --- a/core/state/statedb.go +++ b/core/state/statedb.go @@ -37,7 +37,6 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/predicate" "github.com/ava-labs/coreth/trie" @@ -47,6 +46,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" "github.com/holiman/uint256" ) diff --git a/core/state/trie_prefetcher.go b/core/state/trie_prefetcher.go index fc7be65b4a..f700010d46 100644 --- a/core/state/trie_prefetcher.go +++ b/core/state/trie_prefetcher.go @@ -20,9 +20,9 @@ import ( "sync" "github.com/ava-labs/coreth/libevm/options" - "github.com/ava-labs/coreth/metrics" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" ) var ( diff --git a/core/state/trie_prefetcher_extra_test.go b/core/state/trie_prefetcher_extra_test.go index d768d46a9d..0087678a79 100644 --- a/core/state/trie_prefetcher_extra_test.go +++ b/core/state/trie_prefetcher_extra_test.go @@ -16,11 +16,11 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/triedb" "github.com/ava-labs/coreth/triedb/hashdb" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/metrics" "github.com/stretchr/testify/require" ) diff --git a/core/txpool/blobpool/blobpool.go b/core/txpool/blobpool/blobpool.go index 63d79e4372..27f81faed5 100644 --- a/core/txpool/blobpool/blobpool.go +++ b/core/txpool/blobpool/blobpool.go @@ -45,11 +45,11 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/params" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/rlp" "github.com/holiman/billy" "github.com/holiman/uint256" diff --git a/core/txpool/blobpool/metrics.go b/core/txpool/blobpool/metrics.go index d2d2b7e23c..0192e897aa 100644 --- a/core/txpool/blobpool/metrics.go +++ b/core/txpool/blobpool/metrics.go @@ -26,7 +26,7 @@ package blobpool -import "github.com/ava-labs/coreth/metrics" +import "github.com/ethereum/go-ethereum/metrics" var ( // datacapGauge tracks the user's configured capacity for the blob pool. It diff --git a/core/txpool/legacypool/legacypool.go b/core/txpool/legacypool/legacypool.go index 51825da9e9..8f4a31427e 100644 --- a/core/txpool/legacypool/legacypool.go +++ b/core/txpool/legacypool/legacypool.go @@ -41,13 +41,13 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/utils" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/prque" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" "github.com/holiman/uint256" ) diff --git a/core/txpool/txpool.go b/core/txpool/txpool.go index adfc616a82..71b6ad3c96 100644 --- a/core/txpool/txpool.go +++ b/core/txpool/txpool.go @@ -35,10 +35,10 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/metrics" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" ) var ( diff --git a/go.mod b/go.mod index 92e69d503f..05ca39ac03 100644 --- a/go.mod +++ b/go.mod @@ -28,7 +28,6 @@ require ( github.com/olekukonko/tablewriter v0.0.5 github.com/prometheus/client_golang v1.16.0 github.com/prometheus/client_model v0.3.0 - github.com/shirou/gopsutil v3.21.11+incompatible github.com/spf13/cast v1.5.0 github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.12.0 @@ -41,7 +40,6 @@ require ( golang.org/x/crypto v0.31.0 golang.org/x/exp v0.0.0-20231127185646-65229373498e golang.org/x/sync v0.10.0 - golang.org/x/sys v0.28.0 golang.org/x/text v0.21.0 golang.org/x/time v0.3.0 golang.org/x/tools v0.22.0 @@ -101,6 +99,7 @@ require ( github.com/rivo/uniseg v0.2.0 // indirect github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect + github.com/shirou/gopsutil v3.21.11+incompatible // indirect github.com/spf13/afero v1.8.2 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/subosito/gotenv v1.3.0 // indirect @@ -122,6 +121,7 @@ require ( go.uber.org/zap v1.26.0 // indirect golang.org/x/mod v0.18.0 // indirect golang.org/x/net v0.33.0 // indirect + golang.org/x/sys v0.28.0 // indirect golang.org/x/term v0.27.0 // indirect gonum.org/v1/gonum v0.11.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20240604185151-ef581f913117 // indirect diff --git a/metrics/FORK.md b/metrics/FORK.md deleted file mode 100644 index b19985bf56..0000000000 --- a/metrics/FORK.md +++ /dev/null @@ -1 +0,0 @@ -This repo has been forked from https://github.com/rcrowley/go-metrics at commit e181e09 diff --git a/metrics/LICENSE b/metrics/LICENSE deleted file mode 100644 index 363fa9ee77..0000000000 --- a/metrics/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -Copyright 2012 Richard Crowley. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - -THIS SOFTWARE IS PROVIDED BY RICHARD CROWLEY ``AS IS'' AND ANY EXPRESS -OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL RICHARD CROWLEY OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - -The views and conclusions contained in the software and documentation -are those of the authors and should not be interpreted as representing -official policies, either expressed or implied, of Richard Crowley. diff --git a/metrics/README.md b/metrics/README.md deleted file mode 100644 index cf153c8093..0000000000 --- a/metrics/README.md +++ /dev/null @@ -1,102 +0,0 @@ -go-metrics -========== - -![travis build status](https://travis-ci.org/rcrowley/go-metrics.svg?branch=master) - -Go port of Coda Hale's Metrics library: . - -Documentation: . - -Usage ------ - -Create and update metrics: - -```go -c := metrics.NewCounter() -metrics.Register("foo", c) -c.Inc(47) - -g := metrics.NewGauge() -metrics.Register("bar", g) -g.Update(47) - -r := NewRegistry() -g := metrics.NewRegisteredFunctionalGauge("cache-evictions", r, func() int64 { return cache.getEvictionsCount() }) - -s := metrics.NewExpDecaySample(1028, 0.015) // or metrics.NewUniformSample(1028) -h := metrics.NewHistogram(s) -metrics.Register("baz", h) -h.Update(47) - -m := metrics.NewMeter() -metrics.Register("quux", m) -m.Mark(47) - -t := metrics.NewTimer() -metrics.Register("bang", t) -t.Time(func() {}) -t.Update(47) -``` - -Register() is not threadsafe. For threadsafe metric registration use -GetOrRegister: - -```go -t := metrics.GetOrRegisterTimer("account.create.latency", nil) -t.Time(func() {}) -t.Update(47) -``` - -**NOTE:** Be sure to unregister short-lived meters and timers otherwise they will -leak memory: - -```go -// Will call Stop() on the Meter to allow for garbage collection -metrics.Unregister("quux") -// Or similarly for a Timer that embeds a Meter -metrics.Unregister("bang") -``` - -Periodically log every metric in human-readable form to standard error: - -```go -go metrics.Log(metrics.DefaultRegistry, 5 * time.Second, log.New(os.Stderr, "metrics: ", log.Lmicroseconds)) -``` - -Periodically log every metric in slightly-more-parseable form to syslog: - -```go -w, _ := syslog.Dial("unixgram", "/dev/log", syslog.LOG_INFO, "metrics") -go metrics.Syslog(metrics.DefaultRegistry, 60e9, w) -``` - -Periodically emit every metric to Graphite using the [Graphite client](https://github.com/cyberdelia/go-metrics-graphite): - -```go - -import "github.com/cyberdelia/go-metrics-graphite" - -addr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:2003") -go graphite.Graphite(metrics.DefaultRegistry, 10e9, "metrics", addr) -``` - -Installation ------------- - -```sh -go get github.com/rcrowley/go-metrics -``` - -StatHat support additionally requires their Go client: - -```sh -go get github.com/stathat/go -``` - -Publishing Metrics ------------------- - -Clients are available for the following destinations: - -* Prometheus - https://github.com/deathowl/go-metrics-prometheus diff --git a/metrics/config.go b/metrics/config.go deleted file mode 100644 index a60d96e962..0000000000 --- a/metrics/config.go +++ /dev/null @@ -1,43 +0,0 @@ -// (c) 2022, Ava Labs, Inc. -// -// This file is a derived work, based on the go-ethereum library whose original -// notices appear below. -// -// It is distributed under a license compatible with the licensing terms of the -// original code from which it is derived. -// -// Much love to the original authors for their work. -// ********** -// Copyright 2021 The go-ethereum Authors -// This file is part of go-ethereum. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package metrics - -// Config contains the configuration for the metric collection. -type Config struct { - Enabled bool `toml:",omitempty"` - EnabledExpensive bool `toml:",omitempty"` - HTTP string `toml:",omitempty"` - Port int `toml:",omitempty"` -} - -// DefaultConfig is the default config for metrics used in go-ethereum. -var DefaultConfig = Config{ - Enabled: false, - EnabledExpensive: false, - HTTP: "127.0.0.1", - Port: 6060, -} diff --git a/metrics/counter.go b/metrics/counter.go deleted file mode 100644 index dbe8e16a90..0000000000 --- a/metrics/counter.go +++ /dev/null @@ -1,112 +0,0 @@ -package metrics - -import ( - "sync/atomic" -) - -type CounterSnapshot interface { - Count() int64 -} - -// Counter hold an int64 value that can be incremented and decremented. -type Counter interface { - Clear() - Dec(int64) - Inc(int64) - Snapshot() CounterSnapshot -} - -// GetOrRegisterCounter returns an existing Counter or constructs and registers -// a new StandardCounter. -func GetOrRegisterCounter(name string, r Registry) Counter { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, NewCounter).(Counter) -} - -// GetOrRegisterCounterForced returns an existing Counter or constructs and registers a -// new Counter no matter the global switch is enabled or not. -// Be sure to unregister the counter from the registry once it is of no use to -// allow for garbage collection. -func GetOrRegisterCounterForced(name string, r Registry) Counter { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, NewCounterForced).(Counter) -} - -// NewCounter constructs a new StandardCounter. -func NewCounter() Counter { - if !Enabled { - return NilCounter{} - } - return new(StandardCounter) -} - -// NewCounterForced constructs a new StandardCounter and returns it no matter if -// the global switch is enabled or not. -func NewCounterForced() Counter { - return new(StandardCounter) -} - -// NewRegisteredCounter constructs and registers a new StandardCounter. -func NewRegisteredCounter(name string, r Registry) Counter { - c := NewCounter() - if nil == r { - r = DefaultRegistry - } - r.Register(name, c) - return c -} - -// NewRegisteredCounterForced constructs and registers a new StandardCounter -// and launches a goroutine no matter the global switch is enabled or not. -// Be sure to unregister the counter from the registry once it is of no use to -// allow for garbage collection. -func NewRegisteredCounterForced(name string, r Registry) Counter { - c := NewCounterForced() - if nil == r { - r = DefaultRegistry - } - r.Register(name, c) - return c -} - -// counterSnapshot is a read-only copy of another Counter. -type counterSnapshot int64 - -// Count returns the count at the time the snapshot was taken. -func (c counterSnapshot) Count() int64 { return int64(c) } - -// NilCounter is a no-op Counter. -type NilCounter struct{} - -func (NilCounter) Clear() {} -func (NilCounter) Dec(i int64) {} -func (NilCounter) Inc(i int64) {} -func (NilCounter) Snapshot() CounterSnapshot { return (*emptySnapshot)(nil) } - -// StandardCounter is the standard implementation of a Counter and uses the -// sync/atomic package to manage a single int64 value. -type StandardCounter atomic.Int64 - -// Clear sets the counter to zero. -func (c *StandardCounter) Clear() { - (*atomic.Int64)(c).Store(0) -} - -// Dec decrements the counter by the given amount. -func (c *StandardCounter) Dec(i int64) { - (*atomic.Int64)(c).Add(-i) -} - -// Inc increments the counter by the given amount. -func (c *StandardCounter) Inc(i int64) { - (*atomic.Int64)(c).Add(i) -} - -// Snapshot returns a read-only copy of the counter. -func (c *StandardCounter) Snapshot() CounterSnapshot { - return counterSnapshot((*atomic.Int64)(c).Load()) -} diff --git a/metrics/counter_float64.go b/metrics/counter_float64.go deleted file mode 100644 index 15c81494ef..0000000000 --- a/metrics/counter_float64.go +++ /dev/null @@ -1,126 +0,0 @@ -package metrics - -import ( - "math" - "sync/atomic" -) - -type CounterFloat64Snapshot interface { - Count() float64 -} - -// CounterFloat64 holds a float64 value that can be incremented and decremented. -type CounterFloat64 interface { - Clear() - Dec(float64) - Inc(float64) - Snapshot() CounterFloat64Snapshot -} - -// GetOrRegisterCounterFloat64 returns an existing CounterFloat64 or constructs and registers -// a new StandardCounterFloat64. -func GetOrRegisterCounterFloat64(name string, r Registry) CounterFloat64 { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, NewCounterFloat64).(CounterFloat64) -} - -// GetOrRegisterCounterFloat64Forced returns an existing CounterFloat64 or constructs and registers a -// new CounterFloat64 no matter the global switch is enabled or not. -// Be sure to unregister the counter from the registry once it is of no use to -// allow for garbage collection. -func GetOrRegisterCounterFloat64Forced(name string, r Registry) CounterFloat64 { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, NewCounterFloat64Forced).(CounterFloat64) -} - -// NewCounterFloat64 constructs a new StandardCounterFloat64. -func NewCounterFloat64() CounterFloat64 { - if !Enabled { - return NilCounterFloat64{} - } - return &StandardCounterFloat64{} -} - -// NewCounterFloat64Forced constructs a new StandardCounterFloat64 and returns it no matter if -// the global switch is enabled or not. -func NewCounterFloat64Forced() CounterFloat64 { - return &StandardCounterFloat64{} -} - -// NewRegisteredCounterFloat64 constructs and registers a new StandardCounterFloat64. -func NewRegisteredCounterFloat64(name string, r Registry) CounterFloat64 { - c := NewCounterFloat64() - if nil == r { - r = DefaultRegistry - } - r.Register(name, c) - return c -} - -// NewRegisteredCounterFloat64Forced constructs and registers a new StandardCounterFloat64 -// and launches a goroutine no matter the global switch is enabled or not. -// Be sure to unregister the counter from the registry once it is of no use to -// allow for garbage collection. -func NewRegisteredCounterFloat64Forced(name string, r Registry) CounterFloat64 { - c := NewCounterFloat64Forced() - if nil == r { - r = DefaultRegistry - } - r.Register(name, c) - return c -} - -// counterFloat64Snapshot is a read-only copy of another CounterFloat64. -type counterFloat64Snapshot float64 - -// Count returns the value at the time the snapshot was taken. -func (c counterFloat64Snapshot) Count() float64 { return float64(c) } - -type NilCounterFloat64 struct{} - -func (NilCounterFloat64) Clear() {} -func (NilCounterFloat64) Count() float64 { return 0.0 } -func (NilCounterFloat64) Dec(i float64) {} -func (NilCounterFloat64) Inc(i float64) {} -func (NilCounterFloat64) Snapshot() CounterFloat64Snapshot { return NilCounterFloat64{} } - -// StandardCounterFloat64 is the standard implementation of a CounterFloat64 and uses the -// atomic to manage a single float64 value. -type StandardCounterFloat64 struct { - floatBits atomic.Uint64 -} - -// Clear sets the counter to zero. -func (c *StandardCounterFloat64) Clear() { - c.floatBits.Store(0) -} - -// Dec decrements the counter by the given amount. -func (c *StandardCounterFloat64) Dec(v float64) { - atomicAddFloat(&c.floatBits, -v) -} - -// Inc increments the counter by the given amount. -func (c *StandardCounterFloat64) Inc(v float64) { - atomicAddFloat(&c.floatBits, v) -} - -// Snapshot returns a read-only copy of the counter. -func (c *StandardCounterFloat64) Snapshot() CounterFloat64Snapshot { - v := math.Float64frombits(c.floatBits.Load()) - return counterFloat64Snapshot(v) -} - -func atomicAddFloat(fbits *atomic.Uint64, v float64) { - for { - loadedBits := fbits.Load() - newBits := math.Float64bits(math.Float64frombits(loadedBits) + v) - if fbits.CompareAndSwap(loadedBits, newBits) { - break - } - } -} diff --git a/metrics/counter_float_64_test.go b/metrics/counter_float_64_test.go deleted file mode 100644 index c21bd3307f..0000000000 --- a/metrics/counter_float_64_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package metrics - -import ( - "sync" - "testing" -) - -func BenchmarkCounterFloat64(b *testing.B) { - c := NewCounterFloat64() - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Inc(1.0) - } -} - -func BenchmarkCounterFloat64Parallel(b *testing.B) { - c := NewCounterFloat64() - b.ResetTimer() - var wg sync.WaitGroup - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - for i := 0; i < b.N; i++ { - c.Inc(1.0) - } - wg.Done() - }() - } - wg.Wait() - if have, want := c.Snapshot().Count(), 10.0*float64(b.N); have != want { - b.Fatalf("have %f want %f", have, want) - } -} - -func TestCounterFloat64Clear(t *testing.T) { - c := NewCounterFloat64() - c.Inc(1.0) - c.Clear() - if count := c.Snapshot().Count(); count != 0 { - t.Errorf("c.Count(): 0 != %v\n", count) - } -} - -func TestCounterFloat64Dec1(t *testing.T) { - c := NewCounterFloat64() - c.Dec(1.0) - if count := c.Snapshot().Count(); count != -1.0 { - t.Errorf("c.Count(): -1.0 != %v\n", count) - } -} - -func TestCounterFloat64Dec2(t *testing.T) { - c := NewCounterFloat64() - c.Dec(2.0) - if count := c.Snapshot().Count(); count != -2.0 { - t.Errorf("c.Count(): -2.0 != %v\n", count) - } -} - -func TestCounterFloat64Inc1(t *testing.T) { - c := NewCounterFloat64() - c.Inc(1.0) - if count := c.Snapshot().Count(); count != 1.0 { - t.Errorf("c.Count(): 1.0 != %v\n", count) - } -} - -func TestCounterFloat64Inc2(t *testing.T) { - c := NewCounterFloat64() - c.Inc(2.0) - if count := c.Snapshot().Count(); count != 2.0 { - t.Errorf("c.Count(): 2.0 != %v\n", count) - } -} - -func TestCounterFloat64Snapshot(t *testing.T) { - c := NewCounterFloat64() - c.Inc(1.0) - snapshot := c.Snapshot() - c.Inc(1.0) - if count := snapshot.Count(); count != 1.0 { - t.Errorf("c.Count(): 1.0 != %v\n", count) - } -} - -func TestCounterFloat64Zero(t *testing.T) { - c := NewCounterFloat64() - if count := c.Snapshot().Count(); count != 0 { - t.Errorf("c.Count(): 0 != %v\n", count) - } -} - -func TestGetOrRegisterCounterFloat64(t *testing.T) { - r := NewRegistry() - NewRegisteredCounterFloat64("foo", r).Inc(47.0) - if c := GetOrRegisterCounterFloat64("foo", r).Snapshot(); c.Count() != 47.0 { - t.Fatal(c) - } -} diff --git a/metrics/counter_test.go b/metrics/counter_test.go deleted file mode 100644 index 1b15b23f21..0000000000 --- a/metrics/counter_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package metrics - -import "testing" - -func BenchmarkCounter(b *testing.B) { - c := NewCounter() - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Inc(1) - } -} - -func TestCounterClear(t *testing.T) { - c := NewCounter() - c.Inc(1) - c.Clear() - if count := c.Snapshot().Count(); count != 0 { - t.Errorf("c.Count(): 0 != %v\n", count) - } -} - -func TestCounterDec1(t *testing.T) { - c := NewCounter() - c.Dec(1) - if count := c.Snapshot().Count(); count != -1 { - t.Errorf("c.Count(): -1 != %v\n", count) - } -} - -func TestCounterDec2(t *testing.T) { - c := NewCounter() - c.Dec(2) - if count := c.Snapshot().Count(); count != -2 { - t.Errorf("c.Count(): -2 != %v\n", count) - } -} - -func TestCounterInc1(t *testing.T) { - c := NewCounter() - c.Inc(1) - if count := c.Snapshot().Count(); count != 1 { - t.Errorf("c.Count(): 1 != %v\n", count) - } -} - -func TestCounterInc2(t *testing.T) { - c := NewCounter() - c.Inc(2) - if count := c.Snapshot().Count(); count != 2 { - t.Errorf("c.Count(): 2 != %v\n", count) - } -} - -func TestCounterSnapshot(t *testing.T) { - c := NewCounter() - c.Inc(1) - snapshot := c.Snapshot() - c.Inc(1) - if count := snapshot.Count(); count != 1 { - t.Errorf("c.Count(): 1 != %v\n", count) - } -} - -func TestCounterZero(t *testing.T) { - c := NewCounter() - if count := c.Snapshot().Count(); count != 0 { - t.Errorf("c.Count(): 0 != %v\n", count) - } -} - -func TestGetOrRegisterCounter(t *testing.T) { - r := NewRegistry() - NewRegisteredCounter("foo", r).Inc(47) - if c := GetOrRegisterCounter("foo", r).Snapshot(); c.Count() != 47 { - t.Fatal(c) - } -} diff --git a/metrics/cpu.go b/metrics/cpu.go deleted file mode 100644 index 472a1a42d8..0000000000 --- a/metrics/cpu.go +++ /dev/null @@ -1,35 +0,0 @@ -// (c) 2022, Ava Labs, Inc. -// -// This file is a derived work, based on the go-ethereum library whose original -// notices appear below. -// -// It is distributed under a license compatible with the licensing terms of the -// original code from which it is derived. -// -// Much love to the original authors for their work. -// ********** -// Copyright 2018 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package metrics - -// CPUStats is the system and process CPU stats. -// All values are in seconds. -type CPUStats struct { - GlobalTime float64 // Time spent by the CPU working on all processes - GlobalWait float64 // Time spent by waiting on disk for all processes - LocalTime float64 // Time spent by the CPU working on this process -} diff --git a/metrics/cpu_disabled.go b/metrics/cpu_disabled.go deleted file mode 100644 index f2c3ead5db..0000000000 --- a/metrics/cpu_disabled.go +++ /dev/null @@ -1,34 +0,0 @@ -// (c) 2022, Ava Labs, Inc. -// -// This file is a derived work, based on the go-ethereum library whose original -// notices appear below. -// -// It is distributed under a license compatible with the licensing terms of the -// original code from which it is derived. -// -// Much love to the original authors for their work. -// ********** -// Copyright 2020 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -//go:build ios || js -// +build ios js - -package metrics - -// ReadCPUStats retrieves the current CPU stats. Internally this uses `gosigar`, -// which is not supported on the platforms in this file. -func ReadCPUStats(stats *CPUStats) {} diff --git a/metrics/cpu_enabled.go b/metrics/cpu_enabled.go deleted file mode 100644 index 7b5fe4d207..0000000000 --- a/metrics/cpu_enabled.go +++ /dev/null @@ -1,54 +0,0 @@ -// (c) 2022, Ava Labs, Inc. -// -// This file is a derived work, based on the go-ethereum library whose original -// notices appear below. -// -// It is distributed under a license compatible with the licensing terms of the -// original code from which it is derived. -// -// Much love to the original authors for their work. -// ********** -// Copyright 2020 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -//go:build !ios && !js -// +build !ios,!js - -package metrics - -import ( - "github.com/ethereum/go-ethereum/log" - "github.com/shirou/gopsutil/cpu" -) - -// ReadCPUStats retrieves the current CPU stats. -func ReadCPUStats(stats *CPUStats) { - // passing false to request all cpu times - timeStats, err := cpu.Times(false) - if err != nil { - log.Error("Could not read cpu stats", "err", err) - return - } - if len(timeStats) == 0 { - log.Error("Empty cpu stats") - return - } - // requesting all cpu times will always return an array with only one time stats entry - timeStat := timeStats[0] - stats.GlobalTime = timeStat.User + timeStat.Nice + timeStat.System - stats.GlobalWait = timeStat.Iowait - stats.LocalTime = getProcessCPUTime() -} diff --git a/metrics/cputime_nop.go b/metrics/cputime_nop.go deleted file mode 100644 index 275b983717..0000000000 --- a/metrics/cputime_nop.go +++ /dev/null @@ -1,36 +0,0 @@ -// (c) 2022, Ava Labs, Inc. -// -// This file is a derived work, based on the go-ethereum library whose original -// notices appear below. -// -// It is distributed under a license compatible with the licensing terms of the -// original code from which it is derived. -// -// Much love to the original authors for their work. -// ********** -// Copyright 2018 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -//go:build windows || js -// +build windows js - -package metrics - -// getProcessCPUTime returns 0 on Windows as there is no system call to resolve -// the actual process' CPU time. -func getProcessCPUTime() float64 { - return 0 -} diff --git a/metrics/cputime_unix.go b/metrics/cputime_unix.go deleted file mode 100644 index 5a479d8aa8..0000000000 --- a/metrics/cputime_unix.go +++ /dev/null @@ -1,46 +0,0 @@ -// (c) 2022, Ava Labs, Inc. -// -// This file is a derived work, based on the go-ethereum library whose original -// notices appear below. -// -// It is distributed under a license compatible with the licensing terms of the -// original code from which it is derived. -// -// Much love to the original authors for their work. -// ********** -// Copyright 2018 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -//go:build !windows && !js -// +build !windows,!js - -package metrics - -import ( - syscall "golang.org/x/sys/unix" - - "github.com/ethereum/go-ethereum/log" -) - -// getProcessCPUTime retrieves the process' CPU time since program startup. -func getProcessCPUTime() float64 { - var usage syscall.Rusage - if err := syscall.Getrusage(syscall.RUSAGE_SELF, &usage); err != nil { - log.Warn("Failed to retrieve CPU time", "err", err) - return 0 - } - return float64(usage.Utime.Sec+usage.Stime.Sec) + float64(usage.Utime.Usec+usage.Stime.Usec)/1000000 //nolint:unconvert -} diff --git a/metrics/debug.go b/metrics/debug.go deleted file mode 100644 index de4a2739fe..0000000000 --- a/metrics/debug.go +++ /dev/null @@ -1,76 +0,0 @@ -package metrics - -import ( - "runtime/debug" - "time" -) - -var ( - debugMetrics struct { - GCStats struct { - LastGC Gauge - NumGC Gauge - Pause Histogram - //PauseQuantiles Histogram - PauseTotal Gauge - } - ReadGCStats Timer - } - gcStats debug.GCStats -) - -// Capture new values for the Go garbage collector statistics exported in -// debug.GCStats. This is designed to be called as a goroutine. -func CaptureDebugGCStats(r Registry, d time.Duration) { - for range time.Tick(d) { - CaptureDebugGCStatsOnce(r) - } -} - -// Capture new values for the Go garbage collector statistics exported in -// debug.GCStats. This is designed to be called in a background goroutine. -// Giving a registry which has not been given to RegisterDebugGCStats will -// panic. -// -// Be careful (but much less so) with this because debug.ReadGCStats calls -// the C function runtime·lock(runtime·mheap) which, while not a stop-the-world -// operation, isn't something you want to be doing all the time. -func CaptureDebugGCStatsOnce(r Registry) { - lastGC := gcStats.LastGC - t := time.Now() - debug.ReadGCStats(&gcStats) - debugMetrics.ReadGCStats.UpdateSince(t) - - debugMetrics.GCStats.LastGC.Update(gcStats.LastGC.UnixNano()) - debugMetrics.GCStats.NumGC.Update(gcStats.NumGC) - if lastGC != gcStats.LastGC && 0 < len(gcStats.Pause) { - debugMetrics.GCStats.Pause.Update(int64(gcStats.Pause[0])) - } - //debugMetrics.GCStats.PauseQuantiles.Update(gcStats.PauseQuantiles) - debugMetrics.GCStats.PauseTotal.Update(int64(gcStats.PauseTotal)) -} - -// Register metrics for the Go garbage collector statistics exported in -// debug.GCStats. The metrics are named by their fully-qualified Go symbols, -// i.e. debug.GCStats.PauseTotal. -func RegisterDebugGCStats(r Registry) { - debugMetrics.GCStats.LastGC = NewGauge() - debugMetrics.GCStats.NumGC = NewGauge() - debugMetrics.GCStats.Pause = NewHistogram(NewExpDecaySample(1028, 0.015)) - //debugMetrics.GCStats.PauseQuantiles = NewHistogram(NewExpDecaySample(1028, 0.015)) - debugMetrics.GCStats.PauseTotal = NewGauge() - debugMetrics.ReadGCStats = NewTimer() - - r.Register("debug.GCStats.LastGC", debugMetrics.GCStats.LastGC) - r.Register("debug.GCStats.NumGC", debugMetrics.GCStats.NumGC) - r.Register("debug.GCStats.Pause", debugMetrics.GCStats.Pause) - //r.Register("debug.GCStats.PauseQuantiles", debugMetrics.GCStats.PauseQuantiles) - r.Register("debug.GCStats.PauseTotal", debugMetrics.GCStats.PauseTotal) - r.Register("debug.ReadGCStats", debugMetrics.ReadGCStats) -} - -// Allocate an initial slice for gcStats.Pause to avoid allocations during -// normal operation. -func init() { - gcStats.Pause = make([]time.Duration, 11) -} diff --git a/metrics/debug_test.go b/metrics/debug_test.go deleted file mode 100644 index 07eb867841..0000000000 --- a/metrics/debug_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package metrics - -import ( - "runtime" - "runtime/debug" - "testing" - "time" -) - -func BenchmarkDebugGCStats(b *testing.B) { - r := NewRegistry() - RegisterDebugGCStats(r) - b.ResetTimer() - for i := 0; i < b.N; i++ { - CaptureDebugGCStatsOnce(r) - } -} - -func TestDebugGCStatsBlocking(t *testing.T) { - if g := runtime.GOMAXPROCS(0); g < 2 { - t.Skipf("skipping TestDebugGCMemStatsBlocking with GOMAXPROCS=%d\n", g) - return - } - ch := make(chan int) - go testDebugGCStatsBlocking(ch) - var gcStats debug.GCStats - t0 := time.Now() - debug.ReadGCStats(&gcStats) - t1 := time.Now() - t.Log("i++ during debug.ReadGCStats:", <-ch) - go testDebugGCStatsBlocking(ch) - d := t1.Sub(t0) - t.Log(d) - time.Sleep(d) - t.Log("i++ during time.Sleep:", <-ch) -} - -func testDebugGCStatsBlocking(ch chan int) { - i := 0 - for { - select { - case ch <- i: - return - default: - i++ - } - } -} diff --git a/metrics/disk.go b/metrics/disk.go deleted file mode 100644 index 1fdd32a4d3..0000000000 --- a/metrics/disk.go +++ /dev/null @@ -1,35 +0,0 @@ -// (c) 2022, Ava Labs, Inc. -// -// This file is a derived work, based on the go-ethereum library whose original -// notices appear below. -// -// It is distributed under a license compatible with the licensing terms of the -// original code from which it is derived. -// -// Much love to the original authors for their work. -// ********** -// Copyright 2015 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package metrics - -// DiskStats is the per process disk io stats. -type DiskStats struct { - ReadCount int64 // Number of read operations executed - ReadBytes int64 // Total number of bytes read - WriteCount int64 // Number of write operations executed - WriteBytes int64 // Total number of byte written -} diff --git a/metrics/disk_linux.go b/metrics/disk_linux.go deleted file mode 100644 index 25341d748a..0000000000 --- a/metrics/disk_linux.go +++ /dev/null @@ -1,82 +0,0 @@ -// (c) 2022, Ava Labs, Inc. -// -// This file is a derived work, based on the go-ethereum library whose original -// notices appear below. -// -// It is distributed under a license compatible with the licensing terms of the -// original code from which it is derived. -// -// Much love to the original authors for their work. -// ********** -// Copyright 2015 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -// Contains the Linux implementation of process disk IO counter retrieval. - -package metrics - -import ( - "bufio" - "fmt" - "io" - "os" - "strconv" - "strings" -) - -// ReadDiskStats retrieves the disk IO stats belonging to the current process. -func ReadDiskStats(stats *DiskStats) error { - // Open the process disk IO counter file - inf, err := os.Open(fmt.Sprintf("/proc/%d/io", os.Getpid())) - if err != nil { - return err - } - defer inf.Close() - in := bufio.NewReader(inf) - - // Iterate over the IO counter, and extract what we need - for { - // Read the next line and split to key and value - line, err := in.ReadString('\n') - if err != nil { - if err == io.EOF { - return nil - } - return err - } - parts := strings.Split(line, ":") - if len(parts) != 2 { - continue - } - key := strings.TrimSpace(parts[0]) - value, err := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64) - if err != nil { - return err - } - - // Update the counter based on the key - switch key { - case "syscr": - stats.ReadCount = value - case "syscw": - stats.WriteCount = value - case "rchar": - stats.ReadBytes = value - case "wchar": - stats.WriteBytes = value - } - } -} diff --git a/metrics/disk_nop.go b/metrics/disk_nop.go deleted file mode 100644 index b1d6ff9f5d..0000000000 --- a/metrics/disk_nop.go +++ /dev/null @@ -1,37 +0,0 @@ -// (c) 2022, Ava Labs, Inc. -// -// This file is a derived work, based on the go-ethereum library whose original -// notices appear below. -// -// It is distributed under a license compatible with the licensing terms of the -// original code from which it is derived. -// -// Much love to the original authors for their work. -// ********** -// Copyright 2015 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -//go:build !linux -// +build !linux - -package metrics - -import "errors" - -// ReadDiskStats retrieves the disk IO stats belonging to the current process. -func ReadDiskStats(stats *DiskStats) error { - return errors.New("not implemented") -} diff --git a/metrics/ewma.go b/metrics/ewma.go deleted file mode 100644 index 1d7a4f00cf..0000000000 --- a/metrics/ewma.go +++ /dev/null @@ -1,111 +0,0 @@ -package metrics - -import ( - "math" - "sync" - "sync/atomic" - "time" -) - -type EWMASnapshot interface { - Rate() float64 -} - -// EWMAs continuously calculate an exponentially-weighted moving average -// based on an outside source of clock ticks. -type EWMA interface { - Snapshot() EWMASnapshot - Tick() - Update(int64) -} - -// NewEWMA constructs a new EWMA with the given alpha. -func NewEWMA(alpha float64) EWMA { - return &StandardEWMA{alpha: alpha} -} - -// NewEWMA1 constructs a new EWMA for a one-minute moving average. -func NewEWMA1() EWMA { - return NewEWMA(1 - math.Exp(-5.0/60.0/1)) -} - -// NewEWMA5 constructs a new EWMA for a five-minute moving average. -func NewEWMA5() EWMA { - return NewEWMA(1 - math.Exp(-5.0/60.0/5)) -} - -// NewEWMA15 constructs a new EWMA for a fifteen-minute moving average. -func NewEWMA15() EWMA { - return NewEWMA(1 - math.Exp(-5.0/60.0/15)) -} - -// ewmaSnapshot is a read-only copy of another EWMA. -type ewmaSnapshot float64 - -// Rate returns the rate of events per second at the time the snapshot was -// taken. -func (a ewmaSnapshot) Rate() float64 { return float64(a) } - -// NilEWMA is a no-op EWMA. -type NilEWMA struct{} - -func (NilEWMA) Snapshot() EWMASnapshot { return (*emptySnapshot)(nil) } -func (NilEWMA) Tick() {} -func (NilEWMA) Update(n int64) {} - -// StandardEWMA is the standard implementation of an EWMA and tracks the number -// of uncounted events and processes them on each tick. It uses the -// sync/atomic package to manage uncounted events. -type StandardEWMA struct { - uncounted atomic.Int64 - alpha float64 - rate atomic.Uint64 - init atomic.Bool - mutex sync.Mutex -} - -// Snapshot returns a read-only copy of the EWMA. -func (a *StandardEWMA) Snapshot() EWMASnapshot { - r := math.Float64frombits(a.rate.Load()) * float64(time.Second) - return ewmaSnapshot(r) -} - -// Tick ticks the clock to update the moving average. It assumes it is called -// every five seconds. -func (a *StandardEWMA) Tick() { - // Optimization to avoid mutex locking in the hot-path. - if a.init.Load() { - a.updateRate(a.fetchInstantRate()) - return - } - // Slow-path: this is only needed on the first Tick() and preserves transactional updating - // of init and rate in the else block. The first conditional is needed below because - // a different thread could have set a.init = 1 between the time of the first atomic load and when - // the lock was acquired. - a.mutex.Lock() - if a.init.Load() { - // The fetchInstantRate() uses atomic loading, which is unnecessary in this critical section - // but again, this section is only invoked on the first successful Tick() operation. - a.updateRate(a.fetchInstantRate()) - } else { - a.init.Store(true) - a.rate.Store(math.Float64bits(a.fetchInstantRate())) - } - a.mutex.Unlock() -} - -func (a *StandardEWMA) fetchInstantRate() float64 { - count := a.uncounted.Swap(0) - return float64(count) / float64(5*time.Second) -} - -func (a *StandardEWMA) updateRate(instantRate float64) { - currentRate := math.Float64frombits(a.rate.Load()) - currentRate += a.alpha * (instantRate - currentRate) - a.rate.Store(math.Float64bits(currentRate)) -} - -// Update adds n uncounted events. -func (a *StandardEWMA) Update(n int64) { - a.uncounted.Add(n) -} diff --git a/metrics/ewma_test.go b/metrics/ewma_test.go deleted file mode 100644 index 9a91b43db8..0000000000 --- a/metrics/ewma_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package metrics - -import ( - "math" - "testing" -) - -const epsilon = 0.0000000000000001 - -func BenchmarkEWMA(b *testing.B) { - a := NewEWMA1() - b.ResetTimer() - for i := 0; i < b.N; i++ { - a.Update(1) - a.Tick() - } -} - -func BenchmarkEWMAParallel(b *testing.B) { - a := NewEWMA1() - b.ResetTimer() - - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - a.Update(1) - a.Tick() - } - }) -} - -func TestEWMA1(t *testing.T) { - a := NewEWMA1() - a.Update(3) - a.Tick() - for i, want := range []float64{0.6, - 0.22072766470286553, 0.08120116994196772, 0.029872241020718428, - 0.01098938333324054, 0.004042768199451294, 0.0014872513059998212, - 0.0005471291793327122, 0.00020127757674150815, 7.404588245200814e-05, - 2.7239957857491083e-05, 1.0021020474147462e-05, 3.6865274119969525e-06, - 1.3561976441886433e-06, 4.989172314621449e-07, 1.8354139230109722e-07, - } { - if rate := a.Snapshot().Rate(); math.Abs(want-rate) > epsilon { - t.Errorf("%d minute a.Snapshot().Rate(): %f != %v\n", i, want, rate) - } - elapseMinute(a) - } -} - -func TestEWMA5(t *testing.T) { - a := NewEWMA5() - a.Update(3) - a.Tick() - for i, want := range []float64{ - 0.6, 0.49123845184678905, 0.4021920276213837, 0.32928698165641596, - 0.269597378470333, 0.2207276647028654, 0.18071652714732128, - 0.14795817836496392, 0.12113791079679326, 0.09917933293295193, - 0.08120116994196763, 0.06648189501740036, 0.05443077197364752, - 0.04456414692860035, 0.03648603757513079, 0.0298722410207183831020718428, - } { - if rate := a.Snapshot().Rate(); math.Abs(want-rate) > epsilon { - t.Errorf("%d minute a.Snapshot().Rate(): %f != %v\n", i, want, rate) - } - elapseMinute(a) - } -} - -func TestEWMA15(t *testing.T) { - a := NewEWMA15() - a.Update(3) - a.Tick() - for i, want := range []float64{ - 0.6, 0.5613041910189706, 0.5251039914257684, 0.4912384518467888184678905, - 0.459557003018789, 0.4299187863442732, 0.4021920276213831, - 0.37625345116383313, 0.3519877317060185, 0.3292869816564153165641596, - 0.3080502714195546, 0.2881831806538789, 0.26959737847033216, - 0.2522102307052083, 0.23594443252115815, 0.2207276647028646247028654470286553, - } { - if rate := a.Snapshot().Rate(); math.Abs(want-rate) > epsilon { - t.Errorf("%d minute a.Snapshot().Rate(): %f != %v\n", i, want, rate) - } - elapseMinute(a) - } -} - -func elapseMinute(a EWMA) { - for i := 0; i < 12; i++ { - a.Tick() - } -} diff --git a/metrics/gauge.go b/metrics/gauge.go deleted file mode 100644 index 5933df3107..0000000000 --- a/metrics/gauge.go +++ /dev/null @@ -1,98 +0,0 @@ -package metrics - -import "sync/atomic" - -// GaugeSnapshot contains a readonly int64. -type GaugeSnapshot interface { - Value() int64 -} - -// Gauge holds an int64 value that can be set arbitrarily. -type Gauge interface { - Snapshot() GaugeSnapshot - Update(int64) - UpdateIfGt(int64) - Dec(int64) - Inc(int64) -} - -// GetOrRegisterGauge returns an existing Gauge or constructs and registers a -// new StandardGauge. -func GetOrRegisterGauge(name string, r Registry) Gauge { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, NewGauge).(Gauge) -} - -// NewGauge constructs a new StandardGauge. -func NewGauge() Gauge { - if !Enabled { - return NilGauge{} - } - return &StandardGauge{} -} - -// NewRegisteredGauge constructs and registers a new StandardGauge. -func NewRegisteredGauge(name string, r Registry) Gauge { - c := NewGauge() - if nil == r { - r = DefaultRegistry - } - r.Register(name, c) - return c -} - -// gaugeSnapshot is a read-only copy of another Gauge. -type gaugeSnapshot int64 - -// Value returns the value at the time the snapshot was taken. -func (g gaugeSnapshot) Value() int64 { return int64(g) } - -// NilGauge is a no-op Gauge. -type NilGauge struct{} - -func (NilGauge) Snapshot() GaugeSnapshot { return (*emptySnapshot)(nil) } -func (NilGauge) Update(v int64) {} -func (NilGauge) UpdateIfGt(v int64) {} -func (NilGauge) Dec(i int64) {} -func (NilGauge) Inc(i int64) {} - -// StandardGauge is the standard implementation of a Gauge and uses the -// sync/atomic package to manage a single int64 value. -type StandardGauge struct { - value atomic.Int64 -} - -// Snapshot returns a read-only copy of the gauge. -func (g *StandardGauge) Snapshot() GaugeSnapshot { - return gaugeSnapshot(g.value.Load()) -} - -// Update updates the gauge's value. -func (g *StandardGauge) Update(v int64) { - g.value.Store(v) -} - -// Update updates the gauge's value if v is larger then the current value. -func (g *StandardGauge) UpdateIfGt(v int64) { - for { - exist := g.value.Load() - if exist >= v { - break - } - if g.value.CompareAndSwap(exist, v) { - break - } - } -} - -// Dec decrements the gauge's current value by the given amount. -func (g *StandardGauge) Dec(i int64) { - g.value.Add(-i) -} - -// Inc increments the gauge's current value by the given amount. -func (g *StandardGauge) Inc(i int64) { - g.value.Add(i) -} diff --git a/metrics/gauge_float64.go b/metrics/gauge_float64.go deleted file mode 100644 index c1c3c6b6e6..0000000000 --- a/metrics/gauge_float64.go +++ /dev/null @@ -1,73 +0,0 @@ -package metrics - -import ( - "math" - "sync/atomic" -) - -type GaugeFloat64Snapshot interface { - Value() float64 -} - -// GaugeFloat64 hold a float64 value that can be set arbitrarily. -type GaugeFloat64 interface { - Snapshot() GaugeFloat64Snapshot - Update(float64) -} - -// GetOrRegisterGaugeFloat64 returns an existing GaugeFloat64 or constructs and registers a -// new StandardGaugeFloat64. -func GetOrRegisterGaugeFloat64(name string, r Registry) GaugeFloat64 { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, NewGaugeFloat64()).(GaugeFloat64) -} - -// NewGaugeFloat64 constructs a new StandardGaugeFloat64. -func NewGaugeFloat64() GaugeFloat64 { - if !Enabled { - return NilGaugeFloat64{} - } - return &StandardGaugeFloat64{} -} - -// NewRegisteredGaugeFloat64 constructs and registers a new StandardGaugeFloat64. -func NewRegisteredGaugeFloat64(name string, r Registry) GaugeFloat64 { - c := NewGaugeFloat64() - if nil == r { - r = DefaultRegistry - } - r.Register(name, c) - return c -} - -// gaugeFloat64Snapshot is a read-only copy of another GaugeFloat64. -type gaugeFloat64Snapshot float64 - -// Value returns the value at the time the snapshot was taken. -func (g gaugeFloat64Snapshot) Value() float64 { return float64(g) } - -// NilGaugeFloat64 is a no-op Gauge. -type NilGaugeFloat64 struct{} - -func (NilGaugeFloat64) Snapshot() GaugeFloat64Snapshot { return NilGaugeFloat64{} } -func (NilGaugeFloat64) Update(v float64) {} -func (NilGaugeFloat64) Value() float64 { return 0.0 } - -// StandardGaugeFloat64 is the standard implementation of a GaugeFloat64 and uses -// atomic to manage a single float64 value. -type StandardGaugeFloat64 struct { - floatBits atomic.Uint64 -} - -// Snapshot returns a read-only copy of the gauge. -func (g *StandardGaugeFloat64) Snapshot() GaugeFloat64Snapshot { - v := math.Float64frombits(g.floatBits.Load()) - return gaugeFloat64Snapshot(v) -} - -// Update updates the gauge's value. -func (g *StandardGaugeFloat64) Update(v float64) { - g.floatBits.Store(math.Float64bits(v)) -} diff --git a/metrics/gauge_float64_test.go b/metrics/gauge_float64_test.go deleted file mode 100644 index 194a18821f..0000000000 --- a/metrics/gauge_float64_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package metrics - -import ( - "sync" - "testing" -) - -func BenchmarkGaugeFloat64(b *testing.B) { - g := NewGaugeFloat64() - b.ResetTimer() - for i := 0; i < b.N; i++ { - g.Update(float64(i)) - } -} - -func BenchmarkGaugeFloat64Parallel(b *testing.B) { - c := NewGaugeFloat64() - var wg sync.WaitGroup - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - for i := 0; i < b.N; i++ { - c.Update(float64(i)) - } - wg.Done() - }() - } - wg.Wait() - if have, want := c.Snapshot().Value(), float64(b.N-1); have != want { - b.Fatalf("have %f want %f", have, want) - } -} - -func TestGaugeFloat64Snapshot(t *testing.T) { - g := NewGaugeFloat64() - g.Update(47.0) - snapshot := g.Snapshot() - g.Update(float64(0)) - if v := snapshot.Value(); v != 47.0 { - t.Errorf("g.Value(): 47.0 != %v\n", v) - } -} - -func TestGetOrRegisterGaugeFloat64(t *testing.T) { - r := NewRegistry() - NewRegisteredGaugeFloat64("foo", r).Update(47.0) - t.Logf("registry: %v", r) - if g := GetOrRegisterGaugeFloat64("foo", r).Snapshot(); g.Value() != 47.0 { - t.Fatal(g) - } -} diff --git a/metrics/gauge_info.go b/metrics/gauge_info.go deleted file mode 100644 index 0010edc324..0000000000 --- a/metrics/gauge_info.go +++ /dev/null @@ -1,84 +0,0 @@ -package metrics - -import ( - "encoding/json" - "sync" -) - -type GaugeInfoSnapshot interface { - Value() GaugeInfoValue -} - -// GaugeInfo holds a GaugeInfoValue value that can be set arbitrarily. -type GaugeInfo interface { - Update(GaugeInfoValue) - Snapshot() GaugeInfoSnapshot -} - -// GaugeInfoValue is a mapping of keys to values -type GaugeInfoValue map[string]string - -func (val GaugeInfoValue) String() string { - data, _ := json.Marshal(val) - return string(data) -} - -// GetOrRegisterGaugeInfo returns an existing GaugeInfo or constructs and registers a -// new StandardGaugeInfo. -func GetOrRegisterGaugeInfo(name string, r Registry) GaugeInfo { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, NewGaugeInfo()).(GaugeInfo) -} - -// NewGaugeInfo constructs a new StandardGaugeInfo. -func NewGaugeInfo() GaugeInfo { - if !Enabled { - return NilGaugeInfo{} - } - return &StandardGaugeInfo{ - value: GaugeInfoValue{}, - } -} - -// NewRegisteredGaugeInfo constructs and registers a new StandardGaugeInfo. -func NewRegisteredGaugeInfo(name string, r Registry) GaugeInfo { - c := NewGaugeInfo() - if nil == r { - r = DefaultRegistry - } - r.Register(name, c) - return c -} - -// gaugeInfoSnapshot is a read-only copy of another GaugeInfo. -type gaugeInfoSnapshot GaugeInfoValue - -// Value returns the value at the time the snapshot was taken. -func (g gaugeInfoSnapshot) Value() GaugeInfoValue { return GaugeInfoValue(g) } - -type NilGaugeInfo struct{} - -func (NilGaugeInfo) Snapshot() GaugeInfoSnapshot { return NilGaugeInfo{} } -func (NilGaugeInfo) Update(v GaugeInfoValue) {} -func (NilGaugeInfo) Value() GaugeInfoValue { return GaugeInfoValue{} } - -// StandardGaugeInfo is the standard implementation of a GaugeInfo and uses -// sync.Mutex to manage a single string value. -type StandardGaugeInfo struct { - mutex sync.Mutex - value GaugeInfoValue -} - -// Snapshot returns a read-only copy of the gauge. -func (g *StandardGaugeInfo) Snapshot() GaugeInfoSnapshot { - return gaugeInfoSnapshot(g.value) -} - -// Update updates the gauge's value. -func (g *StandardGaugeInfo) Update(v GaugeInfoValue) { - g.mutex.Lock() - defer g.mutex.Unlock() - g.value = v -} diff --git a/metrics/gauge_info_test.go b/metrics/gauge_info_test.go deleted file mode 100644 index 319afbf92e..0000000000 --- a/metrics/gauge_info_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package metrics - -import ( - "testing" -) - -func TestGaugeInfoJsonString(t *testing.T) { - g := NewGaugeInfo() - g.Update(GaugeInfoValue{ - "chain_id": "5", - "anotherKey": "any_string_value", - "third_key": "anything", - }, - ) - want := `{"anotherKey":"any_string_value","chain_id":"5","third_key":"anything"}` - - original := g.Snapshot() - g.Update(GaugeInfoValue{"value": "updated"}) - - if have := original.Value().String(); have != want { - t.Errorf("\nhave: %v\nwant: %v\n", have, want) - } - if have, want := g.Snapshot().Value().String(), `{"value":"updated"}`; have != want { - t.Errorf("\nhave: %v\nwant: %v\n", have, want) - } -} - -func TestGetOrRegisterGaugeInfo(t *testing.T) { - r := NewRegistry() - NewRegisteredGaugeInfo("foo", r).Update( - GaugeInfoValue{"chain_id": "5"}) - g := GetOrRegisterGaugeInfo("foo", r).Snapshot() - if have, want := g.Value().String(), `{"chain_id":"5"}`; have != want { - t.Errorf("have\n%v\nwant\n%v\n", have, want) - } -} diff --git a/metrics/gauge_test.go b/metrics/gauge_test.go deleted file mode 100644 index f2ba930bc4..0000000000 --- a/metrics/gauge_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package metrics - -import ( - "testing" -) - -func BenchmarkGauge(b *testing.B) { - g := NewGauge() - b.ResetTimer() - for i := 0; i < b.N; i++ { - g.Update(int64(i)) - } -} - -func TestGaugeSnapshot(t *testing.T) { - g := NewGauge() - g.Update(int64(47)) - snapshot := g.Snapshot() - g.Update(int64(0)) - if v := snapshot.Value(); v != 47 { - t.Errorf("g.Value(): 47 != %v\n", v) - } -} - -func TestGetOrRegisterGauge(t *testing.T) { - r := NewRegistry() - NewRegisteredGauge("foo", r).Update(47) - if g := GetOrRegisterGauge("foo", r); g.Snapshot().Value() != 47 { - t.Fatal(g) - } -} diff --git a/metrics/graphite.go b/metrics/graphite.go deleted file mode 100644 index aba752e0ed..0000000000 --- a/metrics/graphite.go +++ /dev/null @@ -1,117 +0,0 @@ -package metrics - -import ( - "bufio" - "fmt" - "log" - "net" - "strconv" - "strings" - "time" -) - -// GraphiteConfig provides a container with configuration parameters for -// the Graphite exporter -type GraphiteConfig struct { - Addr *net.TCPAddr // Network address to connect to - Registry Registry // Registry to be exported - FlushInterval time.Duration // Flush interval - DurationUnit time.Duration // Time conversion unit for durations - Prefix string // Prefix to be prepended to metric names - Percentiles []float64 // Percentiles to export from timers and histograms -} - -// Graphite is a blocking exporter function which reports metrics in r -// to a graphite server located at addr, flushing them every d duration -// and prepending metric names with prefix. -func Graphite(r Registry, d time.Duration, prefix string, addr *net.TCPAddr) { - GraphiteWithConfig(GraphiteConfig{ - Addr: addr, - Registry: r, - FlushInterval: d, - DurationUnit: time.Nanosecond, - Prefix: prefix, - Percentiles: []float64{0.5, 0.75, 0.95, 0.99, 0.999}, - }) -} - -// GraphiteWithConfig is a blocking exporter function just like Graphite, -// but it takes a GraphiteConfig instead. -func GraphiteWithConfig(c GraphiteConfig) { - log.Printf("WARNING: This go-metrics client has been DEPRECATED! It has been moved to https://github.com/cyberdelia/go-metrics-graphite and will be removed from rcrowley/go-metrics on August 12th 2015") - for range time.Tick(c.FlushInterval) { - if err := graphite(&c); nil != err { - log.Println(err) - } - } -} - -// GraphiteOnce performs a single submission to Graphite, returning a -// non-nil error on failed connections. This can be used in a loop -// similar to GraphiteWithConfig for custom error handling. -func GraphiteOnce(c GraphiteConfig) error { - log.Printf("WARNING: This go-metrics client has been DEPRECATED! It has been moved to https://github.com/cyberdelia/go-metrics-graphite and will be removed from rcrowley/go-metrics on August 12th 2015") - return graphite(&c) -} - -func graphite(c *GraphiteConfig) error { - now := time.Now().Unix() - du := float64(c.DurationUnit) - conn, err := net.DialTCP("tcp", nil, c.Addr) - if nil != err { - return err - } - defer conn.Close() - w := bufio.NewWriter(conn) - c.Registry.Each(func(name string, i interface{}) { - switch metric := i.(type) { - case Counter: - fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, metric.Snapshot().Count(), now) - case CounterFloat64: - fmt.Fprintf(w, "%s.%s.count %f %d\n", c.Prefix, name, metric.Snapshot().Count(), now) - case Gauge: - fmt.Fprintf(w, "%s.%s.value %d %d\n", c.Prefix, name, metric.Snapshot().Value(), now) - case GaugeFloat64: - fmt.Fprintf(w, "%s.%s.value %f %d\n", c.Prefix, name, metric.Snapshot().Value(), now) - case GaugeInfo: - fmt.Fprintf(w, "%s.%s.value %s %d\n", c.Prefix, name, metric.Snapshot().Value().String(), now) - case Histogram: - h := metric.Snapshot() - ps := h.Percentiles(c.Percentiles) - fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, h.Count(), now) - fmt.Fprintf(w, "%s.%s.min %d %d\n", c.Prefix, name, h.Min(), now) - fmt.Fprintf(w, "%s.%s.max %d %d\n", c.Prefix, name, h.Max(), now) - fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, h.Mean(), now) - fmt.Fprintf(w, "%s.%s.std-dev %.2f %d\n", c.Prefix, name, h.StdDev(), now) - for psIdx, psKey := range c.Percentiles { - key := strings.Replace(strconv.FormatFloat(psKey*100.0, 'f', -1, 64), ".", "", 1) - fmt.Fprintf(w, "%s.%s.%s-percentile %.2f %d\n", c.Prefix, name, key, ps[psIdx], now) - } - case Meter: - m := metric.Snapshot() - fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, m.Count(), now) - fmt.Fprintf(w, "%s.%s.one-minute %.2f %d\n", c.Prefix, name, m.Rate1(), now) - fmt.Fprintf(w, "%s.%s.five-minute %.2f %d\n", c.Prefix, name, m.Rate5(), now) - fmt.Fprintf(w, "%s.%s.fifteen-minute %.2f %d\n", c.Prefix, name, m.Rate15(), now) - fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, m.RateMean(), now) - case Timer: - t := metric.Snapshot() - ps := t.Percentiles(c.Percentiles) - fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, t.Count(), now) - fmt.Fprintf(w, "%s.%s.min %d %d\n", c.Prefix, name, t.Min()/int64(du), now) - fmt.Fprintf(w, "%s.%s.max %d %d\n", c.Prefix, name, t.Max()/int64(du), now) - fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, t.Mean()/du, now) - fmt.Fprintf(w, "%s.%s.std-dev %.2f %d\n", c.Prefix, name, t.StdDev()/du, now) - for psIdx, psKey := range c.Percentiles { - key := strings.Replace(strconv.FormatFloat(psKey*100.0, 'f', -1, 64), ".", "", 1) - fmt.Fprintf(w, "%s.%s.%s-percentile %.2f %d\n", c.Prefix, name, key, ps[psIdx], now) - } - fmt.Fprintf(w, "%s.%s.one-minute %.2f %d\n", c.Prefix, name, t.Rate1(), now) - fmt.Fprintf(w, "%s.%s.five-minute %.2f %d\n", c.Prefix, name, t.Rate5(), now) - fmt.Fprintf(w, "%s.%s.fifteen-minute %.2f %d\n", c.Prefix, name, t.Rate15(), now) - fmt.Fprintf(w, "%s.%s.mean-rate %.2f %d\n", c.Prefix, name, t.RateMean(), now) - } - w.Flush() - }) - return nil -} diff --git a/metrics/graphite_test.go b/metrics/graphite_test.go deleted file mode 100644 index c797c781df..0000000000 --- a/metrics/graphite_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package metrics - -import ( - "net" - "time" -) - -func ExampleGraphite() { - addr, _ := net.ResolveTCPAddr("net", ":2003") - go Graphite(DefaultRegistry, 1*time.Second, "some.prefix", addr) -} - -func ExampleGraphiteWithConfig() { - addr, _ := net.ResolveTCPAddr("net", ":2003") - go GraphiteWithConfig(GraphiteConfig{ - Addr: addr, - Registry: DefaultRegistry, - FlushInterval: 1 * time.Second, - DurationUnit: time.Millisecond, - Percentiles: []float64{0.5, 0.75, 0.99, 0.999}, - }) -} diff --git a/metrics/healthcheck.go b/metrics/healthcheck.go deleted file mode 100644 index adcd15ab58..0000000000 --- a/metrics/healthcheck.go +++ /dev/null @@ -1,61 +0,0 @@ -package metrics - -// Healthcheck holds an error value describing an arbitrary up/down status. -type Healthcheck interface { - Check() - Error() error - Healthy() - Unhealthy(error) -} - -// NewHealthcheck constructs a new Healthcheck which will use the given -// function to update its status. -func NewHealthcheck(f func(Healthcheck)) Healthcheck { - if !Enabled { - return NilHealthcheck{} - } - return &StandardHealthcheck{nil, f} -} - -// NilHealthcheck is a no-op. -type NilHealthcheck struct{} - -// Check is a no-op. -func (NilHealthcheck) Check() {} - -// Error is a no-op. -func (NilHealthcheck) Error() error { return nil } - -// Healthy is a no-op. -func (NilHealthcheck) Healthy() {} - -// Unhealthy is a no-op. -func (NilHealthcheck) Unhealthy(error) {} - -// StandardHealthcheck is the standard implementation of a Healthcheck and -// stores the status and a function to call to update the status. -type StandardHealthcheck struct { - err error - f func(Healthcheck) -} - -// Check runs the healthcheck function to update the healthcheck's status. -func (h *StandardHealthcheck) Check() { - h.f(h) -} - -// Error returns the healthcheck's status, which will be nil if it is healthy. -func (h *StandardHealthcheck) Error() error { - return h.err -} - -// Healthy marks the healthcheck as healthy. -func (h *StandardHealthcheck) Healthy() { - h.err = nil -} - -// Unhealthy marks the healthcheck as unhealthy. The error is stored and -// may be retrieved by the Error method. -func (h *StandardHealthcheck) Unhealthy(err error) { - h.err = err -} diff --git a/metrics/histogram.go b/metrics/histogram.go deleted file mode 100644 index 10259a2463..0000000000 --- a/metrics/histogram.go +++ /dev/null @@ -1,73 +0,0 @@ -package metrics - -type HistogramSnapshot interface { - SampleSnapshot -} - -// Histogram calculates distribution statistics from a series of int64 values. -type Histogram interface { - Clear() - Update(int64) - Snapshot() HistogramSnapshot -} - -// GetOrRegisterHistogram returns an existing Histogram or constructs and -// registers a new StandardHistogram. -func GetOrRegisterHistogram(name string, r Registry, s Sample) Histogram { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, func() Histogram { return NewHistogram(s) }).(Histogram) -} - -// GetOrRegisterHistogramLazy returns an existing Histogram or constructs and -// registers a new StandardHistogram. -func GetOrRegisterHistogramLazy(name string, r Registry, s func() Sample) Histogram { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, func() Histogram { return NewHistogram(s()) }).(Histogram) -} - -// NewHistogram constructs a new StandardHistogram from a Sample. -func NewHistogram(s Sample) Histogram { - if !Enabled { - return NilHistogram{} - } - return &StandardHistogram{sample: s} -} - -// NewRegisteredHistogram constructs and registers a new StandardHistogram from -// a Sample. -func NewRegisteredHistogram(name string, r Registry, s Sample) Histogram { - c := NewHistogram(s) - if nil == r { - r = DefaultRegistry - } - r.Register(name, c) - return c -} - -// NilHistogram is a no-op Histogram. -type NilHistogram struct{} - -func (NilHistogram) Clear() {} -func (NilHistogram) Snapshot() HistogramSnapshot { return (*emptySnapshot)(nil) } -func (NilHistogram) Update(v int64) {} - -// StandardHistogram is the standard implementation of a Histogram and uses a -// Sample to bound its memory use. -type StandardHistogram struct { - sample Sample -} - -// Clear clears the histogram and its sample. -func (h *StandardHistogram) Clear() { h.sample.Clear() } - -// Snapshot returns a read-only copy of the histogram. -func (h *StandardHistogram) Snapshot() HistogramSnapshot { - return h.sample.Snapshot() -} - -// Update samples a new value. -func (h *StandardHistogram) Update(v int64) { h.sample.Update(v) } diff --git a/metrics/histogram_test.go b/metrics/histogram_test.go deleted file mode 100644 index 22fc5468b0..0000000000 --- a/metrics/histogram_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package metrics - -import "testing" - -func BenchmarkHistogram(b *testing.B) { - h := NewHistogram(NewUniformSample(100)) - b.ResetTimer() - for i := 0; i < b.N; i++ { - h.Update(int64(i)) - } -} - -func TestGetOrRegisterHistogram(t *testing.T) { - r := NewRegistry() - s := NewUniformSample(100) - NewRegisteredHistogram("foo", r, s).Update(47) - if h := GetOrRegisterHistogram("foo", r, s).Snapshot(); h.Count() != 1 { - t.Fatal(h) - } -} - -func TestHistogram10000(t *testing.T) { - h := NewHistogram(NewUniformSample(100000)) - for i := 1; i <= 10000; i++ { - h.Update(int64(i)) - } - testHistogram10000(t, h.Snapshot()) -} - -func TestHistogramEmpty(t *testing.T) { - h := NewHistogram(NewUniformSample(100)).Snapshot() - if count := h.Count(); count != 0 { - t.Errorf("h.Count(): 0 != %v\n", count) - } - if min := h.Min(); min != 0 { - t.Errorf("h.Min(): 0 != %v\n", min) - } - if max := h.Max(); max != 0 { - t.Errorf("h.Max(): 0 != %v\n", max) - } - if mean := h.Mean(); mean != 0.0 { - t.Errorf("h.Mean(): 0.0 != %v\n", mean) - } - if stdDev := h.StdDev(); stdDev != 0.0 { - t.Errorf("h.StdDev(): 0.0 != %v\n", stdDev) - } - ps := h.Percentiles([]float64{0.5, 0.75, 0.99}) - if ps[0] != 0.0 { - t.Errorf("median: 0.0 != %v\n", ps[0]) - } - if ps[1] != 0.0 { - t.Errorf("75th percentile: 0.0 != %v\n", ps[1]) - } - if ps[2] != 0.0 { - t.Errorf("99th percentile: 0.0 != %v\n", ps[2]) - } -} - -func TestHistogramSnapshot(t *testing.T) { - h := NewHistogram(NewUniformSample(100000)) - for i := 1; i <= 10000; i++ { - h.Update(int64(i)) - } - snapshot := h.Snapshot() - h.Update(0) - testHistogram10000(t, snapshot) -} - -func testHistogram10000(t *testing.T, h HistogramSnapshot) { - if count := h.Count(); count != 10000 { - t.Errorf("h.Count(): 10000 != %v\n", count) - } - if min := h.Min(); min != 1 { - t.Errorf("h.Min(): 1 != %v\n", min) - } - if max := h.Max(); max != 10000 { - t.Errorf("h.Max(): 10000 != %v\n", max) - } - if mean := h.Mean(); mean != 5000.5 { - t.Errorf("h.Mean(): 5000.5 != %v\n", mean) - } - if stdDev := h.StdDev(); stdDev != 2886.751331514372 { - t.Errorf("h.StdDev(): 2886.751331514372 != %v\n", stdDev) - } - ps := h.Percentiles([]float64{0.5, 0.75, 0.99}) - if ps[0] != 5000.5 { - t.Errorf("median: 5000.5 != %v\n", ps[0]) - } - if ps[1] != 7500.75 { - t.Errorf("75th percentile: 7500.75 != %v\n", ps[1]) - } - if ps[2] != 9900.99 { - t.Errorf("99th percentile: 9900.99 != %v\n", ps[2]) - } -} diff --git a/metrics/inactive.go b/metrics/inactive.go deleted file mode 100644 index 1f47f0210a..0000000000 --- a/metrics/inactive.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2023 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package metrics - -// compile-time checks that interfaces are implemented. -var ( - _ SampleSnapshot = (*emptySnapshot)(nil) - _ HistogramSnapshot = (*emptySnapshot)(nil) - _ CounterSnapshot = (*emptySnapshot)(nil) - _ GaugeSnapshot = (*emptySnapshot)(nil) - _ MeterSnapshot = (*emptySnapshot)(nil) - _ EWMASnapshot = (*emptySnapshot)(nil) - _ TimerSnapshot = (*emptySnapshot)(nil) -) - -type emptySnapshot struct{} - -func (*emptySnapshot) Count() int64 { return 0 } -func (*emptySnapshot) Max() int64 { return 0 } -func (*emptySnapshot) Mean() float64 { return 0.0 } -func (*emptySnapshot) Min() int64 { return 0 } -func (*emptySnapshot) Percentile(p float64) float64 { return 0.0 } -func (*emptySnapshot) Percentiles(ps []float64) []float64 { return make([]float64, len(ps)) } -func (*emptySnapshot) Size() int { return 0 } -func (*emptySnapshot) StdDev() float64 { return 0.0 } -func (*emptySnapshot) Sum() int64 { return 0 } -func (*emptySnapshot) Values() []int64 { return []int64{} } -func (*emptySnapshot) Variance() float64 { return 0.0 } -func (*emptySnapshot) Value() int64 { return 0 } -func (*emptySnapshot) Rate() float64 { return 0.0 } -func (*emptySnapshot) Rate1() float64 { return 0.0 } -func (*emptySnapshot) Rate5() float64 { return 0.0 } -func (*emptySnapshot) Rate15() float64 { return 0.0 } -func (*emptySnapshot) RateMean() float64 { return 0.0 } diff --git a/metrics/init_test.go b/metrics/init_test.go deleted file mode 100644 index 43401e833c..0000000000 --- a/metrics/init_test.go +++ /dev/null @@ -1,5 +0,0 @@ -package metrics - -func init() { - Enabled = true -} diff --git a/metrics/json.go b/metrics/json.go deleted file mode 100644 index 2087d8211e..0000000000 --- a/metrics/json.go +++ /dev/null @@ -1,31 +0,0 @@ -package metrics - -import ( - "encoding/json" - "io" - "time" -) - -// MarshalJSON returns a byte slice containing a JSON representation of all -// the metrics in the Registry. -func (r *StandardRegistry) MarshalJSON() ([]byte, error) { - return json.Marshal(r.GetAll()) -} - -// WriteJSON writes metrics from the given registry periodically to the -// specified io.Writer as JSON. -func WriteJSON(r Registry, d time.Duration, w io.Writer) { - for range time.Tick(d) { - WriteJSONOnce(r, w) - } -} - -// WriteJSONOnce writes metrics from the given registry to the specified -// io.Writer as JSON. -func WriteJSONOnce(r Registry, w io.Writer) { - json.NewEncoder(w).Encode(r) -} - -func (p *PrefixedRegistry) MarshalJSON() ([]byte, error) { - return json.Marshal(p.GetAll()) -} diff --git a/metrics/json_test.go b/metrics/json_test.go deleted file mode 100644 index f91fe8cfa5..0000000000 --- a/metrics/json_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package metrics - -import ( - "bytes" - "encoding/json" - "testing" -) - -func TestRegistryMarshallJSON(t *testing.T) { - b := &bytes.Buffer{} - enc := json.NewEncoder(b) - r := NewRegistry() - r.Register("counter", NewCounter()) - enc.Encode(r) - if s := b.String(); s != "{\"counter\":{\"count\":0}}\n" { - t.Fatalf(s) - } -} - -func TestRegistryWriteJSONOnce(t *testing.T) { - r := NewRegistry() - r.Register("counter", NewCounter()) - b := &bytes.Buffer{} - WriteJSONOnce(r, b) - if s := b.String(); s != "{\"counter\":{\"count\":0}}\n" { - t.Fail() - } -} diff --git a/metrics/log.go b/metrics/log.go deleted file mode 100644 index 3b9773faa7..0000000000 --- a/metrics/log.go +++ /dev/null @@ -1,86 +0,0 @@ -package metrics - -import ( - "time" -) - -type Logger interface { - Printf(format string, v ...interface{}) -} - -func Log(r Registry, freq time.Duration, l Logger) { - LogScaled(r, freq, time.Nanosecond, l) -} - -// Output each metric in the given registry periodically using the given -// logger. Print timings in `scale` units (eg time.Millisecond) rather than nanos. -func LogScaled(r Registry, freq time.Duration, scale time.Duration, l Logger) { - du := float64(scale) - duSuffix := scale.String()[1:] - - for range time.Tick(freq) { - r.Each(func(name string, i interface{}) { - switch metric := i.(type) { - case Counter: - l.Printf("counter %s\n", name) - l.Printf(" count: %9d\n", metric.Snapshot().Count()) - case CounterFloat64: - l.Printf("counter %s\n", name) - l.Printf(" count: %f\n", metric.Snapshot().Count()) - case Gauge: - l.Printf("gauge %s\n", name) - l.Printf(" value: %9d\n", metric.Snapshot().Value()) - case GaugeFloat64: - l.Printf("gauge %s\n", name) - l.Printf(" value: %f\n", metric.Snapshot().Value()) - case GaugeInfo: - l.Printf("gauge %s\n", name) - l.Printf(" value: %s\n", metric.Snapshot().Value()) - case Healthcheck: - metric.Check() - l.Printf("healthcheck %s\n", name) - l.Printf(" error: %v\n", metric.Error()) - case Histogram: - h := metric.Snapshot() - ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) - l.Printf("histogram %s\n", name) - l.Printf(" count: %9d\n", h.Count()) - l.Printf(" min: %9d\n", h.Min()) - l.Printf(" max: %9d\n", h.Max()) - l.Printf(" mean: %12.2f\n", h.Mean()) - l.Printf(" stddev: %12.2f\n", h.StdDev()) - l.Printf(" median: %12.2f\n", ps[0]) - l.Printf(" 75%%: %12.2f\n", ps[1]) - l.Printf(" 95%%: %12.2f\n", ps[2]) - l.Printf(" 99%%: %12.2f\n", ps[3]) - l.Printf(" 99.9%%: %12.2f\n", ps[4]) - case Meter: - m := metric.Snapshot() - l.Printf("meter %s\n", name) - l.Printf(" count: %9d\n", m.Count()) - l.Printf(" 1-min rate: %12.2f\n", m.Rate1()) - l.Printf(" 5-min rate: %12.2f\n", m.Rate5()) - l.Printf(" 15-min rate: %12.2f\n", m.Rate15()) - l.Printf(" mean rate: %12.2f\n", m.RateMean()) - case Timer: - t := metric.Snapshot() - ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) - l.Printf("timer %s\n", name) - l.Printf(" count: %9d\n", t.Count()) - l.Printf(" min: %12.2f%s\n", float64(t.Min())/du, duSuffix) - l.Printf(" max: %12.2f%s\n", float64(t.Max())/du, duSuffix) - l.Printf(" mean: %12.2f%s\n", t.Mean()/du, duSuffix) - l.Printf(" stddev: %12.2f%s\n", t.StdDev()/du, duSuffix) - l.Printf(" median: %12.2f%s\n", ps[0]/du, duSuffix) - l.Printf(" 75%%: %12.2f%s\n", ps[1]/du, duSuffix) - l.Printf(" 95%%: %12.2f%s\n", ps[2]/du, duSuffix) - l.Printf(" 99%%: %12.2f%s\n", ps[3]/du, duSuffix) - l.Printf(" 99.9%%: %12.2f%s\n", ps[4]/du, duSuffix) - l.Printf(" 1-min rate: %12.2f\n", t.Rate1()) - l.Printf(" 5-min rate: %12.2f\n", t.Rate5()) - l.Printf(" 15-min rate: %12.2f\n", t.Rate15()) - l.Printf(" mean rate: %12.2f\n", t.RateMean()) - } - }) - } -} diff --git a/metrics/memory.md b/metrics/memory.md deleted file mode 100644 index 47454f54b6..0000000000 --- a/metrics/memory.md +++ /dev/null @@ -1,285 +0,0 @@ -Memory usage -============ - -(Highly unscientific.) - -Command used to gather static memory usage: - -```sh -grep ^Vm "/proc/$(ps fax | grep [m]etrics-bench | awk '{print $1}')/status" -``` - -Program used to gather baseline memory usage: - -```go -package main - -import "time" - -func main() { - time.Sleep(600e9) -} -``` - -Baseline --------- - -``` -VmPeak: 42604 kB -VmSize: 42604 kB -VmLck: 0 kB -VmHWM: 1120 kB -VmRSS: 1120 kB -VmData: 35460 kB -VmStk: 136 kB -VmExe: 1020 kB -VmLib: 1848 kB -VmPTE: 36 kB -VmSwap: 0 kB -``` - -Program used to gather metric memory usage (with other metrics being similar): - -```go -package main - -import ( - "fmt" - "metrics" - "time" -) - -func main() { - fmt.Sprintf("foo") - metrics.NewRegistry() - time.Sleep(600e9) -} -``` - -1000 counters registered ------------------------- - -``` -VmPeak: 44016 kB -VmSize: 44016 kB -VmLck: 0 kB -VmHWM: 1928 kB -VmRSS: 1928 kB -VmData: 36868 kB -VmStk: 136 kB -VmExe: 1024 kB -VmLib: 1848 kB -VmPTE: 40 kB -VmSwap: 0 kB -``` - -**1.412 kB virtual, TODO 0.808 kB resident per counter.** - -100000 counters registered --------------------------- - -``` -VmPeak: 55024 kB -VmSize: 55024 kB -VmLck: 0 kB -VmHWM: 12440 kB -VmRSS: 12440 kB -VmData: 47876 kB -VmStk: 136 kB -VmExe: 1024 kB -VmLib: 1848 kB -VmPTE: 64 kB -VmSwap: 0 kB -``` - -**0.1242 kB virtual, 0.1132 kB resident per counter.** - -1000 gauges registered ----------------------- - -``` -VmPeak: 44012 kB -VmSize: 44012 kB -VmLck: 0 kB -VmHWM: 1928 kB -VmRSS: 1928 kB -VmData: 36868 kB -VmStk: 136 kB -VmExe: 1020 kB -VmLib: 1848 kB -VmPTE: 40 kB -VmSwap: 0 kB -``` - -**1.408 kB virtual, 0.808 kB resident per counter.** - -100000 gauges registered ------------------------- - -``` -VmPeak: 55020 kB -VmSize: 55020 kB -VmLck: 0 kB -VmHWM: 12432 kB -VmRSS: 12432 kB -VmData: 47876 kB -VmStk: 136 kB -VmExe: 1020 kB -VmLib: 1848 kB -VmPTE: 60 kB -VmSwap: 0 kB -``` - -**0.12416 kB virtual, 0.11312 resident per gauge.** - -1000 histograms with a uniform sample size of 1028 --------------------------------------------------- - -``` -VmPeak: 72272 kB -VmSize: 72272 kB -VmLck: 0 kB -VmHWM: 16204 kB -VmRSS: 16204 kB -VmData: 65100 kB -VmStk: 136 kB -VmExe: 1048 kB -VmLib: 1848 kB -VmPTE: 80 kB -VmSwap: 0 kB -``` - -**29.668 kB virtual, TODO 15.084 resident per histogram.** - -10000 histograms with a uniform sample size of 1028 ---------------------------------------------------- - -``` -VmPeak: 256912 kB -VmSize: 256912 kB -VmLck: 0 kB -VmHWM: 146204 kB -VmRSS: 146204 kB -VmData: 249740 kB -VmStk: 136 kB -VmExe: 1048 kB -VmLib: 1848 kB -VmPTE: 448 kB -VmSwap: 0 kB -``` - -**21.4308 kB virtual, 14.5084 kB resident per histogram.** - -50000 histograms with a uniform sample size of 1028 ---------------------------------------------------- - -``` -VmPeak: 908112 kB -VmSize: 908112 kB -VmLck: 0 kB -VmHWM: 645832 kB -VmRSS: 645588 kB -VmData: 900940 kB -VmStk: 136 kB -VmExe: 1048 kB -VmLib: 1848 kB -VmPTE: 1716 kB -VmSwap: 1544 kB -``` - -**17.31016 kB virtual, 12.88936 kB resident per histogram.** - -1000 histograms with an exponentially-decaying sample size of 1028 and alpha of 0.015 -------------------------------------------------------------------------------------- - -``` -VmPeak: 62480 kB -VmSize: 62480 kB -VmLck: 0 kB -VmHWM: 11572 kB -VmRSS: 11572 kB -VmData: 55308 kB -VmStk: 136 kB -VmExe: 1048 kB -VmLib: 1848 kB -VmPTE: 64 kB -VmSwap: 0 kB -``` - -**19.876 kB virtual, 10.452 kB resident per histogram.** - -10000 histograms with an exponentially-decaying sample size of 1028 and alpha of 0.015 --------------------------------------------------------------------------------------- - -``` -VmPeak: 153296 kB -VmSize: 153296 kB -VmLck: 0 kB -VmHWM: 101176 kB -VmRSS: 101176 kB -VmData: 146124 kB -VmStk: 136 kB -VmExe: 1048 kB -VmLib: 1848 kB -VmPTE: 240 kB -VmSwap: 0 kB -``` - -**11.0692 kB virtual, 10.0056 kB resident per histogram.** - -50000 histograms with an exponentially-decaying sample size of 1028 and alpha of 0.015 --------------------------------------------------------------------------------------- - -``` -VmPeak: 557264 kB -VmSize: 557264 kB -VmLck: 0 kB -VmHWM: 501056 kB -VmRSS: 501056 kB -VmData: 550092 kB -VmStk: 136 kB -VmExe: 1048 kB -VmLib: 1848 kB -VmPTE: 1032 kB -VmSwap: 0 kB -``` - -**10.2932 kB virtual, 9.99872 kB resident per histogram.** - -1000 meters ------------ - -``` -VmPeak: 74504 kB -VmSize: 74504 kB -VmLck: 0 kB -VmHWM: 24124 kB -VmRSS: 24124 kB -VmData: 67340 kB -VmStk: 136 kB -VmExe: 1040 kB -VmLib: 1848 kB -VmPTE: 92 kB -VmSwap: 0 kB -``` - -**31.9 kB virtual, 23.004 kB resident per meter.** - -10000 meters ------------- - -``` -VmPeak: 278920 kB -VmSize: 278920 kB -VmLck: 0 kB -VmHWM: 227300 kB -VmRSS: 227300 kB -VmData: 271756 kB -VmStk: 136 kB -VmExe: 1040 kB -VmLib: 1848 kB -VmPTE: 488 kB -VmSwap: 0 kB -``` - -**23.6316 kB virtual, 22.618 kB resident per meter.** diff --git a/metrics/meter.go b/metrics/meter.go deleted file mode 100644 index 22475ef6eb..0000000000 --- a/metrics/meter.go +++ /dev/null @@ -1,189 +0,0 @@ -package metrics - -import ( - "math" - "sync" - "sync/atomic" - "time" -) - -type MeterSnapshot interface { - Count() int64 - Rate1() float64 - Rate5() float64 - Rate15() float64 - RateMean() float64 -} - -// Meters count events to produce exponentially-weighted moving average rates -// at one-, five-, and fifteen-minutes and a mean rate. -type Meter interface { - Mark(int64) - Snapshot() MeterSnapshot - Stop() -} - -// GetOrRegisterMeter returns an existing Meter or constructs and registers a -// new StandardMeter. -// Be sure to unregister the meter from the registry once it is of no use to -// allow for garbage collection. -func GetOrRegisterMeter(name string, r Registry) Meter { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, NewMeter).(Meter) -} - -// NewMeter constructs a new StandardMeter and launches a goroutine. -// Be sure to call Stop() once the meter is of no use to allow for garbage collection. -func NewMeter() Meter { - if !Enabled { - return NilMeter{} - } - m := newStandardMeter() - arbiter.Lock() - defer arbiter.Unlock() - arbiter.meters[m] = struct{}{} - if !arbiter.started { - arbiter.started = true - go arbiter.tick() - } - return m -} - -// NewInactiveMeter returns a meter but does not start any goroutines. This -// method is mainly intended for testing. -func NewInactiveMeter() Meter { - if !Enabled { - return NilMeter{} - } - m := newStandardMeter() - return m -} - -// NewRegisteredMeter constructs and registers a new StandardMeter -// and launches a goroutine. -// Be sure to unregister the meter from the registry once it is of no use to -// allow for garbage collection. -func NewRegisteredMeter(name string, r Registry) Meter { - return GetOrRegisterMeter(name, r) -} - -// meterSnapshot is a read-only copy of the meter's internal values. -type meterSnapshot struct { - count int64 - rate1, rate5, rate15, rateMean float64 -} - -// Count returns the count of events at the time the snapshot was taken. -func (m *meterSnapshot) Count() int64 { return m.count } - -// Rate1 returns the one-minute moving average rate of events per second at the -// time the snapshot was taken. -func (m *meterSnapshot) Rate1() float64 { return m.rate1 } - -// Rate5 returns the five-minute moving average rate of events per second at -// the time the snapshot was taken. -func (m *meterSnapshot) Rate5() float64 { return m.rate5 } - -// Rate15 returns the fifteen-minute moving average rate of events per second -// at the time the snapshot was taken. -func (m *meterSnapshot) Rate15() float64 { return m.rate15 } - -// RateMean returns the meter's mean rate of events per second at the time the -// snapshot was taken. -func (m *meterSnapshot) RateMean() float64 { return m.rateMean } - -// NilMeter is a no-op Meter. -type NilMeter struct{} - -func (NilMeter) Count() int64 { return 0 } -func (NilMeter) Mark(n int64) {} -func (NilMeter) Snapshot() MeterSnapshot { return (*emptySnapshot)(nil) } -func (NilMeter) Stop() {} - -// StandardMeter is the standard implementation of a Meter. -type StandardMeter struct { - count atomic.Int64 - uncounted atomic.Int64 // not yet added to the EWMAs - rateMean atomic.Uint64 - - a1, a5, a15 EWMA - startTime time.Time - stopped atomic.Bool -} - -func newStandardMeter() *StandardMeter { - return &StandardMeter{ - a1: NewEWMA1(), - a5: NewEWMA5(), - a15: NewEWMA15(), - startTime: time.Now(), - } -} - -// Stop stops the meter, Mark() will be a no-op if you use it after being stopped. -func (m *StandardMeter) Stop() { - if stopped := m.stopped.Swap(true); !stopped { - arbiter.Lock() - delete(arbiter.meters, m) - arbiter.Unlock() - } -} - -// Mark records the occurrence of n events. -func (m *StandardMeter) Mark(n int64) { - m.uncounted.Add(n) -} - -// Snapshot returns a read-only copy of the meter. -func (m *StandardMeter) Snapshot() MeterSnapshot { - return &meterSnapshot{ - count: m.count.Load() + m.uncounted.Load(), - rate1: m.a1.Snapshot().Rate(), - rate5: m.a5.Snapshot().Rate(), - rate15: m.a15.Snapshot().Rate(), - rateMean: math.Float64frombits(m.rateMean.Load()), - } -} - -func (m *StandardMeter) tick() { - // Take the uncounted values, add to count - n := m.uncounted.Swap(0) - count := m.count.Add(n) - m.rateMean.Store(math.Float64bits(float64(count) / time.Since(m.startTime).Seconds())) - // Update the EWMA's internal state - m.a1.Update(n) - m.a5.Update(n) - m.a15.Update(n) - // And trigger them to calculate the rates - m.a1.Tick() - m.a5.Tick() - m.a15.Tick() -} - -// meterArbiter ticks meters every 5s from a single goroutine. -// meters are references in a set for future stopping. -type meterArbiter struct { - sync.RWMutex - started bool - meters map[*StandardMeter]struct{} - ticker *time.Ticker -} - -var arbiter = meterArbiter{ticker: time.NewTicker(5 * time.Second), meters: make(map[*StandardMeter]struct{})} - -// Ticks meters on the scheduled interval -func (ma *meterArbiter) tick() { - for range ma.ticker.C { - ma.tickMeters() - } -} - -func (ma *meterArbiter) tickMeters() { - ma.RLock() - defer ma.RUnlock() - for meter := range ma.meters { - meter.tick() - } -} diff --git a/metrics/meter_test.go b/metrics/meter_test.go deleted file mode 100644 index 019c4d765b..0000000000 --- a/metrics/meter_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package metrics - -import ( - "testing" - "time" -) - -func BenchmarkMeter(b *testing.B) { - m := NewMeter() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Mark(1) - } -} -func TestMeter(t *testing.T) { - m := NewMeter() - m.Mark(47) - if v := m.Snapshot().Count(); v != 47 { - t.Fatalf("have %d want %d", v, 47) - } -} -func TestGetOrRegisterMeter(t *testing.T) { - r := NewRegistry() - NewRegisteredMeter("foo", r).Mark(47) - if m := GetOrRegisterMeter("foo", r).Snapshot(); m.Count() != 47 { - t.Fatal(m.Count()) - } -} - -func TestMeterDecay(t *testing.T) { - ma := meterArbiter{ - ticker: time.NewTicker(time.Millisecond), - meters: make(map[*StandardMeter]struct{}), - } - defer ma.ticker.Stop() - m := newStandardMeter() - ma.meters[m] = struct{}{} - m.Mark(1) - ma.tickMeters() - rateMean := m.Snapshot().RateMean() - time.Sleep(100 * time.Millisecond) - ma.tickMeters() - if m.Snapshot().RateMean() >= rateMean { - t.Error("m.RateMean() didn't decrease") - } -} - -func TestMeterNonzero(t *testing.T) { - m := NewMeter() - m.Mark(3) - if count := m.Snapshot().Count(); count != 3 { - t.Errorf("m.Count(): 3 != %v\n", count) - } -} - -func TestMeterStop(t *testing.T) { - l := len(arbiter.meters) - m := NewMeter() - if l+1 != len(arbiter.meters) { - t.Errorf("arbiter.meters: %d != %d\n", l+1, len(arbiter.meters)) - } - m.Stop() - if l != len(arbiter.meters) { - t.Errorf("arbiter.meters: %d != %d\n", l, len(arbiter.meters)) - } -} - -func TestMeterZero(t *testing.T) { - m := NewMeter().Snapshot() - if count := m.Count(); count != 0 { - t.Errorf("m.Count(): 0 != %v\n", count) - } -} - -func TestMeterRepeat(t *testing.T) { - m := NewMeter() - for i := 0; i < 101; i++ { - m.Mark(int64(i)) - } - if count := m.Snapshot().Count(); count != 5050 { - t.Errorf("m.Count(): 5050 != %v\n", count) - } - for i := 0; i < 101; i++ { - m.Mark(int64(i)) - } - if count := m.Snapshot().Count(); count != 10100 { - t.Errorf("m.Count(): 10100 != %v\n", count) - } -} diff --git a/metrics/metrics.go b/metrics/metrics.go deleted file mode 100644 index e01beef68e..0000000000 --- a/metrics/metrics.go +++ /dev/null @@ -1,18 +0,0 @@ -// Go port of Coda Hale's Metrics library -// -// -// -// Coda Hale's original work: -package metrics - -// Enabled is checked by the constructor functions for all of the -// standard metrics. If it is true, the metric returned is a stub. -// -// This global kill-switch helps quantify the observer effect and makes -// for less cluttered pprof profiles. -var Enabled = true - -// EnabledExpensive is a soft-flag meant for external packages to check if costly -// metrics gathering is allowed or not. The goal is to separate standard metrics -// for health monitoring and debug metrics that might impact runtime performance. -var EnabledExpensive = false diff --git a/metrics/metrics_test.go b/metrics/metrics_test.go deleted file mode 100644 index 775b247185..0000000000 --- a/metrics/metrics_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package metrics - -import ( - "fmt" - "sync" - "testing" - "time" -) - -const FANOUT = 128 - -func BenchmarkMetrics(b *testing.B) { - r := NewRegistry() - c := NewRegisteredCounter("counter", r) - cf := NewRegisteredCounterFloat64("counterfloat64", r) - g := NewRegisteredGauge("gauge", r) - gf := NewRegisteredGaugeFloat64("gaugefloat64", r) - h := NewRegisteredHistogram("histogram", r, NewUniformSample(100)) - m := NewRegisteredMeter("meter", r) - t := NewRegisteredTimer("timer", r) - RegisterDebugGCStats(r) - b.ResetTimer() - ch := make(chan bool) - - wgD := &sync.WaitGroup{} - /* - wgD.Add(1) - go func() { - defer wgD.Done() - //log.Println("go CaptureDebugGCStats") - for { - select { - case <-ch: - //log.Println("done CaptureDebugGCStats") - return - default: - CaptureDebugGCStatsOnce(r) - } - } - }() - //*/ - - wgW := &sync.WaitGroup{} - /* - wgW.Add(1) - go func() { - defer wgW.Done() - //log.Println("go Write") - for { - select { - case <-ch: - //log.Println("done Write") - return - default: - WriteOnce(r, io.Discard) - } - } - }() - //*/ - - wg := &sync.WaitGroup{} - wg.Add(FANOUT) - for i := 0; i < FANOUT; i++ { - go func(i int) { - defer wg.Done() - //log.Println("go", i) - for i := 0; i < b.N; i++ { - c.Inc(1) - cf.Inc(1.0) - g.Update(int64(i)) - gf.Update(float64(i)) - h.Update(int64(i)) - m.Mark(1) - t.Update(1) - } - //log.Println("done", i) - }(i) - } - wg.Wait() - close(ch) - wgD.Wait() - wgW.Wait() -} - -func Example() { - c := NewCounter() - Register("money", c) - c.Inc(17) - - // Threadsafe registration - t := GetOrRegisterTimer("db.get.latency", nil) - t.Time(func() { time.Sleep(10 * time.Millisecond) }) - t.Update(1) - - fmt.Println(c.Snapshot().Count()) - fmt.Println(t.Snapshot().Min()) - // Output: 17 - // 1 -} diff --git a/metrics/opentsdb.go b/metrics/opentsdb.go deleted file mode 100644 index e81690f943..0000000000 --- a/metrics/opentsdb.go +++ /dev/null @@ -1,128 +0,0 @@ -package metrics - -import ( - "bufio" - "fmt" - "io" - "log" - "net" - "os" - "strings" - "time" -) - -var shortHostName = "" - -// OpenTSDBConfig provides a container with configuration parameters for -// the OpenTSDB exporter -type OpenTSDBConfig struct { - Addr *net.TCPAddr // Network address to connect to - Registry Registry // Registry to be exported - FlushInterval time.Duration // Flush interval - DurationUnit time.Duration // Time conversion unit for durations - Prefix string // Prefix to be prepended to metric names -} - -// OpenTSDB is a blocking exporter function which reports metrics in r -// to a TSDB server located at addr, flushing them every d duration -// and prepending metric names with prefix. -func OpenTSDB(r Registry, d time.Duration, prefix string, addr *net.TCPAddr) { - OpenTSDBWithConfig(OpenTSDBConfig{ - Addr: addr, - Registry: r, - FlushInterval: d, - DurationUnit: time.Nanosecond, - Prefix: prefix, - }) -} - -// OpenTSDBWithConfig is a blocking exporter function just like OpenTSDB, -// but it takes a OpenTSDBConfig instead. -func OpenTSDBWithConfig(c OpenTSDBConfig) { - for range time.Tick(c.FlushInterval) { - if err := openTSDB(&c); nil != err { - log.Println(err) - } - } -} - -func getShortHostname() string { - if shortHostName == "" { - host, _ := os.Hostname() - if index := strings.Index(host, "."); index > 0 { - shortHostName = host[:index] - } else { - shortHostName = host - } - } - return shortHostName -} - -// writeRegistry writes the registry-metrics on the opentsb format. -func (c *OpenTSDBConfig) writeRegistry(w io.Writer, now int64, shortHostname string) { - du := float64(c.DurationUnit) - - c.Registry.Each(func(name string, i interface{}) { - switch metric := i.(type) { - case Counter: - fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, metric.Snapshot().Count(), shortHostname) - case CounterFloat64: - fmt.Fprintf(w, "put %s.%s.count %d %f host=%s\n", c.Prefix, name, now, metric.Snapshot().Count(), shortHostname) - case Gauge: - fmt.Fprintf(w, "put %s.%s.value %d %d host=%s\n", c.Prefix, name, now, metric.Snapshot().Value(), shortHostname) - case GaugeFloat64: - fmt.Fprintf(w, "put %s.%s.value %d %f host=%s\n", c.Prefix, name, now, metric.Snapshot().Value(), shortHostname) - case GaugeInfo: - fmt.Fprintf(w, "put %s.%s.value %d %s host=%s\n", c.Prefix, name, now, metric.Snapshot().Value().String(), shortHostname) - case Histogram: - h := metric.Snapshot() - ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) - fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, h.Count(), shortHostname) - fmt.Fprintf(w, "put %s.%s.min %d %d host=%s\n", c.Prefix, name, now, h.Min(), shortHostname) - fmt.Fprintf(w, "put %s.%s.max %d %d host=%s\n", c.Prefix, name, now, h.Max(), shortHostname) - fmt.Fprintf(w, "put %s.%s.mean %d %.2f host=%s\n", c.Prefix, name, now, h.Mean(), shortHostname) - fmt.Fprintf(w, "put %s.%s.std-dev %d %.2f host=%s\n", c.Prefix, name, now, h.StdDev(), shortHostname) - fmt.Fprintf(w, "put %s.%s.50-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[0], shortHostname) - fmt.Fprintf(w, "put %s.%s.75-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[1], shortHostname) - fmt.Fprintf(w, "put %s.%s.95-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[2], shortHostname) - fmt.Fprintf(w, "put %s.%s.99-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[3], shortHostname) - fmt.Fprintf(w, "put %s.%s.999-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[4], shortHostname) - case Meter: - m := metric.Snapshot() - fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, m.Count(), shortHostname) - fmt.Fprintf(w, "put %s.%s.one-minute %d %.2f host=%s\n", c.Prefix, name, now, m.Rate1(), shortHostname) - fmt.Fprintf(w, "put %s.%s.five-minute %d %.2f host=%s\n", c.Prefix, name, now, m.Rate5(), shortHostname) - fmt.Fprintf(w, "put %s.%s.fifteen-minute %d %.2f host=%s\n", c.Prefix, name, now, m.Rate15(), shortHostname) - fmt.Fprintf(w, "put %s.%s.mean %d %.2f host=%s\n", c.Prefix, name, now, m.RateMean(), shortHostname) - case Timer: - t := metric.Snapshot() - ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) - fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, t.Count(), shortHostname) - fmt.Fprintf(w, "put %s.%s.min %d %d host=%s\n", c.Prefix, name, now, t.Min()/int64(du), shortHostname) - fmt.Fprintf(w, "put %s.%s.max %d %d host=%s\n", c.Prefix, name, now, t.Max()/int64(du), shortHostname) - fmt.Fprintf(w, "put %s.%s.mean %d %.2f host=%s\n", c.Prefix, name, now, t.Mean()/du, shortHostname) - fmt.Fprintf(w, "put %s.%s.std-dev %d %.2f host=%s\n", c.Prefix, name, now, t.StdDev()/du, shortHostname) - fmt.Fprintf(w, "put %s.%s.50-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[0]/du, shortHostname) - fmt.Fprintf(w, "put %s.%s.75-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[1]/du, shortHostname) - fmt.Fprintf(w, "put %s.%s.95-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[2]/du, shortHostname) - fmt.Fprintf(w, "put %s.%s.99-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[3]/du, shortHostname) - fmt.Fprintf(w, "put %s.%s.999-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[4]/du, shortHostname) - fmt.Fprintf(w, "put %s.%s.one-minute %d %.2f host=%s\n", c.Prefix, name, now, t.Rate1(), shortHostname) - fmt.Fprintf(w, "put %s.%s.five-minute %d %.2f host=%s\n", c.Prefix, name, now, t.Rate5(), shortHostname) - fmt.Fprintf(w, "put %s.%s.fifteen-minute %d %.2f host=%s\n", c.Prefix, name, now, t.Rate15(), shortHostname) - fmt.Fprintf(w, "put %s.%s.mean-rate %d %.2f host=%s\n", c.Prefix, name, now, t.RateMean(), shortHostname) - } - }) -} - -func openTSDB(c *OpenTSDBConfig) error { - conn, err := net.DialTCP("tcp", nil, c.Addr) - if nil != err { - return err - } - defer conn.Close() - w := bufio.NewWriter(conn) - c.writeRegistry(w, time.Now().Unix(), getShortHostname()) - w.Flush() - return nil -} diff --git a/metrics/opentsdb_test.go b/metrics/opentsdb_test.go deleted file mode 100644 index d13973a588..0000000000 --- a/metrics/opentsdb_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package metrics - -import ( - "fmt" - "net" - "os" - "strings" - "testing" - "time" -) - -func ExampleOpenTSDB() { - addr, _ := net.ResolveTCPAddr("net", ":2003") - go OpenTSDB(DefaultRegistry, 1*time.Second, "some.prefix", addr) -} - -func ExampleOpenTSDBWithConfig() { - addr, _ := net.ResolveTCPAddr("net", ":2003") - go OpenTSDBWithConfig(OpenTSDBConfig{ - Addr: addr, - Registry: DefaultRegistry, - FlushInterval: 1 * time.Second, - DurationUnit: time.Millisecond, - }) -} - -func TestExampleOpenTSB(t *testing.T) { - r := NewOrderedRegistry() - NewRegisteredGaugeInfo("foo", r).Update(GaugeInfoValue{"chain_id": "5"}) - NewRegisteredGaugeFloat64("pi", r).Update(3.14) - NewRegisteredCounter("months", r).Inc(12) - NewRegisteredCounterFloat64("tau", r).Inc(1.57) - NewRegisteredMeter("elite", r).Mark(1337) - NewRegisteredTimer("second", r).Update(time.Second) - NewRegisteredCounterFloat64("tau", r).Inc(1.57) - NewRegisteredCounterFloat64("tau", r).Inc(1.57) - - w := new(strings.Builder) - (&OpenTSDBConfig{ - Registry: r, - DurationUnit: time.Millisecond, - Prefix: "pre", - }).writeRegistry(w, 978307200, "hal9000") - - wantB, err := os.ReadFile("./testdata/opentsb.want") - if err != nil { - t.Fatal(err) - } - want := strings.ReplaceAll(string(wantB), "\r\n", "\n") - if have := w.String(); have != want { - t.Errorf("\nhave:\n%v\nwant:\n%v\n", have, want) - t.Logf("have vs want:\n%v", findFirstDiffPos(have, want)) - } -} - -func findFirstDiffPos(a, b string) string { - yy := strings.Split(b, "\n") - for i, x := range strings.Split(a, "\n") { - if i >= len(yy) { - return fmt.Sprintf("have:%d: %s\nwant:%d: ", i, x, i) - } - if y := yy[i]; x != y { - return fmt.Sprintf("have:%d: %s\nwant:%d: %s", i, x, i, y) - } - } - return "" -} diff --git a/metrics/prometheus/interfaces.go b/metrics/prometheus/interfaces.go new file mode 100644 index 0000000000..b9484722dd --- /dev/null +++ b/metrics/prometheus/interfaces.go @@ -0,0 +1,12 @@ +// (c) 2025 Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. +package prometheus + +// Registry is a narrower interface of [prometheus.Registry] containing +// only the required functions for the [Gatherer]. +type Registry interface { + // Call the given function for each registered metric. + Each(func(string, any)) + // Get the metric by the given name or nil if none is registered. + Get(string) any +} diff --git a/metrics/prometheus/prometheus.go b/metrics/prometheus/prometheus.go index 1d79cfbad7..07c14004ff 100644 --- a/metrics/prometheus/prometheus.go +++ b/metrics/prometheus/prometheus.go @@ -1,196 +1,197 @@ -// (c) 2021, Ava Labs, Inc. All rights reserved. +// (c) 2021-2025, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. package prometheus import ( + "errors" + "fmt" "sort" "strings" - "github.com/ava-labs/coreth/metrics" - "github.com/prometheus/client_golang/prometheus" + "github.com/ethereum/go-ethereum/metrics" + dto "github.com/prometheus/client_model/go" ) -var ( - pv = []float64{.5, .75, .95, .99, .999, .9999} - pvShortPercent = []float64{50, 95, 99} - pvShort = []float64{.50, .95, .99} -) +// Gatherer implements [prometheus.Gatherer] interface by +// gathering all metrics from the given Prometheus registry. +type Gatherer struct { + registry Registry +} + +var _ prometheus.Gatherer = (*Gatherer)(nil) -type gatherer struct { - reg metrics.Registry +// NewGatherer returns a [Gatherer] using the given registry. +func NewGatherer(registry Registry) *Gatherer { + return &Gatherer{ + registry: registry, + } } -func (g gatherer) Gather() ([]*dto.MetricFamily, error) { +// Gather gathers metrics from the registry and converts them to +// a slice of metric families. +func (g *Gatherer) Gather() (mfs []*dto.MetricFamily, err error) { // Gather and pre-sort the metrics to avoid random listings var names []string - g.reg.Each(func(name string, i interface{}) { + g.registry.Each(func(name string, i any) { names = append(names, name) }) sort.Strings(names) - mfs := make([]*dto.MetricFamily, 0, len(names)) + mfs = make([]*dto.MetricFamily, 0, len(names)) for _, name := range names { - mIntf := g.reg.Get(name) - name := strings.Replace(name, "/", "_", -1) - - switch m := mIntf.(type) { - case metrics.Counter: - val := m.Snapshot().Count() - valFloat := float64(val) - mfs = append(mfs, &dto.MetricFamily{ - Name: &name, - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{{ - Counter: &dto.Counter{ - Value: &valFloat, - }, - }}, - }) - case metrics.CounterFloat64: - val := m.Snapshot().Count() - mfs = append(mfs, &dto.MetricFamily{ - Name: &name, - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{{ - Counter: &dto.Counter{ - Value: &val, - }, - }}, - }) - case metrics.Gauge: - val := m.Snapshot().Value() - valFloat := float64(val) - mfs = append(mfs, &dto.MetricFamily{ - Name: &name, - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{{ - Gauge: &dto.Gauge{ - Value: &valFloat, - }, - }}, - }) - case metrics.GaugeFloat64: - val := m.Snapshot().Value() - mfs = append(mfs, &dto.MetricFamily{ - Name: &name, - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{{ - Gauge: &dto.Gauge{ - Value: &val, - }, - }}, - }) - case metrics.Histogram: - snapshot := m.Snapshot() - count := snapshot.Count() - countUint := uint64(count) - sum := snapshot.Sum() - sumFloat := float64(sum) - - ps := snapshot.Percentiles(pv) - qs := make([]*dto.Quantile, len(pv)) - for i := range ps { - v := pv[i] - s := ps[i] - qs[i] = &dto.Quantile{ - Quantile: &v, - Value: &s, - } + mf, err := metricFamily(g.registry, name) + if err != nil { + if errors.Is(err, errMetricSkip) { + continue } + return nil, err + } + mfs = append(mfs, mf) + } - mfs = append(mfs, &dto.MetricFamily{ - Name: &name, - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{{ - Summary: &dto.Summary{ - SampleCount: &countUint, - SampleSum: &sumFloat, - Quantile: qs, - }, - }}, - }) - case metrics.Meter: - val := m.Snapshot().Count() - valFloat := float64(val) - mfs = append(mfs, &dto.MetricFamily{ - Name: &name, - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{{ - Gauge: &dto.Gauge{ - Value: &valFloat, - }, - }}, - }) - case metrics.Timer: - snapshot := m.Snapshot() - count := snapshot.Count() - countUint := uint64(count) - sum := snapshot.Sum() - sumFloat := float64(sum) - - ps := snapshot.Percentiles(pv) - qs := make([]*dto.Quantile, len(pv)) - for i := range ps { - v := pv[i] - s := ps[i] - qs[i] = &dto.Quantile{ - Quantile: &v, - Value: &s, - } - } + return mfs, nil +} - mfs = append(mfs, &dto.MetricFamily{ - Name: &name, - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{{ - Summary: &dto.Summary{ - SampleCount: &countUint, - SampleSum: &sumFloat, - Quantile: qs, - }, - }}, - }) - case metrics.ResettingTimer: - snapshot := m.Snapshot() - - count := uint64(snapshot.Count()) - if count == 0 { - continue +var ( + errMetricSkip = errors.New("metric skipped") +) + +func ptrTo[T any](x T) *T { return &x } + +func metricFamily(registry Registry, name string) (mf *dto.MetricFamily, err error) { + metric := registry.Get(name) + name = strings.ReplaceAll(name, "/", "_") + + switch m := metric.(type) { + case metrics.Counter: + return &dto.MetricFamily{ + Name: &name, + Type: dto.MetricType_COUNTER.Enum(), + Metric: []*dto.Metric{{ + Counter: &dto.Counter{ + Value: ptrTo(float64(m.Snapshot().Count())), + }, + }}, + }, nil + case metrics.CounterFloat64: + return &dto.MetricFamily{ + Name: &name, + Type: dto.MetricType_COUNTER.Enum(), + Metric: []*dto.Metric{{ + Counter: &dto.Counter{ + Value: ptrTo(m.Snapshot().Count()), + }, + }}, + }, nil + case metrics.Gauge: + return &dto.MetricFamily{ + Name: &name, + Type: dto.MetricType_GAUGE.Enum(), + Metric: []*dto.Metric{{ + Gauge: &dto.Gauge{ + Value: ptrTo(float64(m.Snapshot().Value())), + }, + }}, + }, nil + case metrics.GaugeFloat64: + return &dto.MetricFamily{ + Name: &name, + Type: dto.MetricType_GAUGE.Enum(), + Metric: []*dto.Metric{{ + Gauge: &dto.Gauge{ + Value: ptrTo(m.Snapshot().Value()), + }, + }}, + }, nil + case metrics.Histogram: + snapshot := m.Snapshot() + + quantiles := []float64{.5, .75, .95, .99, .999, .9999} + thresholds := snapshot.Percentiles(quantiles) + dtoQuantiles := make([]*dto.Quantile, len(quantiles)) + for i := range thresholds { + dtoQuantiles[i] = &dto.Quantile{ + Quantile: ptrTo(quantiles[i]), + Value: ptrTo(thresholds[i]), } + } - ps := snapshot.Percentiles(pvShortPercent) - qs := make([]*dto.Quantile, len(pv)) - for i := range pvShort { - v := pv[i] - s := ps[i] - qs[i] = &dto.Quantile{ - Quantile: &v, - Value: &s, - } + return &dto.MetricFamily{ + Name: &name, + Type: dto.MetricType_SUMMARY.Enum(), + Metric: []*dto.Metric{{ + Summary: &dto.Summary{ + SampleCount: ptrTo(uint64(snapshot.Count())), //nolint:gosec + SampleSum: ptrTo(float64(snapshot.Sum())), + Quantile: dtoQuantiles, + }, + }}, + }, nil + case metrics.Meter: + return &dto.MetricFamily{ + Name: &name, + Type: dto.MetricType_GAUGE.Enum(), + Metric: []*dto.Metric{{ + Gauge: &dto.Gauge{ + Value: ptrTo(float64(m.Snapshot().Count())), + }, + }}, + }, nil + case metrics.Timer: + snapshot := m.Snapshot() + + quantiles := []float64{.5, .75, .95, .99, .999, .9999} + thresholds := snapshot.Percentiles(quantiles) + dtoQuantiles := make([]*dto.Quantile, len(quantiles)) + for i := range thresholds { + dtoQuantiles[i] = &dto.Quantile{ + Quantile: ptrTo(quantiles[i]), + Value: ptrTo(thresholds[i]), } + } - mfs = append(mfs, &dto.MetricFamily{ - Name: &name, - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{{ - Summary: &dto.Summary{ - SampleCount: &count, - // TODO: do we need to specify SampleSum here? and if so - // what should that be? - Quantile: qs, - }, - }}, - }) + return &dto.MetricFamily{ + Name: &name, + Type: dto.MetricType_SUMMARY.Enum(), + Metric: []*dto.Metric{{ + Summary: &dto.Summary{ + SampleCount: ptrTo(uint64(snapshot.Count())), //nolint:gosec + SampleSum: ptrTo(float64(snapshot.Sum())), + Quantile: dtoQuantiles, + }, + }}, + }, nil + case metrics.ResettingTimer: + snapshot := m.Snapshot() + if snapshot.Count() == 0 { + return nil, fmt.Errorf("%w: %q resetting timer metric count is zero", errMetricSkip, name) } - } - return mfs, nil -} + pvShortPercent := []float64{50, 95, 99} + thresholds := snapshot.Percentiles(pvShortPercent) + dtoQuantiles := make([]*dto.Quantile, len(pvShortPercent)) + for i := range pvShortPercent { + dtoQuantiles[i] = &dto.Quantile{ + Quantile: ptrTo(pvShortPercent[i]), + Value: ptrTo(thresholds[i]), + } + } -func Gatherer(reg metrics.Registry) prometheus.Gatherer { - return gatherer{reg: reg} + return &dto.MetricFamily{ + Name: &name, + Type: dto.MetricType_SUMMARY.Enum(), + Metric: []*dto.Metric{{ + Summary: &dto.Summary{ + SampleCount: ptrTo(uint64(snapshot.Count())), //nolint:gosec + Quantile: dtoQuantiles, + }, + }}, + }, nil + default: + return nil, fmt.Errorf("metric %q: type is not supported: %T", name, metric) + } } diff --git a/metrics/prometheus/prometheus_test.go b/metrics/prometheus/prometheus_test.go index 967e3f2602..00cce63c85 100644 --- a/metrics/prometheus/prometheus_test.go +++ b/metrics/prometheus/prometheus_test.go @@ -1,4 +1,4 @@ -// (c) 2021, Ava Labs, Inc. All rights reserved. +// (c) 2021-2025, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. package prometheus @@ -7,81 +7,91 @@ import ( "testing" "time" + "github.com/ava-labs/coreth/plugin/evm/testutils" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" - "github.com/ava-labs/coreth/metrics" + "github.com/ethereum/go-ethereum/metrics" ) -func TestGatherer(t *testing.T) { +func TestGatherer_Gather(t *testing.T) { + testutils.WithMetrics(t) + registry := metrics.NewRegistry() + register := func(t *testing.T, name string, collector any) { + t.Helper() + err := registry.Register(name, collector) + require.NoError(t, err) + } counter := metrics.NewCounter() counter.Inc(12345) + register(t, "test/counter", counter) - err := registry.Register("test/counter", counter) - assert.NoError(t, err) + counterFloat64 := metrics.NewCounterFloat64() + counterFloat64.Inc(1.1) + register(t, "test/counter_float64", counterFloat64) gauge := metrics.NewGauge() gauge.Update(23456) - - err = registry.Register("test/gauge", gauge) - assert.NoError(t, err) + register(t, "test/gauge", gauge) gaugeFloat64 := metrics.NewGaugeFloat64() gaugeFloat64.Update(34567.89) - - err = registry.Register("test/gauge_float64", gaugeFloat64) - assert.NoError(t, err) + register(t, "test/gauge_float64", gaugeFloat64) sample := metrics.NewUniformSample(1028) histogram := metrics.NewHistogram(sample) - - err = registry.Register("test/histogram", histogram) - assert.NoError(t, err) + register(t, "test/histogram", histogram) meter := metrics.NewMeter() - defer meter.Stop() + t.Cleanup(meter.Stop) meter.Mark(9999999) - - err = registry.Register("test/meter", meter) - assert.NoError(t, err) + register(t, "test/meter", meter) timer := metrics.NewTimer() - defer timer.Stop() + t.Cleanup(timer.Stop) timer.Update(20 * time.Millisecond) timer.Update(21 * time.Millisecond) timer.Update(22 * time.Millisecond) timer.Update(120 * time.Millisecond) timer.Update(23 * time.Millisecond) timer.Update(24 * time.Millisecond) - - err = registry.Register("test/timer", timer) - assert.NoError(t, err) + register(t, "test/timer", timer) resettingTimer := metrics.NewResettingTimer() - resettingTimer.Update(10 * time.Millisecond) - resettingTimer.Update(11 * time.Millisecond) - resettingTimer.Update(12 * time.Millisecond) - resettingTimer.Update(120 * time.Millisecond) - resettingTimer.Update(13 * time.Millisecond) - resettingTimer.Update(14 * time.Millisecond) - - err = registry.Register("test/resetting_timer", resettingTimer) - assert.NoError(t, err) - - err = registry.Register("test/resetting_timer_snapshot", resettingTimer.Snapshot()) - assert.NoError(t, err) + register(t, "test/resetting_timer", resettingTimer) + resettingTimer.Update(time.Second) // must be after register call emptyResettingTimer := metrics.NewResettingTimer() - - err = registry.Register("test/empty_resetting_timer", emptyResettingTimer) - assert.NoError(t, err) - - err = registry.Register("test/empty_resetting_timer_snapshot", emptyResettingTimer.Snapshot()) - assert.NoError(t, err) - - g := Gatherer(registry) - - _, err = g.Gather() - assert.NoError(t, err) + register(t, "test/empty_resetting_timer", emptyResettingTimer) + + emptyResettingTimer.Update(time.Second) // no effect because of snapshot below + register(t, "test/empty_resetting_timer_snapshot", emptyResettingTimer.Snapshot()) + + gatherer := NewGatherer(registry) + + families, err := gatherer.Gather() + require.NoError(t, err) + + familyStrings := make([]string, len(families)) + for i := range families { + familyStrings[i] = families[i].String() + } + want := []string{ + `name:"test_counter" type:COUNTER metric: > `, + `name:"test_counter_float64" type:COUNTER metric: > `, + `name:"test_gauge" type:GAUGE metric: > `, + `name:"test_gauge_float64" type:GAUGE metric: > `, + `name:"test_histogram" type:SUMMARY metric: quantile: quantile: quantile: quantile: quantile: > > `, + `name:"test_meter" type:GAUGE metric: > `, + `name:"test_resetting_timer" type:SUMMARY metric: quantile: quantile: > > `, + `name:"test_timer" type:SUMMARY metric: quantile: quantile: quantile: quantile: quantile: > > `, + } + assert.Equal(t, want, familyStrings) + + register(t, "unsupported", metrics.NewGaugeInfo()) + families, err = gatherer.Gather() + assert.EqualError(t, err, "metric \"unsupported\": type is not supported: *metrics.StandardGaugeInfo") + assert.Empty(t, families) } diff --git a/metrics/prometheus/testdata/prometheus.want b/metrics/prometheus/testdata/prometheus.want deleted file mode 100644 index 861c5f5cf0..0000000000 --- a/metrics/prometheus/testdata/prometheus.want +++ /dev/null @@ -1,70 +0,0 @@ -# TYPE system_cpu_schedlatency_count counter -system_cpu_schedlatency_count 5645 - -# TYPE system_cpu_schedlatency summary -system_cpu_schedlatency {quantile="0.5"} 0 -system_cpu_schedlatency {quantile="0.75"} 7168 -system_cpu_schedlatency {quantile="0.95"} 1.6777216e+07 -system_cpu_schedlatency {quantile="0.99"} 2.9360128e+07 -system_cpu_schedlatency {quantile="0.999"} 3.3554432e+07 -system_cpu_schedlatency {quantile="0.9999"} 3.3554432e+07 - -# TYPE system_memory_pauses_count counter -system_memory_pauses_count 14 - -# TYPE system_memory_pauses summary -system_memory_pauses {quantile="0.5"} 32768 -system_memory_pauses {quantile="0.75"} 57344 -system_memory_pauses {quantile="0.95"} 196608 -system_memory_pauses {quantile="0.99"} 196608 -system_memory_pauses {quantile="0.999"} 196608 -system_memory_pauses {quantile="0.9999"} 196608 - -# TYPE test_counter gauge -test_counter 12345 - -# TYPE test_counter_float64 gauge -test_counter_float64 54321.98 - -# TYPE test_gauge gauge -test_gauge 23456 - -# TYPE test_gauge_float64 gauge -test_gauge_float64 34567.89 - -# TYPE test_gauge_info gauge -test_gauge_info {arch="amd64", commit="7caa2d8163ae3132c1c2d6978c76610caee2d949", os="linux", protocol_versions="64 65 66", version="1.10.18-unstable"} 1 - -# TYPE test_histogram_count counter -test_histogram_count 3 - -# TYPE test_histogram summary -test_histogram {quantile="0.5"} 2 -test_histogram {quantile="0.75"} 3 -test_histogram {quantile="0.95"} 3 -test_histogram {quantile="0.99"} 3 -test_histogram {quantile="0.999"} 3 -test_histogram {quantile="0.9999"} 3 - -# TYPE test_meter gauge -test_meter 0 - -# TYPE test_resetting_timer_count counter -test_resetting_timer_count 6 - -# TYPE test_resetting_timer summary -test_resetting_timer {quantile="0.50"} 1.25e+07 -test_resetting_timer {quantile="0.95"} 1.2e+08 -test_resetting_timer {quantile="0.99"} 1.2e+08 - -# TYPE test_timer_count counter -test_timer_count 6 - -# TYPE test_timer summary -test_timer {quantile="0.5"} 2.25e+07 -test_timer {quantile="0.75"} 4.8e+07 -test_timer {quantile="0.95"} 1.2e+08 -test_timer {quantile="0.99"} 1.2e+08 -test_timer {quantile="0.999"} 1.2e+08 -test_timer {quantile="0.9999"} 1.2e+08 - diff --git a/metrics/registry.go b/metrics/registry.go deleted file mode 100644 index 8bfbc08042..0000000000 --- a/metrics/registry.go +++ /dev/null @@ -1,372 +0,0 @@ -package metrics - -import ( - "fmt" - "reflect" - "sort" - "strings" - "sync" -) - -// DuplicateMetric is the error returned by Registry.Register when a metric -// already exists. If you mean to Register that metric you must first -// Unregister the existing metric. -type DuplicateMetric string - -func (err DuplicateMetric) Error() string { - return fmt.Sprintf("duplicate metric: %s", string(err)) -} - -// A Registry holds references to a set of metrics by name and can iterate -// over them, calling callback functions provided by the user. -// -// This is an interface so as to encourage other structs to implement -// the Registry API as appropriate. -type Registry interface { - - // Call the given function for each registered metric. - Each(func(string, interface{})) - - // Get the metric by the given name or nil if none is registered. - Get(string) interface{} - - // GetAll metrics in the Registry. - GetAll() map[string]map[string]interface{} - - // Gets an existing metric or registers the given one. - // The interface can be the metric to register if not found in registry, - // or a function returning the metric for lazy instantiation. - GetOrRegister(string, interface{}) interface{} - - // Register the given metric under the given name. - Register(string, interface{}) error - - // Run all registered healthchecks. - RunHealthchecks() - - // Unregister the metric with the given name. - Unregister(string) -} - -type orderedRegistry struct { - StandardRegistry -} - -// Call the given function for each registered metric. -func (r *orderedRegistry) Each(f func(string, interface{})) { - var names []string - reg := r.registered() - for name := range reg { - names = append(names, name) - } - sort.Strings(names) - for _, name := range names { - f(name, reg[name]) - } -} - -// NewRegistry creates a new registry. -func NewRegistry() Registry { - return new(StandardRegistry) -} - -// NewOrderedRegistry creates a new ordered registry (for testing). -func NewOrderedRegistry() Registry { - return new(orderedRegistry) -} - -// The standard implementation of a Registry uses sync.map -// of names to metrics. -type StandardRegistry struct { - metrics sync.Map -} - -// Call the given function for each registered metric. -func (r *StandardRegistry) Each(f func(string, interface{})) { - for name, i := range r.registered() { - f(name, i) - } -} - -// Get the metric by the given name or nil if none is registered. -func (r *StandardRegistry) Get(name string) interface{} { - item, _ := r.metrics.Load(name) - return item -} - -// Gets an existing metric or creates and registers a new one. Threadsafe -// alternative to calling Get and Register on failure. -// The interface can be the metric to register if not found in registry, -// or a function returning the metric for lazy instantiation. -func (r *StandardRegistry) GetOrRegister(name string, i interface{}) interface{} { - // fast path - cached, ok := r.metrics.Load(name) - if ok { - return cached - } - if v := reflect.ValueOf(i); v.Kind() == reflect.Func { - i = v.Call(nil)[0].Interface() - } - item, _, ok := r.loadOrRegister(name, i) - if !ok { - return i - } - return item -} - -// Register the given metric under the given name. Returns a DuplicateMetric -// if a metric by the given name is already registered. -func (r *StandardRegistry) Register(name string, i interface{}) error { - // fast path - _, ok := r.metrics.Load(name) - if ok { - return DuplicateMetric(name) - } - - if v := reflect.ValueOf(i); v.Kind() == reflect.Func { - i = v.Call(nil)[0].Interface() - } - _, loaded, _ := r.loadOrRegister(name, i) - if loaded { - return DuplicateMetric(name) - } - return nil -} - -// Run all registered healthchecks. -func (r *StandardRegistry) RunHealthchecks() { - r.metrics.Range(func(key, value any) bool { - if h, ok := value.(Healthcheck); ok { - h.Check() - } - return true - }) -} - -// GetAll metrics in the Registry -func (r *StandardRegistry) GetAll() map[string]map[string]interface{} { - data := make(map[string]map[string]interface{}) - r.Each(func(name string, i interface{}) { - values := make(map[string]interface{}) - switch metric := i.(type) { - case Counter: - values["count"] = metric.Snapshot().Count() - case CounterFloat64: - values["count"] = metric.Snapshot().Count() - case Gauge: - values["value"] = metric.Snapshot().Value() - case GaugeFloat64: - values["value"] = metric.Snapshot().Value() - case Healthcheck: - values["error"] = nil - metric.Check() - if err := metric.Error(); nil != err { - values["error"] = metric.Error().Error() - } - case Histogram: - h := metric.Snapshot() - ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) - values["count"] = h.Count() - values["min"] = h.Min() - values["max"] = h.Max() - values["mean"] = h.Mean() - values["stddev"] = h.StdDev() - values["median"] = ps[0] - values["75%"] = ps[1] - values["95%"] = ps[2] - values["99%"] = ps[3] - values["99.9%"] = ps[4] - case Meter: - m := metric.Snapshot() - values["count"] = m.Count() - values["1m.rate"] = m.Rate1() - values["5m.rate"] = m.Rate5() - values["15m.rate"] = m.Rate15() - values["mean.rate"] = m.RateMean() - case Timer: - t := metric.Snapshot() - ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) - values["count"] = t.Count() - values["min"] = t.Min() - values["max"] = t.Max() - values["mean"] = t.Mean() - values["stddev"] = t.StdDev() - values["median"] = ps[0] - values["75%"] = ps[1] - values["95%"] = ps[2] - values["99%"] = ps[3] - values["99.9%"] = ps[4] - values["1m.rate"] = t.Rate1() - values["5m.rate"] = t.Rate5() - values["15m.rate"] = t.Rate15() - values["mean.rate"] = t.RateMean() - } - data[name] = values - }) - return data -} - -// Unregister the metric with the given name. -func (r *StandardRegistry) Unregister(name string) { - r.stop(name) - r.metrics.LoadAndDelete(name) -} - -func (r *StandardRegistry) loadOrRegister(name string, i interface{}) (interface{}, bool, bool) { - switch i.(type) { - case Counter, CounterFloat64, Gauge, GaugeFloat64, GaugeInfo, Healthcheck, Histogram, Meter, Timer, ResettingTimer: - default: - return nil, false, false - } - item, loaded := r.metrics.LoadOrStore(name, i) - return item, loaded, true -} - -func (r *StandardRegistry) registered() map[string]interface{} { - metrics := make(map[string]interface{}) - r.metrics.Range(func(key, value any) bool { - metrics[key.(string)] = value - return true - }) - return metrics -} - -func (r *StandardRegistry) stop(name string) { - if i, ok := r.metrics.Load(name); ok { - if s, ok := i.(Stoppable); ok { - s.Stop() - } - } -} - -// Stoppable defines the metrics which has to be stopped. -type Stoppable interface { - Stop() -} - -type PrefixedRegistry struct { - underlying Registry - prefix string -} - -func NewPrefixedRegistry(prefix string) Registry { - return &PrefixedRegistry{ - underlying: NewRegistry(), - prefix: prefix, - } -} - -func NewPrefixedChildRegistry(parent Registry, prefix string) Registry { - return &PrefixedRegistry{ - underlying: parent, - prefix: prefix, - } -} - -// Call the given function for each registered metric. -func (r *PrefixedRegistry) Each(fn func(string, interface{})) { - wrappedFn := func(prefix string) func(string, interface{}) { - return func(name string, iface interface{}) { - if strings.HasPrefix(name, prefix) { - fn(name, iface) - } else { - return - } - } - } - - baseRegistry, prefix := findPrefix(r, "") - baseRegistry.Each(wrappedFn(prefix)) -} - -func findPrefix(registry Registry, prefix string) (Registry, string) { - switch r := registry.(type) { - case *PrefixedRegistry: - return findPrefix(r.underlying, r.prefix+prefix) - case *StandardRegistry: - return r, prefix - } - return nil, "" -} - -// Get the metric by the given name or nil if none is registered. -func (r *PrefixedRegistry) Get(name string) interface{} { - realName := r.prefix + name - return r.underlying.Get(realName) -} - -// Gets an existing metric or registers the given one. -// The interface can be the metric to register if not found in registry, -// or a function returning the metric for lazy instantiation. -func (r *PrefixedRegistry) GetOrRegister(name string, metric interface{}) interface{} { - realName := r.prefix + name - return r.underlying.GetOrRegister(realName, metric) -} - -// Register the given metric under the given name. The name will be prefixed. -func (r *PrefixedRegistry) Register(name string, metric interface{}) error { - realName := r.prefix + name - return r.underlying.Register(realName, metric) -} - -// Run all registered healthchecks. -func (r *PrefixedRegistry) RunHealthchecks() { - r.underlying.RunHealthchecks() -} - -// GetAll metrics in the Registry -func (r *PrefixedRegistry) GetAll() map[string]map[string]interface{} { - return r.underlying.GetAll() -} - -// Unregister the metric with the given name. The name will be prefixed. -func (r *PrefixedRegistry) Unregister(name string) { - realName := r.prefix + name - r.underlying.Unregister(realName) -} - -var ( - DefaultRegistry = NewRegistry() - EphemeralRegistry = NewRegistry() - AccountingRegistry = NewRegistry() // registry used in swarm -) - -// Call the given function for each registered metric. -func Each(f func(string, interface{})) { - DefaultRegistry.Each(f) -} - -// Get the metric by the given name or nil if none is registered. -func Get(name string) interface{} { - return DefaultRegistry.Get(name) -} - -// Gets an existing metric or creates and registers a new one. Threadsafe -// alternative to calling Get and Register on failure. -func GetOrRegister(name string, i interface{}) interface{} { - return DefaultRegistry.GetOrRegister(name, i) -} - -// Register the given metric under the given name. Returns a DuplicateMetric -// if a metric by the given name is already registered. -func Register(name string, i interface{}) error { - return DefaultRegistry.Register(name, i) -} - -// Register the given metric under the given name. Panics if a metric by the -// given name is already registered. -func MustRegister(name string, i interface{}) { - if err := Register(name, i); err != nil { - panic(err) - } -} - -// Run all registered healthchecks. -func RunHealthchecks() { - DefaultRegistry.RunHealthchecks() -} - -// Unregister the metric with the given name. -func Unregister(name string) { - DefaultRegistry.Unregister(name) -} diff --git a/metrics/registry_test.go b/metrics/registry_test.go deleted file mode 100644 index 75012dd4ac..0000000000 --- a/metrics/registry_test.go +++ /dev/null @@ -1,335 +0,0 @@ -package metrics - -import ( - "sync" - "testing" -) - -func BenchmarkRegistry(b *testing.B) { - r := NewRegistry() - r.Register("foo", NewCounter()) - b.ResetTimer() - for i := 0; i < b.N; i++ { - r.Each(func(string, interface{}) {}) - } -} - -func BenchmarkRegistryGetOrRegisterParallel_8(b *testing.B) { - benchmarkRegistryGetOrRegisterParallel(b, 8) -} - -func BenchmarkRegistryGetOrRegisterParallel_32(b *testing.B) { - benchmarkRegistryGetOrRegisterParallel(b, 32) -} - -func benchmarkRegistryGetOrRegisterParallel(b *testing.B, amount int) { - r := NewRegistry() - b.ResetTimer() - var wg sync.WaitGroup - for i := 0; i < amount; i++ { - wg.Add(1) - go func() { - for i := 0; i < b.N; i++ { - r.GetOrRegister("foo", NewMeter) - } - wg.Done() - }() - } - wg.Wait() -} - -func TestRegistry(t *testing.T) { - r := NewRegistry() - r.Register("foo", NewCounter()) - i := 0 - r.Each(func(name string, iface interface{}) { - i++ - if name != "foo" { - t.Fatal(name) - } - if _, ok := iface.(Counter); !ok { - t.Fatal(iface) - } - }) - if i != 1 { - t.Fatal(i) - } - r.Unregister("foo") - i = 0 - r.Each(func(string, interface{}) { i++ }) - if i != 0 { - t.Fatal(i) - } -} - -func TestRegistryDuplicate(t *testing.T) { - r := NewRegistry() - if err := r.Register("foo", NewCounter()); nil != err { - t.Fatal(err) - } - if err := r.Register("foo", NewGauge()); nil == err { - t.Fatal(err) - } - i := 0 - r.Each(func(name string, iface interface{}) { - i++ - if _, ok := iface.(Counter); !ok { - t.Fatal(iface) - } - }) - if i != 1 { - t.Fatal(i) - } -} - -func TestRegistryGet(t *testing.T) { - r := NewRegistry() - r.Register("foo", NewCounter()) - if count := r.Get("foo").(Counter).Snapshot().Count(); count != 0 { - t.Fatal(count) - } - r.Get("foo").(Counter).Inc(1) - if count := r.Get("foo").(Counter).Snapshot().Count(); count != 1 { - t.Fatal(count) - } -} - -func TestRegistryGetOrRegister(t *testing.T) { - r := NewRegistry() - - // First metric wins with GetOrRegister - _ = r.GetOrRegister("foo", NewCounter()) - m := r.GetOrRegister("foo", NewGauge()) - if _, ok := m.(Counter); !ok { - t.Fatal(m) - } - - i := 0 - r.Each(func(name string, iface interface{}) { - i++ - if name != "foo" { - t.Fatal(name) - } - if _, ok := iface.(Counter); !ok { - t.Fatal(iface) - } - }) - if i != 1 { - t.Fatal(i) - } -} - -func TestRegistryGetOrRegisterWithLazyInstantiation(t *testing.T) { - r := NewRegistry() - - // First metric wins with GetOrRegister - _ = r.GetOrRegister("foo", NewCounter) - m := r.GetOrRegister("foo", NewGauge) - if _, ok := m.(Counter); !ok { - t.Fatal(m) - } - - i := 0 - r.Each(func(name string, iface interface{}) { - i++ - if name != "foo" { - t.Fatal(name) - } - if _, ok := iface.(Counter); !ok { - t.Fatal(iface) - } - }) - if i != 1 { - t.Fatal(i) - } -} - -func TestRegistryUnregister(t *testing.T) { - l := len(arbiter.meters) - r := NewRegistry() - r.Register("foo", NewCounter()) - r.Register("bar", NewMeter()) - r.Register("baz", NewTimer()) - if len(arbiter.meters) != l+2 { - t.Errorf("arbiter.meters: %d != %d\n", l+2, len(arbiter.meters)) - } - r.Unregister("foo") - r.Unregister("bar") - r.Unregister("baz") - if len(arbiter.meters) != l { - t.Errorf("arbiter.meters: %d != %d\n", l+2, len(arbiter.meters)) - } -} - -func TestPrefixedChildRegistryGetOrRegister(t *testing.T) { - r := NewRegistry() - pr := NewPrefixedChildRegistry(r, "prefix.") - - _ = pr.GetOrRegister("foo", NewCounter()) - - i := 0 - r.Each(func(name string, m interface{}) { - i++ - if name != "prefix.foo" { - t.Fatal(name) - } - }) - if i != 1 { - t.Fatal(i) - } -} - -func TestPrefixedRegistryGetOrRegister(t *testing.T) { - r := NewPrefixedRegistry("prefix.") - - _ = r.GetOrRegister("foo", NewCounter()) - - i := 0 - r.Each(func(name string, m interface{}) { - i++ - if name != "prefix.foo" { - t.Fatal(name) - } - }) - if i != 1 { - t.Fatal(i) - } -} - -func TestPrefixedRegistryRegister(t *testing.T) { - r := NewPrefixedRegistry("prefix.") - err := r.Register("foo", NewCounter()) - c := NewCounter() - Register("bar", c) - if err != nil { - t.Fatal(err.Error()) - } - - i := 0 - r.Each(func(name string, m interface{}) { - i++ - if name != "prefix.foo" { - t.Fatal(name) - } - }) - if i != 1 { - t.Fatal(i) - } -} - -func TestPrefixedRegistryUnregister(t *testing.T) { - r := NewPrefixedRegistry("prefix.") - - _ = r.Register("foo", NewCounter()) - - i := 0 - r.Each(func(name string, m interface{}) { - i++ - if name != "prefix.foo" { - t.Fatal(name) - } - }) - if i != 1 { - t.Fatal(i) - } - - r.Unregister("foo") - - i = 0 - r.Each(func(name string, m interface{}) { - i++ - }) - - if i != 0 { - t.Fatal(i) - } -} - -func TestPrefixedRegistryGet(t *testing.T) { - pr := NewPrefixedRegistry("prefix.") - name := "foo" - pr.Register(name, NewCounter()) - - fooCounter := pr.Get(name) - if fooCounter == nil { - t.Fatal(name) - } -} - -func TestPrefixedChildRegistryGet(t *testing.T) { - r := NewRegistry() - pr := NewPrefixedChildRegistry(r, "prefix.") - name := "foo" - pr.Register(name, NewCounter()) - fooCounter := pr.Get(name) - if fooCounter == nil { - t.Fatal(name) - } -} - -func TestChildPrefixedRegistryRegister(t *testing.T) { - r := NewPrefixedChildRegistry(DefaultRegistry, "prefix.") - err := r.Register("foo", NewCounter()) - c := NewCounter() - Register("bar", c) - if err != nil { - t.Fatal(err.Error()) - } - - i := 0 - r.Each(func(name string, m interface{}) { - i++ - if name != "prefix.foo" { - t.Fatal(name) - } - }) - if i != 1 { - t.Fatal(i) - } -} - -func TestChildPrefixedRegistryOfChildRegister(t *testing.T) { - r := NewPrefixedChildRegistry(NewRegistry(), "prefix.") - r2 := NewPrefixedChildRegistry(r, "prefix2.") - err := r.Register("foo2", NewCounter()) - if err != nil { - t.Fatal(err.Error()) - } - err = r2.Register("baz", NewCounter()) - if err != nil { - t.Fatal(err.Error()) - } - c := NewCounter() - Register("bars", c) - - i := 0 - r2.Each(func(name string, m interface{}) { - i++ - if name != "prefix.prefix2.baz" { - t.Fatal(name) - } - }) - if i != 1 { - t.Fatal(i) - } -} - -func TestWalkRegistries(t *testing.T) { - r := NewPrefixedChildRegistry(NewRegistry(), "prefix.") - r2 := NewPrefixedChildRegistry(r, "prefix2.") - err := r.Register("foo2", NewCounter()) - if err != nil { - t.Fatal(err.Error()) - } - err = r2.Register("baz", NewCounter()) - if err != nil { - t.Fatal(err.Error()) - } - c := NewCounter() - Register("bars", c) - - _, prefix := findPrefix(r2, "") - if prefix != "prefix.prefix2." { - t.Fatal(prefix) - } -} diff --git a/metrics/resetting_sample.go b/metrics/resetting_sample.go deleted file mode 100644 index c38ffcd3ec..0000000000 --- a/metrics/resetting_sample.go +++ /dev/null @@ -1,24 +0,0 @@ -package metrics - -// ResettingSample converts an ordinary sample into one that resets whenever its -// snapshot is retrieved. This will break for multi-monitor systems, but when only -// a single metric is being pushed out, this ensure that low-frequency events don't -// skew th charts indefinitely. -func ResettingSample(sample Sample) Sample { - return &resettingSample{ - Sample: sample, - } -} - -// resettingSample is a simple wrapper around a sample that resets it upon the -// snapshot retrieval. -type resettingSample struct { - Sample -} - -// Snapshot returns a read-only copy of the sample with the original reset. -func (rs *resettingSample) Snapshot() SampleSnapshot { - s := rs.Sample.Snapshot() - rs.Sample.Clear() - return s -} diff --git a/metrics/resetting_timer.go b/metrics/resetting_timer.go deleted file mode 100644 index 6802e3fcea..0000000000 --- a/metrics/resetting_timer.go +++ /dev/null @@ -1,171 +0,0 @@ -package metrics - -import ( - "sync" - "time" -) - -// Initial slice capacity for the values stored in a ResettingTimer -const InitialResettingTimerSliceCap = 10 - -type ResettingTimerSnapshot interface { - Count() int - Mean() float64 - Max() int64 - Min() int64 - Percentiles([]float64) []float64 -} - -// ResettingTimer is used for storing aggregated values for timers, which are reset on every flush interval. -type ResettingTimer interface { - Snapshot() ResettingTimerSnapshot - Time(func()) - Update(time.Duration) - UpdateSince(time.Time) -} - -// GetOrRegisterResettingTimer returns an existing ResettingTimer or constructs and registers a -// new StandardResettingTimer. -func GetOrRegisterResettingTimer(name string, r Registry) ResettingTimer { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, NewResettingTimer).(ResettingTimer) -} - -// NewRegisteredResettingTimer constructs and registers a new StandardResettingTimer. -func NewRegisteredResettingTimer(name string, r Registry) ResettingTimer { - c := NewResettingTimer() - if nil == r { - r = DefaultRegistry - } - r.Register(name, c) - return c -} - -// NewResettingTimer constructs a new StandardResettingTimer -func NewResettingTimer() ResettingTimer { - if !Enabled { - return NilResettingTimer{} - } - return &StandardResettingTimer{ - values: make([]int64, 0, InitialResettingTimerSliceCap), - } -} - -// NilResettingTimer is a no-op ResettingTimer. -type NilResettingTimer struct{} - -func (NilResettingTimer) Values() []int64 { return nil } -func (n NilResettingTimer) Snapshot() ResettingTimerSnapshot { return n } -func (NilResettingTimer) Time(f func()) { f() } -func (NilResettingTimer) Update(time.Duration) {} -func (NilResettingTimer) Percentiles([]float64) []float64 { return nil } -func (NilResettingTimer) Mean() float64 { return 0.0 } -func (NilResettingTimer) Max() int64 { return 0 } -func (NilResettingTimer) Min() int64 { return 0 } -func (NilResettingTimer) UpdateSince(time.Time) {} -func (NilResettingTimer) Count() int { return 0 } - -// StandardResettingTimer is the standard implementation of a ResettingTimer. -// and Meter. -type StandardResettingTimer struct { - values []int64 - sum int64 // sum is a running count of the total sum, used later to calculate mean - - mutex sync.Mutex -} - -// Snapshot resets the timer and returns a read-only copy of its contents. -func (t *StandardResettingTimer) Snapshot() ResettingTimerSnapshot { - t.mutex.Lock() - defer t.mutex.Unlock() - snapshot := &resettingTimerSnapshot{} - if len(t.values) > 0 { - snapshot.mean = float64(t.sum) / float64(len(t.values)) - snapshot.values = t.values - t.values = make([]int64, 0, InitialResettingTimerSliceCap) - } - t.sum = 0 - return snapshot -} - -// Record the duration of the execution of the given function. -func (t *StandardResettingTimer) Time(f func()) { - ts := time.Now() - f() - t.Update(time.Since(ts)) -} - -// Record the duration of an event. -func (t *StandardResettingTimer) Update(d time.Duration) { - t.mutex.Lock() - defer t.mutex.Unlock() - t.values = append(t.values, int64(d)) - t.sum += int64(d) -} - -// Record the duration of an event that started at a time and ends now. -func (t *StandardResettingTimer) UpdateSince(ts time.Time) { - t.Update(time.Since(ts)) -} - -// resettingTimerSnapshot is a point-in-time copy of another ResettingTimer. -type resettingTimerSnapshot struct { - values []int64 - mean float64 - max int64 - min int64 - thresholdBoundaries []float64 - calculated bool -} - -// Count return the length of the values from snapshot. -func (t *resettingTimerSnapshot) Count() int { - return len(t.values) -} - -// Percentiles returns the boundaries for the input percentiles. -// note: this method is not thread safe -func (t *resettingTimerSnapshot) Percentiles(percentiles []float64) []float64 { - t.calc(percentiles) - return t.thresholdBoundaries -} - -// Mean returns the mean of the snapshotted values -// note: this method is not thread safe -func (t *resettingTimerSnapshot) Mean() float64 { - if !t.calculated { - t.calc(nil) - } - - return t.mean -} - -// Max returns the max of the snapshotted values -// note: this method is not thread safe -func (t *resettingTimerSnapshot) Max() int64 { - if !t.calculated { - t.calc(nil) - } - return t.max -} - -// Min returns the min of the snapshotted values -// note: this method is not thread safe -func (t *resettingTimerSnapshot) Min() int64 { - if !t.calculated { - t.calc(nil) - } - return t.min -} - -func (t *resettingTimerSnapshot) calc(percentiles []float64) { - scores := CalculatePercentiles(t.values, percentiles) - t.thresholdBoundaries = scores - if len(t.values) == 0 { - return - } - t.min = t.values[0] - t.max = t.values[len(t.values)-1] -} diff --git a/metrics/resetting_timer_test.go b/metrics/resetting_timer_test.go deleted file mode 100644 index 4571fc8eb0..0000000000 --- a/metrics/resetting_timer_test.go +++ /dev/null @@ -1,197 +0,0 @@ -package metrics - -import ( - "testing" - "time" -) - -func TestResettingTimer(t *testing.T) { - tests := []struct { - values []int64 - start int - end int - wantP50 float64 - wantP95 float64 - wantP99 float64 - wantMean float64 - wantMin int64 - wantMax int64 - }{ - { - values: []int64{}, - start: 1, - end: 11, - wantP50: 5.5, wantP95: 10, wantP99: 10, - wantMin: 1, wantMax: 10, wantMean: 5.5, - }, - { - values: []int64{}, - start: 1, - end: 101, - wantP50: 50.5, wantP95: 95.94999999999999, wantP99: 99.99, - wantMin: 1, wantMax: 100, wantMean: 50.5, - }, - { - values: []int64{1}, - start: 0, - end: 0, - wantP50: 1, wantP95: 1, wantP99: 1, - wantMin: 1, wantMax: 1, wantMean: 1, - }, - { - values: []int64{0}, - start: 0, - end: 0, - wantP50: 0, wantP95: 0, wantP99: 0, - wantMin: 0, wantMax: 0, wantMean: 0, - }, - { - values: []int64{}, - start: 0, - end: 0, - wantP50: 0, wantP95: 0, wantP99: 0, - wantMin: 0, wantMax: 0, wantMean: 0, - }, - { - values: []int64{1, 10}, - start: 0, - end: 0, - wantP50: 5.5, wantP95: 10, wantP99: 10, - wantMin: 1, wantMax: 10, wantMean: 5.5, - }, - } - for i, tt := range tests { - timer := NewResettingTimer() - - for i := tt.start; i < tt.end; i++ { - tt.values = append(tt.values, int64(i)) - } - - for _, v := range tt.values { - timer.Update(time.Duration(v)) - } - snap := timer.Snapshot() - - ps := snap.Percentiles([]float64{0.50, 0.95, 0.99}) - - if have, want := snap.Min(), tt.wantMin; have != want { - t.Fatalf("%d: min: have %d, want %d", i, have, want) - } - if have, want := snap.Max(), tt.wantMax; have != want { - t.Fatalf("%d: max: have %d, want %d", i, have, want) - } - if have, want := snap.Mean(), tt.wantMean; have != want { - t.Fatalf("%d: mean: have %v, want %v", i, have, want) - } - if have, want := ps[0], tt.wantP50; have != want { - t.Errorf("%d: p50: have %v, want %v", i, have, want) - } - if have, want := ps[1], tt.wantP95; have != want { - t.Errorf("%d: p95: have %v, want %v", i, have, want) - } - if have, want := ps[2], tt.wantP99; have != want { - t.Errorf("%d: p99: have %v, want %v", i, have, want) - } - } -} - -func TestResettingTimerWithFivePercentiles(t *testing.T) { - tests := []struct { - values []int64 - start int - end int - wantP05 float64 - wantP20 float64 - wantP50 float64 - wantP95 float64 - wantP99 float64 - wantMean float64 - wantMin int64 - wantMax int64 - }{ - { - values: []int64{}, - start: 1, - end: 11, - wantP05: 1, wantP20: 2.2, wantP50: 5.5, wantP95: 10, wantP99: 10, - wantMin: 1, wantMax: 10, wantMean: 5.5, - }, - { - values: []int64{}, - start: 1, - end: 101, - wantP05: 5.050000000000001, wantP20: 20.200000000000003, wantP50: 50.5, wantP95: 95.94999999999999, wantP99: 99.99, - wantMin: 1, wantMax: 100, wantMean: 50.5, - }, - { - values: []int64{1}, - start: 0, - end: 0, - wantP05: 1, wantP20: 1, wantP50: 1, wantP95: 1, wantP99: 1, - wantMin: 1, wantMax: 1, wantMean: 1, - }, - { - values: []int64{0}, - start: 0, - end: 0, - wantP05: 0, wantP20: 0, wantP50: 0, wantP95: 0, wantP99: 0, - wantMin: 0, wantMax: 0, wantMean: 0, - }, - { - values: []int64{}, - start: 0, - end: 0, - wantP05: 0, wantP20: 0, wantP50: 0, wantP95: 0, wantP99: 0, - wantMin: 0, wantMax: 0, wantMean: 0, - }, - { - values: []int64{1, 10}, - start: 0, - end: 0, - wantP05: 1, wantP20: 1, wantP50: 5.5, wantP95: 10, wantP99: 10, - wantMin: 1, wantMax: 10, wantMean: 5.5, - }, - } - for ind, tt := range tests { - timer := NewResettingTimer() - - for i := tt.start; i < tt.end; i++ { - tt.values = append(tt.values, int64(i)) - } - - for _, v := range tt.values { - timer.Update(time.Duration(v)) - } - - snap := timer.Snapshot() - - ps := snap.Percentiles([]float64{0.05, 0.20, 0.50, 0.95, 0.99}) - - if tt.wantMin != snap.Min() { - t.Errorf("%d: min: got %d, want %d", ind, snap.Min(), tt.wantMin) - } - - if tt.wantMax != snap.Max() { - t.Errorf("%d: max: got %d, want %d", ind, snap.Max(), tt.wantMax) - } - - if tt.wantMean != snap.Mean() { - t.Errorf("%d: mean: got %.2f, want %.2f", ind, snap.Mean(), tt.wantMean) - } - if tt.wantP05 != ps[0] { - t.Errorf("%d: p05: got %v, want %v", ind, ps[0], tt.wantP05) - } - if tt.wantP20 != ps[1] { - t.Errorf("%d: p20: got %v, want %v", ind, ps[1], tt.wantP20) - } - if tt.wantP50 != ps[2] { - t.Errorf("%d: p50: got %v, want %v", ind, ps[2], tt.wantP50) - } - if tt.wantP95 != ps[3] { - t.Errorf("%d: p95: got %v, want %v", ind, ps[3], tt.wantP95) - } - if tt.wantP99 != ps[4] { - t.Errorf("%d: p99: got %v, want %v", ind, ps[4], tt.wantP99) - } - } -} diff --git a/metrics/sample.go b/metrics/sample.go deleted file mode 100644 index bb81e105cf..0000000000 --- a/metrics/sample.go +++ /dev/null @@ -1,446 +0,0 @@ -package metrics - -import ( - "math" - "math/rand" - "sync" - "time" - - "golang.org/x/exp/slices" -) - -const rescaleThreshold = time.Hour - -type SampleSnapshot interface { - Count() int64 - Max() int64 - Mean() float64 - Min() int64 - Percentile(float64) float64 - Percentiles([]float64) []float64 - Size() int - StdDev() float64 - Sum() int64 - Variance() float64 -} - -// Samples maintain a statistically-significant selection of values from -// a stream. -type Sample interface { - Snapshot() SampleSnapshot - Clear() - Update(int64) -} - -// ExpDecaySample is an exponentially-decaying sample using a forward-decaying -// priority reservoir. See Cormode et al's "Forward Decay: A Practical Time -// Decay Model for Streaming Systems". -// -// -type ExpDecaySample struct { - alpha float64 - count int64 - mutex sync.Mutex - reservoirSize int - t0, t1 time.Time - values *expDecaySampleHeap - rand *rand.Rand -} - -// NewExpDecaySample constructs a new exponentially-decaying sample with the -// given reservoir size and alpha. -func NewExpDecaySample(reservoirSize int, alpha float64) Sample { - if !Enabled { - return NilSample{} - } - s := &ExpDecaySample{ - alpha: alpha, - reservoirSize: reservoirSize, - t0: time.Now(), - values: newExpDecaySampleHeap(reservoirSize), - } - s.t1 = s.t0.Add(rescaleThreshold) - return s -} - -// SetRand sets the random source (useful in tests) -func (s *ExpDecaySample) SetRand(prng *rand.Rand) Sample { - s.rand = prng - return s -} - -// Clear clears all samples. -func (s *ExpDecaySample) Clear() { - s.mutex.Lock() - defer s.mutex.Unlock() - s.count = 0 - s.t0 = time.Now() - s.t1 = s.t0.Add(rescaleThreshold) - s.values.Clear() -} - -// Snapshot returns a read-only copy of the sample. -func (s *ExpDecaySample) Snapshot() SampleSnapshot { - s.mutex.Lock() - defer s.mutex.Unlock() - var ( - samples = s.values.Values() - values = make([]int64, len(samples)) - max int64 = math.MinInt64 - min int64 = math.MaxInt64 - sum int64 - ) - for i, item := range samples { - v := item.v - values[i] = v - sum += v - if v > max { - max = v - } - if v < min { - min = v - } - } - return newSampleSnapshotPrecalculated(s.count, values, min, max, sum) -} - -// Update samples a new value. -func (s *ExpDecaySample) Update(v int64) { - s.update(time.Now(), v) -} - -// update samples a new value at a particular timestamp. This is a method all -// its own to facilitate testing. -func (s *ExpDecaySample) update(t time.Time, v int64) { - s.mutex.Lock() - defer s.mutex.Unlock() - s.count++ - if s.values.Size() == s.reservoirSize { - s.values.Pop() - } - var f64 float64 - if s.rand != nil { - f64 = s.rand.Float64() - } else { - f64 = rand.Float64() - } - s.values.Push(expDecaySample{ - k: math.Exp(t.Sub(s.t0).Seconds()*s.alpha) / f64, - v: v, - }) - if t.After(s.t1) { - values := s.values.Values() - t0 := s.t0 - s.values.Clear() - s.t0 = t - s.t1 = s.t0.Add(rescaleThreshold) - for _, v := range values { - v.k = v.k * math.Exp(-s.alpha*s.t0.Sub(t0).Seconds()) - s.values.Push(v) - } - } -} - -// NilSample is a no-op Sample. -type NilSample struct{} - -func (NilSample) Clear() {} -func (NilSample) Snapshot() SampleSnapshot { return (*emptySnapshot)(nil) } -func (NilSample) Update(v int64) {} - -// SamplePercentile returns an arbitrary percentile of the slice of int64. -func SamplePercentile(values []int64, p float64) float64 { - return CalculatePercentiles(values, []float64{p})[0] -} - -// CalculatePercentiles returns a slice of arbitrary percentiles of the slice of -// int64. This method returns interpolated results, so e.g if there are only two -// values, [0, 10], a 50% percentile will land between them. -// -// Note: As a side-effect, this method will also sort the slice of values. -// Note2: The input format for percentiles is NOT percent! To express 50%, use 0.5, not 50. -func CalculatePercentiles(values []int64, ps []float64) []float64 { - scores := make([]float64, len(ps)) - size := len(values) - if size == 0 { - return scores - } - slices.Sort(values) - for i, p := range ps { - pos := p * float64(size+1) - - if pos < 1.0 { - scores[i] = float64(values[0]) - } else if pos >= float64(size) { - scores[i] = float64(values[size-1]) - } else { - lower := float64(values[int(pos)-1]) - upper := float64(values[int(pos)]) - scores[i] = lower + (pos-math.Floor(pos))*(upper-lower) - } - } - return scores -} - -// sampleSnapshot is a read-only copy of another Sample. -type sampleSnapshot struct { - count int64 - values []int64 - - max int64 - min int64 - mean float64 - sum int64 - variance float64 -} - -// newSampleSnapshotPrecalculated creates a read-only sampleSnapShot, using -// precalculated sums to avoid iterating the values -func newSampleSnapshotPrecalculated(count int64, values []int64, min, max, sum int64) *sampleSnapshot { - if len(values) == 0 { - return &sampleSnapshot{ - count: count, - values: values, - } - } - return &sampleSnapshot{ - count: count, - values: values, - max: max, - min: min, - mean: float64(sum) / float64(len(values)), - sum: sum, - } -} - -// newSampleSnapshot creates a read-only sampleSnapShot, and calculates some -// numbers. -func newSampleSnapshot(count int64, values []int64) *sampleSnapshot { - var ( - max int64 = math.MinInt64 - min int64 = math.MaxInt64 - sum int64 - ) - for _, v := range values { - sum += v - if v > max { - max = v - } - if v < min { - min = v - } - } - return newSampleSnapshotPrecalculated(count, values, min, max, sum) -} - -// Count returns the count of inputs at the time the snapshot was taken. -func (s *sampleSnapshot) Count() int64 { return s.count } - -// Max returns the maximal value at the time the snapshot was taken. -func (s *sampleSnapshot) Max() int64 { return s.max } - -// Mean returns the mean value at the time the snapshot was taken. -func (s *sampleSnapshot) Mean() float64 { return s.mean } - -// Min returns the minimal value at the time the snapshot was taken. -func (s *sampleSnapshot) Min() int64 { return s.min } - -// Percentile returns an arbitrary percentile of values at the time the -// snapshot was taken. -func (s *sampleSnapshot) Percentile(p float64) float64 { - return SamplePercentile(s.values, p) -} - -// Percentiles returns a slice of arbitrary percentiles of values at the time -// the snapshot was taken. -func (s *sampleSnapshot) Percentiles(ps []float64) []float64 { - return CalculatePercentiles(s.values, ps) -} - -// Size returns the size of the sample at the time the snapshot was taken. -func (s *sampleSnapshot) Size() int { return len(s.values) } - -// Snapshot returns the snapshot. -func (s *sampleSnapshot) Snapshot() SampleSnapshot { return s } - -// StdDev returns the standard deviation of values at the time the snapshot was -// taken. -func (s *sampleSnapshot) StdDev() float64 { - if s.variance == 0.0 { - s.variance = SampleVariance(s.mean, s.values) - } - return math.Sqrt(s.variance) -} - -// Sum returns the sum of values at the time the snapshot was taken. -func (s *sampleSnapshot) Sum() int64 { return s.sum } - -// Values returns a copy of the values in the sample. -func (s *sampleSnapshot) Values() []int64 { - values := make([]int64, len(s.values)) - copy(values, s.values) - return values -} - -// Variance returns the variance of values at the time the snapshot was taken. -func (s *sampleSnapshot) Variance() float64 { - if s.variance == 0.0 { - s.variance = SampleVariance(s.mean, s.values) - } - return s.variance -} - -// SampleVariance returns the variance of the slice of int64. -func SampleVariance(mean float64, values []int64) float64 { - if len(values) == 0 { - return 0.0 - } - var sum float64 - for _, v := range values { - d := float64(v) - mean - sum += d * d - } - return sum / float64(len(values)) -} - -// A uniform sample using Vitter's Algorithm R. -// -// -type UniformSample struct { - count int64 - mutex sync.Mutex - reservoirSize int - values []int64 - rand *rand.Rand -} - -// NewUniformSample constructs a new uniform sample with the given reservoir -// size. -func NewUniformSample(reservoirSize int) Sample { - if !Enabled { - return NilSample{} - } - return &UniformSample{ - reservoirSize: reservoirSize, - values: make([]int64, 0, reservoirSize), - } -} - -// SetRand sets the random source (useful in tests) -func (s *UniformSample) SetRand(prng *rand.Rand) Sample { - s.rand = prng - return s -} - -// Clear clears all samples. -func (s *UniformSample) Clear() { - s.mutex.Lock() - defer s.mutex.Unlock() - s.count = 0 - s.values = make([]int64, 0, s.reservoirSize) -} - -// Snapshot returns a read-only copy of the sample. -func (s *UniformSample) Snapshot() SampleSnapshot { - s.mutex.Lock() - values := make([]int64, len(s.values)) - copy(values, s.values) - count := s.count - s.mutex.Unlock() - return newSampleSnapshot(count, values) -} - -// Update samples a new value. -func (s *UniformSample) Update(v int64) { - s.mutex.Lock() - defer s.mutex.Unlock() - s.count++ - if len(s.values) < s.reservoirSize { - s.values = append(s.values, v) - } else { - var r int64 - if s.rand != nil { - r = s.rand.Int63n(s.count) - } else { - r = rand.Int63n(s.count) - } - if r < int64(len(s.values)) { - s.values[int(r)] = v - } - } -} - -// expDecaySample represents an individual sample in a heap. -type expDecaySample struct { - k float64 - v int64 -} - -func newExpDecaySampleHeap(reservoirSize int) *expDecaySampleHeap { - return &expDecaySampleHeap{make([]expDecaySample, 0, reservoirSize)} -} - -// expDecaySampleHeap is a min-heap of expDecaySamples. -// The internal implementation is copied from the standard library's container/heap -type expDecaySampleHeap struct { - s []expDecaySample -} - -func (h *expDecaySampleHeap) Clear() { - h.s = h.s[:0] -} - -func (h *expDecaySampleHeap) Push(s expDecaySample) { - n := len(h.s) - h.s = h.s[0 : n+1] - h.s[n] = s - h.up(n) -} - -func (h *expDecaySampleHeap) Pop() expDecaySample { - n := len(h.s) - 1 - h.s[0], h.s[n] = h.s[n], h.s[0] - h.down(0, n) - - n = len(h.s) - s := h.s[n-1] - h.s = h.s[0 : n-1] - return s -} - -func (h *expDecaySampleHeap) Size() int { - return len(h.s) -} - -func (h *expDecaySampleHeap) Values() []expDecaySample { - return h.s -} - -func (h *expDecaySampleHeap) up(j int) { - for { - i := (j - 1) / 2 // parent - if i == j || !(h.s[j].k < h.s[i].k) { - break - } - h.s[i], h.s[j] = h.s[j], h.s[i] - j = i - } -} - -func (h *expDecaySampleHeap) down(i, n int) { - for { - j1 := 2*i + 1 - if j1 >= n || j1 < 0 { // j1 < 0 after int overflow - break - } - j := j1 // left child - if j2 := j1 + 1; j2 < n && !(h.s[j1].k < h.s[j2].k) { - j = j2 // = 2*i + 2 // right child - } - if !(h.s[j].k < h.s[i].k) { - break - } - h.s[i], h.s[j] = h.s[j], h.s[i] - i = j - } -} diff --git a/metrics/sample_test.go b/metrics/sample_test.go deleted file mode 100644 index 7967357055..0000000000 --- a/metrics/sample_test.go +++ /dev/null @@ -1,360 +0,0 @@ -package metrics - -import ( - "math" - "math/rand" - "runtime" - "testing" - "time" -) - -const epsilonPercentile = .00000000001 - -// Benchmark{Compute,Copy}{1000,1000000} demonstrate that, even for relatively -// expensive computations like Variance, the cost of copying the Sample, as -// approximated by a make and copy, is much greater than the cost of the -// computation for small samples and only slightly less for large samples. -func BenchmarkCompute1000(b *testing.B) { - s := make([]int64, 1000) - var sum int64 - for i := 0; i < len(s); i++ { - s[i] = int64(i) - sum += int64(i) - } - mean := float64(sum) / float64(len(s)) - b.ResetTimer() - for i := 0; i < b.N; i++ { - SampleVariance(mean, s) - } -} -func BenchmarkCompute1000000(b *testing.B) { - s := make([]int64, 1000000) - var sum int64 - for i := 0; i < len(s); i++ { - s[i] = int64(i) - sum += int64(i) - } - mean := float64(sum) / float64(len(s)) - b.ResetTimer() - for i := 0; i < b.N; i++ { - SampleVariance(mean, s) - } -} -func BenchmarkCopy1000(b *testing.B) { - s := make([]int64, 1000) - for i := 0; i < len(s); i++ { - s[i] = int64(i) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - sCopy := make([]int64, len(s)) - copy(sCopy, s) - } -} -func BenchmarkCopy1000000(b *testing.B) { - s := make([]int64, 1000000) - for i := 0; i < len(s); i++ { - s[i] = int64(i) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - sCopy := make([]int64, len(s)) - copy(sCopy, s) - } -} - -func BenchmarkExpDecaySample257(b *testing.B) { - benchmarkSample(b, NewExpDecaySample(257, 0.015)) -} - -func BenchmarkExpDecaySample514(b *testing.B) { - benchmarkSample(b, NewExpDecaySample(514, 0.015)) -} - -func BenchmarkExpDecaySample1028(b *testing.B) { - benchmarkSample(b, NewExpDecaySample(1028, 0.015)) -} - -func BenchmarkUniformSample257(b *testing.B) { - benchmarkSample(b, NewUniformSample(257)) -} - -func BenchmarkUniformSample514(b *testing.B) { - benchmarkSample(b, NewUniformSample(514)) -} - -func BenchmarkUniformSample1028(b *testing.B) { - benchmarkSample(b, NewUniformSample(1028)) -} - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -func TestExpDecaySample(t *testing.T) { - for _, tc := range []struct { - reservoirSize int - alpha float64 - updates int - }{ - {100, 0.99, 10}, - {1000, 0.01, 100}, - {100, 0.99, 1000}, - } { - sample := NewExpDecaySample(tc.reservoirSize, tc.alpha) - for i := 0; i < tc.updates; i++ { - sample.Update(int64(i)) - } - snap := sample.Snapshot() - if have, want := int(snap.Count()), tc.updates; have != want { - t.Errorf("have %d want %d", have, want) - } - if have, want := snap.Size(), min(tc.updates, tc.reservoirSize); have != want { - t.Errorf("have %d want %d", have, want) - } - values := snap.(*sampleSnapshot).values - if have, want := len(values), min(tc.updates, tc.reservoirSize); have != want { - t.Errorf("have %d want %d", have, want) - } - for _, v := range values { - if v > int64(tc.updates) || v < 0 { - t.Errorf("out of range [0, %d): %v", tc.updates, v) - } - } - } -} - -// This test makes sure that the sample's priority is not amplified by using -// nanosecond duration since start rather than second duration since start. -// The priority becomes +Inf quickly after starting if this is done, -// effectively freezing the set of samples until a rescale step happens. -func TestExpDecaySampleNanosecondRegression(t *testing.T) { - sw := NewExpDecaySample(100, 0.99) - for i := 0; i < 100; i++ { - sw.Update(10) - } - time.Sleep(1 * time.Millisecond) - for i := 0; i < 100; i++ { - sw.Update(20) - } - s := sw.Snapshot() - v := s.(*sampleSnapshot).values - avg := float64(0) - for i := 0; i < len(v); i++ { - avg += float64(v[i]) - } - avg /= float64(len(v)) - if avg > 16 || avg < 14 { - t.Errorf("out of range [14, 16]: %v\n", avg) - } -} - -func TestExpDecaySampleRescale(t *testing.T) { - s := NewExpDecaySample(2, 0.001).(*ExpDecaySample) - s.update(time.Now(), 1) - s.update(time.Now().Add(time.Hour+time.Microsecond), 1) - for _, v := range s.values.Values() { - if v.k == 0.0 { - t.Fatal("v.k == 0.0") - } - } -} - -func TestExpDecaySampleSnapshot(t *testing.T) { - now := time.Now() - s := NewExpDecaySample(100, 0.99).(*ExpDecaySample).SetRand(rand.New(rand.NewSource(1))) - for i := 1; i <= 10000; i++ { - s.(*ExpDecaySample).update(now.Add(time.Duration(i)), int64(i)) - } - snapshot := s.Snapshot() - s.Update(1) - testExpDecaySampleStatistics(t, snapshot) -} - -func TestExpDecaySampleStatistics(t *testing.T) { - now := time.Now() - s := NewExpDecaySample(100, 0.99).(*ExpDecaySample).SetRand(rand.New(rand.NewSource(1))) - for i := 1; i <= 10000; i++ { - s.(*ExpDecaySample).update(now.Add(time.Duration(i)), int64(i)) - } - testExpDecaySampleStatistics(t, s.Snapshot()) -} - -func TestUniformSample(t *testing.T) { - sw := NewUniformSample(100) - for i := 0; i < 1000; i++ { - sw.Update(int64(i)) - } - s := sw.Snapshot() - if size := s.Count(); size != 1000 { - t.Errorf("s.Count(): 1000 != %v\n", size) - } - if size := s.Size(); size != 100 { - t.Errorf("s.Size(): 100 != %v\n", size) - } - values := s.(*sampleSnapshot).values - - if l := len(values); l != 100 { - t.Errorf("len(s.Values()): 100 != %v\n", l) - } - for _, v := range values { - if v > 1000 || v < 0 { - t.Errorf("out of range [0, 100): %v\n", v) - } - } -} - -func TestUniformSampleIncludesTail(t *testing.T) { - sw := NewUniformSample(100) - max := 100 - for i := 0; i < max; i++ { - sw.Update(int64(i)) - } - s := sw.Snapshot() - v := s.(*sampleSnapshot).values - sum := 0 - exp := (max - 1) * max / 2 - for i := 0; i < len(v); i++ { - sum += int(v[i]) - } - if exp != sum { - t.Errorf("sum: %v != %v\n", exp, sum) - } -} - -func TestUniformSampleSnapshot(t *testing.T) { - s := NewUniformSample(100).(*UniformSample).SetRand(rand.New(rand.NewSource(1))) - for i := 1; i <= 10000; i++ { - s.Update(int64(i)) - } - snapshot := s.Snapshot() - s.Update(1) - testUniformSampleStatistics(t, snapshot) -} - -func TestUniformSampleStatistics(t *testing.T) { - s := NewUniformSample(100).(*UniformSample).SetRand(rand.New(rand.NewSource(1))) - for i := 1; i <= 10000; i++ { - s.Update(int64(i)) - } - testUniformSampleStatistics(t, s.Snapshot()) -} - -func benchmarkSample(b *testing.B, s Sample) { - var memStats runtime.MemStats - runtime.ReadMemStats(&memStats) - pauseTotalNs := memStats.PauseTotalNs - b.ResetTimer() - for i := 0; i < b.N; i++ { - s.Update(1) - } - b.StopTimer() - runtime.GC() - runtime.ReadMemStats(&memStats) - b.Logf("GC cost: %d ns/op", int(memStats.PauseTotalNs-pauseTotalNs)/b.N) -} - -func testExpDecaySampleStatistics(t *testing.T, s SampleSnapshot) { - if count := s.Count(); count != 10000 { - t.Errorf("s.Count(): 10000 != %v\n", count) - } - if min := s.Min(); min != 107 { - t.Errorf("s.Min(): 107 != %v\n", min) - } - if max := s.Max(); max != 10000 { - t.Errorf("s.Max(): 10000 != %v\n", max) - } - if mean := s.Mean(); mean != 4965.98 { - t.Errorf("s.Mean(): 4965.98 != %v\n", mean) - } - if stdDev := s.StdDev(); stdDev != 2959.825156930727 { - t.Errorf("s.StdDev(): 2959.825156930727 != %v\n", stdDev) - } - ps := s.Percentiles([]float64{0.5, 0.75, 0.99}) - if ps[0] != 4615 { - t.Errorf("median: 4615 != %v\n", ps[0]) - } - if ps[1] != 7672 { - t.Errorf("75th percentile: 7672 != %v\n", ps[1]) - } - if ps[2] != 9998.99 { - t.Errorf("99th percentile: 9998.99 != %v\n", ps[2]) - } -} - -func testUniformSampleStatistics(t *testing.T, s SampleSnapshot) { - if count := s.Count(); count != 10000 { - t.Errorf("s.Count(): 10000 != %v\n", count) - } - if min := s.Min(); min != 37 { - t.Errorf("s.Min(): 37 != %v\n", min) - } - if max := s.Max(); max != 9989 { - t.Errorf("s.Max(): 9989 != %v\n", max) - } - if mean := s.Mean(); mean != 4748.14 { - t.Errorf("s.Mean(): 4748.14 != %v\n", mean) - } - if stdDev := s.StdDev(); stdDev != 2826.684117548333 { - t.Errorf("s.StdDev(): 2826.684117548333 != %v\n", stdDev) - } - ps := s.Percentiles([]float64{0.5, 0.75, 0.99}) - if ps[0] != 4599 { - t.Errorf("median: 4599 != %v\n", ps[0]) - } - if ps[1] != 7380.5 { - t.Errorf("75th percentile: 7380.5 != %v\n", ps[1]) - } - if math.Abs(9986.429999999998-ps[2]) > epsilonPercentile { - t.Errorf("99th percentile: 9986.429999999998 != %v\n", ps[2]) - } -} - -// TestUniformSampleConcurrentUpdateCount would expose data race problems with -// concurrent Update and Count calls on Sample when test is called with -race -// argument -func TestUniformSampleConcurrentUpdateCount(t *testing.T) { - if testing.Short() { - t.Skip("skipping in short mode") - } - s := NewUniformSample(100) - for i := 0; i < 100; i++ { - s.Update(int64(i)) - } - quit := make(chan struct{}) - go func() { - t := time.NewTicker(10 * time.Millisecond) - defer t.Stop() - for { - select { - case <-t.C: - s.Update(rand.Int63()) - case <-quit: - t.Stop() - return - } - } - }() - for i := 0; i < 1000; i++ { - s.Snapshot().Count() - time.Sleep(5 * time.Millisecond) - } - quit <- struct{}{} -} - -func BenchmarkCalculatePercentiles(b *testing.B) { - pss := []float64{0.5, 0.75, 0.95, 0.99, 0.999, 0.9999} - var vals []int64 - for i := 0; i < 1000; i++ { - vals = append(vals, int64(rand.Int31())) - } - v := make([]int64, len(vals)) - b.ResetTimer() - for i := 0; i < b.N; i++ { - copy(v, vals) - _ = CalculatePercentiles(v, pss) - } -} diff --git a/metrics/syslog.go b/metrics/syslog.go deleted file mode 100644 index fd856d6973..0000000000 --- a/metrics/syslog.go +++ /dev/null @@ -1,83 +0,0 @@ -//go:build !windows -// +build !windows - -package metrics - -import ( - "fmt" - "log/syslog" - "time" -) - -// Output each metric in the given registry to syslog periodically using -// the given syslogger. -func Syslog(r Registry, d time.Duration, w *syslog.Writer) { - for range time.Tick(d) { - r.Each(func(name string, i interface{}) { - switch metric := i.(type) { - case Counter: - w.Info(fmt.Sprintf("counter %s: count: %d", name, metric.Snapshot().Count())) - case CounterFloat64: - w.Info(fmt.Sprintf("counter %s: count: %f", name, metric.Snapshot().Count())) - case Gauge: - w.Info(fmt.Sprintf("gauge %s: value: %d", name, metric.Snapshot().Value())) - case GaugeFloat64: - w.Info(fmt.Sprintf("gauge %s: value: %f", name, metric.Snapshot().Value())) - case GaugeInfo: - w.Info(fmt.Sprintf("gauge %s: value: %s", name, metric.Snapshot().Value())) - case Healthcheck: - metric.Check() - w.Info(fmt.Sprintf("healthcheck %s: error: %v", name, metric.Error())) - case Histogram: - h := metric.Snapshot() - ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) - w.Info(fmt.Sprintf( - "histogram %s: count: %d min: %d max: %d mean: %.2f stddev: %.2f median: %.2f 75%%: %.2f 95%%: %.2f 99%%: %.2f 99.9%%: %.2f", - name, - h.Count(), - h.Min(), - h.Max(), - h.Mean(), - h.StdDev(), - ps[0], - ps[1], - ps[2], - ps[3], - ps[4], - )) - case Meter: - m := metric.Snapshot() - w.Info(fmt.Sprintf( - "meter %s: count: %d 1-min: %.2f 5-min: %.2f 15-min: %.2f mean: %.2f", - name, - m.Count(), - m.Rate1(), - m.Rate5(), - m.Rate15(), - m.RateMean(), - )) - case Timer: - t := metric.Snapshot() - ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) - w.Info(fmt.Sprintf( - "timer %s: count: %d min: %d max: %d mean: %.2f stddev: %.2f median: %.2f 75%%: %.2f 95%%: %.2f 99%%: %.2f 99.9%%: %.2f 1-min: %.2f 5-min: %.2f 15-min: %.2f mean-rate: %.2f", - name, - t.Count(), - t.Min(), - t.Max(), - t.Mean(), - t.StdDev(), - ps[0], - ps[1], - ps[2], - ps[3], - ps[4], - t.Rate1(), - t.Rate5(), - t.Rate15(), - t.RateMean(), - )) - } - }) - } -} diff --git a/metrics/testdata/opentsb.want b/metrics/testdata/opentsb.want deleted file mode 100644 index 43fe1b2ac2..0000000000 --- a/metrics/testdata/opentsb.want +++ /dev/null @@ -1,23 +0,0 @@ -put pre.elite.count 978307200 1337 host=hal9000 -put pre.elite.one-minute 978307200 0.00 host=hal9000 -put pre.elite.five-minute 978307200 0.00 host=hal9000 -put pre.elite.fifteen-minute 978307200 0.00 host=hal9000 -put pre.elite.mean 978307200 0.00 host=hal9000 -put pre.foo.value 978307200 {"chain_id":"5"} host=hal9000 -put pre.months.count 978307200 12 host=hal9000 -put pre.pi.value 978307200 3.140000 host=hal9000 -put pre.second.count 978307200 1 host=hal9000 -put pre.second.min 978307200 1000 host=hal9000 -put pre.second.max 978307200 1000 host=hal9000 -put pre.second.mean 978307200 1000.00 host=hal9000 -put pre.second.std-dev 978307200 0.00 host=hal9000 -put pre.second.50-percentile 978307200 1000.00 host=hal9000 -put pre.second.75-percentile 978307200 1000.00 host=hal9000 -put pre.second.95-percentile 978307200 1000.00 host=hal9000 -put pre.second.99-percentile 978307200 1000.00 host=hal9000 -put pre.second.999-percentile 978307200 1000.00 host=hal9000 -put pre.second.one-minute 978307200 0.00 host=hal9000 -put pre.second.five-minute 978307200 0.00 host=hal9000 -put pre.second.fifteen-minute 978307200 0.00 host=hal9000 -put pre.second.mean-rate 978307200 0.00 host=hal9000 -put pre.tau.count 978307200 1.570000 host=hal9000 diff --git a/metrics/timer.go b/metrics/timer.go deleted file mode 100644 index bb8def82fb..0000000000 --- a/metrics/timer.go +++ /dev/null @@ -1,182 +0,0 @@ -package metrics - -import ( - "sync" - "time" -) - -type TimerSnapshot interface { - HistogramSnapshot - MeterSnapshot -} - -// Timers capture the duration and rate of events. -type Timer interface { - Snapshot() TimerSnapshot - Stop() - Time(func()) - UpdateSince(time.Time) - Update(time.Duration) -} - -// GetOrRegisterTimer returns an existing Timer or constructs and registers a -// new StandardTimer. -// Be sure to unregister the meter from the registry once it is of no use to -// allow for garbage collection. -func GetOrRegisterTimer(name string, r Registry) Timer { - if nil == r { - r = DefaultRegistry - } - return r.GetOrRegister(name, NewTimer).(Timer) -} - -// NewCustomTimer constructs a new StandardTimer from a Histogram and a Meter. -// Be sure to call Stop() once the timer is of no use to allow for garbage collection. -func NewCustomTimer(h Histogram, m Meter) Timer { - if !Enabled { - return NilTimer{} - } - return &StandardTimer{ - histogram: h, - meter: m, - } -} - -// NewRegisteredTimer constructs and registers a new StandardTimer. -// Be sure to unregister the meter from the registry once it is of no use to -// allow for garbage collection. -func NewRegisteredTimer(name string, r Registry) Timer { - c := NewTimer() - if nil == r { - r = DefaultRegistry - } - r.Register(name, c) - return c -} - -// NewTimer constructs a new StandardTimer using an exponentially-decaying -// sample with the same reservoir size and alpha as UNIX load averages. -// Be sure to call Stop() once the timer is of no use to allow for garbage collection. -func NewTimer() Timer { - if !Enabled { - return NilTimer{} - } - return &StandardTimer{ - histogram: NewHistogram(NewExpDecaySample(1028, 0.015)), - meter: NewMeter(), - } -} - -// NilTimer is a no-op Timer. -type NilTimer struct{} - -func (NilTimer) Snapshot() TimerSnapshot { return (*emptySnapshot)(nil) } -func (NilTimer) Stop() {} -func (NilTimer) Time(f func()) { f() } -func (NilTimer) Update(time.Duration) {} -func (NilTimer) UpdateSince(time.Time) {} - -// StandardTimer is the standard implementation of a Timer and uses a Histogram -// and Meter. -type StandardTimer struct { - histogram Histogram - meter Meter - mutex sync.Mutex -} - -// Snapshot returns a read-only copy of the timer. -func (t *StandardTimer) Snapshot() TimerSnapshot { - t.mutex.Lock() - defer t.mutex.Unlock() - return &timerSnapshot{ - histogram: t.histogram.Snapshot(), - meter: t.meter.Snapshot(), - } -} - -// Stop stops the meter. -func (t *StandardTimer) Stop() { - t.meter.Stop() -} - -// Record the duration of the execution of the given function. -func (t *StandardTimer) Time(f func()) { - ts := time.Now() - f() - t.Update(time.Since(ts)) -} - -// Record the duration of an event, in nanoseconds. -func (t *StandardTimer) Update(d time.Duration) { - t.mutex.Lock() - defer t.mutex.Unlock() - t.histogram.Update(d.Nanoseconds()) - t.meter.Mark(1) -} - -// Record the duration of an event that started at a time and ends now. -// The record uses nanoseconds. -func (t *StandardTimer) UpdateSince(ts time.Time) { - t.Update(time.Since(ts)) -} - -// timerSnapshot is a read-only copy of another Timer. -type timerSnapshot struct { - histogram HistogramSnapshot - meter MeterSnapshot -} - -// Count returns the number of events recorded at the time the snapshot was -// taken. -func (t *timerSnapshot) Count() int64 { return t.histogram.Count() } - -// Max returns the maximum value at the time the snapshot was taken. -func (t *timerSnapshot) Max() int64 { return t.histogram.Max() } - -// Size returns the size of the sample at the time the snapshot was taken. -func (t *timerSnapshot) Size() int { return t.histogram.Size() } - -// Mean returns the mean value at the time the snapshot was taken. -func (t *timerSnapshot) Mean() float64 { return t.histogram.Mean() } - -// Min returns the minimum value at the time the snapshot was taken. -func (t *timerSnapshot) Min() int64 { return t.histogram.Min() } - -// Percentile returns an arbitrary percentile of sampled values at the time the -// snapshot was taken. -func (t *timerSnapshot) Percentile(p float64) float64 { - return t.histogram.Percentile(p) -} - -// Percentiles returns a slice of arbitrary percentiles of sampled values at -// the time the snapshot was taken. -func (t *timerSnapshot) Percentiles(ps []float64) []float64 { - return t.histogram.Percentiles(ps) -} - -// Rate1 returns the one-minute moving average rate of events per second at the -// time the snapshot was taken. -func (t *timerSnapshot) Rate1() float64 { return t.meter.Rate1() } - -// Rate5 returns the five-minute moving average rate of events per second at -// the time the snapshot was taken. -func (t *timerSnapshot) Rate5() float64 { return t.meter.Rate5() } - -// Rate15 returns the fifteen-minute moving average rate of events per second -// at the time the snapshot was taken. -func (t *timerSnapshot) Rate15() float64 { return t.meter.Rate15() } - -// RateMean returns the meter's mean rate of events per second at the time the -// snapshot was taken. -func (t *timerSnapshot) RateMean() float64 { return t.meter.RateMean() } - -// StdDev returns the standard deviation of the values at the time the snapshot -// was taken. -func (t *timerSnapshot) StdDev() float64 { return t.histogram.StdDev() } - -// Sum returns the sum at the time the snapshot was taken. -func (t *timerSnapshot) Sum() int64 { return t.histogram.Sum() } - -// Variance returns the variance of the values at the time the snapshot was -// taken. -func (t *timerSnapshot) Variance() float64 { return t.histogram.Variance() } diff --git a/metrics/timer_test.go b/metrics/timer_test.go deleted file mode 100644 index f10de16c9c..0000000000 --- a/metrics/timer_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package metrics - -import ( - "fmt" - "math" - "testing" - "time" -) - -func BenchmarkTimer(b *testing.B) { - tm := NewTimer() - b.ResetTimer() - for i := 0; i < b.N; i++ { - tm.Update(1) - } -} - -func TestGetOrRegisterTimer(t *testing.T) { - r := NewRegistry() - NewRegisteredTimer("foo", r).Update(47) - if tm := GetOrRegisterTimer("foo", r).Snapshot(); tm.Count() != 1 { - t.Fatal(tm) - } -} - -func TestTimerExtremes(t *testing.T) { - tm := NewTimer() - tm.Update(math.MaxInt64) - tm.Update(0) - if stdDev := tm.Snapshot().StdDev(); stdDev != 4.611686018427388e+18 { - t.Errorf("tm.StdDev(): 4.611686018427388e+18 != %v\n", stdDev) - } -} - -func TestTimerStop(t *testing.T) { - l := len(arbiter.meters) - tm := NewTimer() - if l+1 != len(arbiter.meters) { - t.Errorf("arbiter.meters: %d != %d\n", l+1, len(arbiter.meters)) - } - tm.Stop() - if l != len(arbiter.meters) { - t.Errorf("arbiter.meters: %d != %d\n", l, len(arbiter.meters)) - } -} - -func TestTimerFunc(t *testing.T) { - var ( - tm = NewTimer() - testStart = time.Now() - actualTime time.Duration - ) - tm.Time(func() { - time.Sleep(50 * time.Millisecond) - actualTime = time.Since(testStart) - }) - var ( - drift = time.Millisecond * 2 - measured = time.Duration(tm.Snapshot().Max()) - ceil = actualTime + drift - floor = actualTime - drift - ) - if measured > ceil || measured < floor { - t.Errorf("tm.Max(): %v > %v || %v > %v\n", measured, ceil, measured, floor) - } -} - -func TestTimerZero(t *testing.T) { - tm := NewTimer().Snapshot() - if count := tm.Count(); count != 0 { - t.Errorf("tm.Count(): 0 != %v\n", count) - } - if min := tm.Min(); min != 0 { - t.Errorf("tm.Min(): 0 != %v\n", min) - } - if max := tm.Max(); max != 0 { - t.Errorf("tm.Max(): 0 != %v\n", max) - } - if mean := tm.Mean(); mean != 0.0 { - t.Errorf("tm.Mean(): 0.0 != %v\n", mean) - } - if stdDev := tm.StdDev(); stdDev != 0.0 { - t.Errorf("tm.StdDev(): 0.0 != %v\n", stdDev) - } - ps := tm.Percentiles([]float64{0.5, 0.75, 0.99}) - if ps[0] != 0.0 { - t.Errorf("median: 0.0 != %v\n", ps[0]) - } - if ps[1] != 0.0 { - t.Errorf("75th percentile: 0.0 != %v\n", ps[1]) - } - if ps[2] != 0.0 { - t.Errorf("99th percentile: 0.0 != %v\n", ps[2]) - } - if rate1 := tm.Rate1(); rate1 != 0.0 { - t.Errorf("tm.Rate1(): 0.0 != %v\n", rate1) - } - if rate5 := tm.Rate5(); rate5 != 0.0 { - t.Errorf("tm.Rate5(): 0.0 != %v\n", rate5) - } - if rate15 := tm.Rate15(); rate15 != 0.0 { - t.Errorf("tm.Rate15(): 0.0 != %v\n", rate15) - } - if rateMean := tm.RateMean(); rateMean != 0.0 { - t.Errorf("tm.RateMean(): 0.0 != %v\n", rateMean) - } -} - -func ExampleGetOrRegisterTimer() { - m := "account.create.latency" - t := GetOrRegisterTimer(m, nil) - t.Update(47) - fmt.Println(t.Snapshot().Max()) // Output: 47 -} diff --git a/metrics/validate.sh b/metrics/validate.sh deleted file mode 100755 index 0d8ba28df3..0000000000 --- a/metrics/validate.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash - -set -e - -# check there are no formatting issues -GOFMT_LINES=$(gofmt -l . | wc -l | xargs) -test "$GOFMT_LINES" -eq 0 || echo "gofmt needs to be run, ${GOFMT_LINES} files have issues" - -# run the tests for the root package -go test -race . diff --git a/metrics/writer.go b/metrics/writer.go deleted file mode 100644 index 098da45c27..0000000000 --- a/metrics/writer.go +++ /dev/null @@ -1,100 +0,0 @@ -package metrics - -import ( - "fmt" - "io" - "strings" - "time" - - "golang.org/x/exp/slices" -) - -// Write sorts writes each metric in the given registry periodically to the -// given io.Writer. -func Write(r Registry, d time.Duration, w io.Writer) { - for range time.Tick(d) { - WriteOnce(r, w) - } -} - -// WriteOnce sorts and writes metrics in the given registry to the given -// io.Writer. -func WriteOnce(r Registry, w io.Writer) { - var namedMetrics []namedMetric - r.Each(func(name string, i interface{}) { - namedMetrics = append(namedMetrics, namedMetric{name, i}) - }) - slices.SortFunc(namedMetrics, namedMetric.cmp) - for _, namedMetric := range namedMetrics { - switch metric := namedMetric.m.(type) { - case Counter: - fmt.Fprintf(w, "counter %s\n", namedMetric.name) - fmt.Fprintf(w, " count: %9d\n", metric.Snapshot().Count()) - case CounterFloat64: - fmt.Fprintf(w, "counter %s\n", namedMetric.name) - fmt.Fprintf(w, " count: %f\n", metric.Snapshot().Count()) - case Gauge: - fmt.Fprintf(w, "gauge %s\n", namedMetric.name) - fmt.Fprintf(w, " value: %9d\n", metric.Snapshot().Value()) - case GaugeFloat64: - fmt.Fprintf(w, "gauge %s\n", namedMetric.name) - fmt.Fprintf(w, " value: %f\n", metric.Snapshot().Value()) - case GaugeInfo: - fmt.Fprintf(w, "gauge %s\n", namedMetric.name) - fmt.Fprintf(w, " value: %s\n", metric.Snapshot().Value().String()) - case Healthcheck: - metric.Check() - fmt.Fprintf(w, "healthcheck %s\n", namedMetric.name) - fmt.Fprintf(w, " error: %v\n", metric.Error()) - case Histogram: - h := metric.Snapshot() - ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) - fmt.Fprintf(w, "histogram %s\n", namedMetric.name) - fmt.Fprintf(w, " count: %9d\n", h.Count()) - fmt.Fprintf(w, " min: %9d\n", h.Min()) - fmt.Fprintf(w, " max: %9d\n", h.Max()) - fmt.Fprintf(w, " mean: %12.2f\n", h.Mean()) - fmt.Fprintf(w, " stddev: %12.2f\n", h.StdDev()) - fmt.Fprintf(w, " median: %12.2f\n", ps[0]) - fmt.Fprintf(w, " 75%%: %12.2f\n", ps[1]) - fmt.Fprintf(w, " 95%%: %12.2f\n", ps[2]) - fmt.Fprintf(w, " 99%%: %12.2f\n", ps[3]) - fmt.Fprintf(w, " 99.9%%: %12.2f\n", ps[4]) - case Meter: - m := metric.Snapshot() - fmt.Fprintf(w, "meter %s\n", namedMetric.name) - fmt.Fprintf(w, " count: %9d\n", m.Count()) - fmt.Fprintf(w, " 1-min rate: %12.2f\n", m.Rate1()) - fmt.Fprintf(w, " 5-min rate: %12.2f\n", m.Rate5()) - fmt.Fprintf(w, " 15-min rate: %12.2f\n", m.Rate15()) - fmt.Fprintf(w, " mean rate: %12.2f\n", m.RateMean()) - case Timer: - t := metric.Snapshot() - ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) - fmt.Fprintf(w, "timer %s\n", namedMetric.name) - fmt.Fprintf(w, " count: %9d\n", t.Count()) - fmt.Fprintf(w, " min: %9d\n", t.Min()) - fmt.Fprintf(w, " max: %9d\n", t.Max()) - fmt.Fprintf(w, " mean: %12.2f\n", t.Mean()) - fmt.Fprintf(w, " stddev: %12.2f\n", t.StdDev()) - fmt.Fprintf(w, " median: %12.2f\n", ps[0]) - fmt.Fprintf(w, " 75%%: %12.2f\n", ps[1]) - fmt.Fprintf(w, " 95%%: %12.2f\n", ps[2]) - fmt.Fprintf(w, " 99%%: %12.2f\n", ps[3]) - fmt.Fprintf(w, " 99.9%%: %12.2f\n", ps[4]) - fmt.Fprintf(w, " 1-min rate: %12.2f\n", t.Rate1()) - fmt.Fprintf(w, " 5-min rate: %12.2f\n", t.Rate5()) - fmt.Fprintf(w, " 15-min rate: %12.2f\n", t.Rate15()) - fmt.Fprintf(w, " mean rate: %12.2f\n", t.RateMean()) - } - } -} - -type namedMetric struct { - name string - m interface{} -} - -func (m namedMetric) cmp(other namedMetric) int { - return strings.Compare(m.name, other.name) -} diff --git a/metrics/writer_test.go b/metrics/writer_test.go deleted file mode 100644 index 8376bf8975..0000000000 --- a/metrics/writer_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package metrics - -import ( - "testing" - - "golang.org/x/exp/slices" -) - -func TestMetricsSorting(t *testing.T) { - var namedMetrics = []namedMetric{ - {name: "zzz"}, - {name: "bbb"}, - {name: "fff"}, - {name: "ggg"}, - } - - slices.SortFunc(namedMetrics, namedMetric.cmp) - for i, name := range []string{"bbb", "fff", "ggg", "zzz"} { - if namedMetrics[i].name != name { - t.Fail() - } - } -} diff --git a/peer/peer_tracker.go b/peer/peer_tracker.go index 8070005ca6..ca11a4faf6 100644 --- a/peer/peer_tracker.go +++ b/peer/peer_tracker.go @@ -15,7 +15,7 @@ import ( "github.com/ethereum/go-ethereum/log" - "github.com/ava-labs/coreth/metrics" + "github.com/ethereum/go-ethereum/metrics" ) const ( diff --git a/peer/stats/stats.go b/peer/stats/stats.go index 165537bae7..a23772540c 100644 --- a/peer/stats/stats.go +++ b/peer/stats/stats.go @@ -6,7 +6,7 @@ package stats import ( "time" - "github.com/ava-labs/coreth/metrics" + "github.com/ethereum/go-ethereum/metrics" ) // RequestHandlerStats provides the interface for metrics for app requests. diff --git a/plugin/evm/atomic/mempool.go b/plugin/evm/atomic/mempool.go index f74eacda7e..f84dcf1840 100644 --- a/plugin/evm/atomic/mempool.go +++ b/plugin/evm/atomic/mempool.go @@ -14,9 +14,9 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/prometheus/client_golang/prometheus" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/plugin/evm/config" "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" ) const ( diff --git a/plugin/evm/network_handler.go b/plugin/evm/network_handler.go index aa4b728ed5..6d9a282b7f 100644 --- a/plugin/evm/network_handler.go +++ b/plugin/evm/network_handler.go @@ -8,7 +8,6 @@ import ( "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/plugin/evm/message" syncHandlers "github.com/ava-labs/coreth/sync/handlers" syncStats "github.com/ava-labs/coreth/sync/handlers/stats" @@ -16,6 +15,7 @@ import ( "github.com/ava-labs/coreth/warp" warpHandlers "github.com/ava-labs/coreth/warp/handlers" "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/metrics" ) var _ message.RequestHandler = &networkHandler{} diff --git a/plugin/evm/syncervm_test.go b/plugin/evm/syncervm_test.go index 7c8e76fa0a..4e42bfac7e 100644 --- a/plugin/evm/syncervm_test.go +++ b/plugin/evm/syncervm_test.go @@ -15,6 +15,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/ava-labs/avalanchego/api/metrics" avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" avalanchedatabase "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/prefixdb" @@ -33,7 +34,6 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/plugin/evm/database" @@ -87,11 +87,6 @@ func TestStateSyncFromScratchExceedParent(t *testing.T) { func TestStateSyncToggleEnabledToDisabled(t *testing.T) { rand.Seed(1) - // Hack: registering metrics uses global variables, so we need to disable metrics here so that we can initialize the VM twice. - metrics.Enabled = false - defer func() { - metrics.Enabled = true - }() var lock sync.Mutex reqCount := 0 @@ -141,7 +136,8 @@ func TestStateSyncToggleEnabledToDisabled(t *testing.T) { go vmSetup.serverVM.AppRequest(ctx, nodeID, requestID, time.Now().Add(1*time.Second), request) return nil } - // Disable metrics to prevent duplicate registerer + // Reset metrics to allow re-initialization + vmSetup.syncerVM.ctx.Metrics = metrics.NewPrefixGatherer() stateSyncDisabledConfigJSON := `{"state-sync-enabled":false}` if err := syncDisabledVM.Initialize( context.Background(), @@ -206,6 +202,8 @@ func TestStateSyncToggleEnabledToDisabled(t *testing.T) { `{"state-sync-enabled":true, "state-sync-min-blocks":%d}`, test.stateSyncMinBlocks, ) + // Reset metrics to allow re-initialization + vmSetup.syncerVM.ctx.Metrics = metrics.NewPrefixGatherer() if err := syncReEnabledVM.Initialize( context.Background(), vmSetup.syncerVM.ctx, diff --git a/plugin/evm/testutils/metrics.go b/plugin/evm/testutils/metrics.go new file mode 100644 index 0000000000..aa2ee19037 --- /dev/null +++ b/plugin/evm/testutils/metrics.go @@ -0,0 +1,20 @@ +package testutils + +import ( + "testing" + + "github.com/ethereum/go-ethereum/metrics" +) + +// WithMetrics enables go-ethereum metrics globally for the test. +// If the [metrics.Enabled] is already true, nothing is done. +// Otherwise, it is set to true and is reverted to false when the test finishes. +func WithMetrics(t *testing.T) { + if metrics.Enabled { + return + } + metrics.Enabled = true + t.Cleanup(func() { + metrics.Enabled = false + }) +} diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index e955358909..d02d4229a7 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -34,8 +34,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/eth" "github.com/ava-labs/coreth/eth/ethconfig" - "github.com/ava-labs/coreth/metrics" - corethPrometheus "github.com/ava-labs/coreth/metrics/prometheus" + corethprometheus "github.com/ava-labs/coreth/metrics/prometheus" "github.com/ava-labs/coreth/miner" "github.com/ava-labs/coreth/node" "github.com/ava-labs/coreth/params" @@ -46,6 +45,7 @@ import ( "github.com/ava-labs/coreth/triedb" "github.com/ava-labs/coreth/triedb/hashdb" "github.com/ava-labs/coreth/utils" + "github.com/ethereum/go-ethereum/metrics" warpcontract "github.com/ava-labs/coreth/precompile/contracts/warp" "github.com/ava-labs/coreth/rpc" @@ -631,13 +631,9 @@ func (vm *VM) Initialize( } func (vm *VM) initializeMetrics() error { + metrics.Enabled = true vm.sdkMetrics = prometheus.NewRegistry() - // If metrics are enabled, register the default metrics registry - if !metrics.Enabled { - return nil - } - - gatherer := corethPrometheus.Gatherer(metrics.DefaultRegistry) + gatherer := corethprometheus.NewGatherer(metrics.DefaultRegistry) if err := vm.ctx.Metrics.Register(ethMetricsPrefix, gatherer); err != nil { return err } diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 9acc363533..9fb8949c9a 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -23,7 +23,6 @@ import ( "github.com/ava-labs/coreth/constants" "github.com/ava-labs/coreth/eth/filters" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/plugin/evm/config" "github.com/ava-labs/coreth/trie" @@ -32,6 +31,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/ava-labs/avalanchego/api/metrics" avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/memdb" @@ -376,6 +376,12 @@ func GenesisVMWithUTXOs(t *testing.T, finishBootstrapping bool, genesisJSON stri return issuer, vm, db, sharedMemory, sender } +// resetMetrics resets the vm avalanchego metrics, and allows +// for the VM to be re-initialized in tests. +func resetMetrics(vm *VM) { + vm.ctx.Metrics = metrics.NewPrefixGatherer() +} + func TestVMConfig(t *testing.T) { txFeeCap := float64(11) enabledEthAPIs := []string{"debug"} @@ -3771,10 +3777,6 @@ func TestExtraStateChangeAtomicGasLimitExceeded(t *testing.T) { } func TestSkipChainConfigCheckCompatible(t *testing.T) { - // Hack: registering metrics uses global variables, so we need to disable metrics here so that we can initialize the VM twice. - metrics.Enabled = false - defer func() { metrics.Enabled = true }() - importAmount := uint64(50000000) issuer, vm, dbManager, _, appSender := GenesisVMWithUTXOs(t, true, genesisJSONApricotPhase1, "", "", map[ids.ShortID]uint64{ testShortIDAddrs[0]: importAmount, @@ -3803,10 +3805,14 @@ func TestSkipChainConfigCheckCompatible(t *testing.T) { genesisWithUpgradeBytes, err := json.Marshal(genesisWithUpgrade) require.NoError(t, err) + resetMetrics(vm) + // this will not be allowed err = reinitVM.Initialize(context.Background(), vm.ctx, dbManager, genesisWithUpgradeBytes, []byte{}, []byte{}, issuer, []*commonEng.Fx{}, appSender) require.ErrorContains(t, err, "mismatching ApricotPhase2 fork block timestamp in database") + resetMetrics(vm) + // try again with skip-upgrade-check config := []byte(`{"skip-upgrade-check": true}`) err = reinitVM.Initialize(context.Background(), vm.ctx, dbManager, genesisWithUpgradeBytes, []byte{}, config, issuer, []*commonEng.Fx{}, appSender) diff --git a/rpc/handler.go b/rpc/handler.go index ef35a61ca8..82d1235ab1 100644 --- a/rpc/handler.go +++ b/rpc/handler.go @@ -38,8 +38,8 @@ import ( "sync" "time" - "github.com/ava-labs/coreth/metrics" "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" "golang.org/x/time/rate" ) diff --git a/rpc/metrics.go b/rpc/metrics.go index 889b48fcdc..bafdcf591c 100644 --- a/rpc/metrics.go +++ b/rpc/metrics.go @@ -30,7 +30,7 @@ import ( "fmt" "time" - "github.com/ava-labs/coreth/metrics" + "github.com/ethereum/go-ethereum/metrics" ) var ( diff --git a/scripts/geth-allowed-packages.txt b/scripts/geth-allowed-packages.txt index c295d5d044..e54cbd6481 100644 --- a/scripts/geth-allowed-packages.txt +++ b/scripts/geth-allowed-packages.txt @@ -17,4 +17,5 @@ "github.com/ethereum/go-ethereum/ethdb/pebble" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/log" +"github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/rlp" diff --git a/scripts/lint_allowed_geth_imports.sh b/scripts/lint_allowed_geth_imports.sh index e428113613..6ae45f88eb 100755 --- a/scripts/lint_allowed_geth_imports.sh +++ b/scripts/lint_allowed_geth_imports.sh @@ -8,7 +8,7 @@ set -o pipefail # 1. Recursively search through all go files for any lines that include a direct import from go-ethereum # 2. Sort the unique results # #. Print out the difference between the search results and the list of specified allowed package imports from geth. -extra_imports=$(grep -r --include='*.go' '"github.com/ethereum/go-ethereum/.*"' -o -h | sort -u | comm -23 - ./scripts/geth-allowed-packages.txt) +extra_imports=$(find . -type f \( -name "*.go" \) ! -path "./core/main_test.go" -exec grep -o -h '"github.com/ethereum/go-ethereum/.*"' {} + | sort -u | comm -23 - ./scripts/geth-allowed-packages.txt) if [ -n "${extra_imports}" ]; then echo "new go-ethereum imports should be added to ./scripts/geth-allowed-packages.txt to prevent accidental imports:" echo "${extra_imports}" diff --git a/sync/client/stats/stats.go b/sync/client/stats/stats.go index 14af154423..0bd47ce96d 100644 --- a/sync/client/stats/stats.go +++ b/sync/client/stats/stats.go @@ -7,8 +7,8 @@ import ( "fmt" "time" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/plugin/evm/message" + "github.com/ethereum/go-ethereum/metrics" ) var ( diff --git a/sync/handlers/stats/stats.go b/sync/handlers/stats/stats.go index 9dd04c4ea0..d6e3271911 100644 --- a/sync/handlers/stats/stats.go +++ b/sync/handlers/stats/stats.go @@ -6,7 +6,7 @@ package stats import ( "time" - "github.com/ava-labs/coreth/metrics" + "github.com/ethereum/go-ethereum/metrics" ) // HandlerStats reports prometheus metrics for the state sync handlers diff --git a/sync/statesync/trie_sync_stats.go b/sync/statesync/trie_sync_stats.go index c55fc8da35..4cc6a0c5b2 100644 --- a/sync/statesync/trie_sync_stats.go +++ b/sync/statesync/trie_sync_stats.go @@ -10,9 +10,9 @@ import ( utils_math "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/timer" - "github.com/ava-labs/coreth/metrics" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" ) const ( diff --git a/sync/statesync/trie_sync_stats_test.go b/sync/statesync/trie_sync_stats_test.go index c23cfec2a2..1d01cd29ec 100644 --- a/sync/statesync/trie_sync_stats_test.go +++ b/sync/statesync/trie_sync_stats_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/ava-labs/coreth/metrics" + "github.com/ethereum/go-ethereum/metrics" "github.com/stretchr/testify/require" ) diff --git a/trie/stacktrie.go b/trie/stacktrie.go index a191252dbb..cf71416ce4 100644 --- a/trie/stacktrie.go +++ b/trie/stacktrie.go @@ -32,9 +32,9 @@ import ( "sync" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/metrics" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" ) var ( diff --git a/trie/utils/verkle.go b/trie/utils/verkle.go index 7f46409852..ce059edc64 100644 --- a/trie/utils/verkle.go +++ b/trie/utils/verkle.go @@ -20,9 +20,9 @@ import ( "encoding/binary" "sync" - "github.com/ava-labs/coreth/metrics" "github.com/crate-crypto/go-ipa/bandersnatch/fr" "github.com/ethereum/go-ethereum/common/lru" + "github.com/ethereum/go-ethereum/metrics" "github.com/gballet/go-verkle" "github.com/holiman/uint256" ) diff --git a/triedb/hashdb/database.go b/triedb/hashdb/database.go index 11efee0fb8..d0d7bafb92 100644 --- a/triedb/hashdb/database.go +++ b/triedb/hashdb/database.go @@ -35,13 +35,13 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/trie/trienode" "github.com/ava-labs/coreth/trie/triestate" "github.com/ava-labs/coreth/utils" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/rlp" ) diff --git a/triedb/pathdb/metrics.go b/triedb/pathdb/metrics.go index 8e3bb412d5..e2df1ca156 100644 --- a/triedb/pathdb/metrics.go +++ b/triedb/pathdb/metrics.go @@ -26,7 +26,7 @@ package pathdb -import "github.com/ava-labs/coreth/metrics" +import "github.com/ethereum/go-ethereum/metrics" // nolint: unused var ( diff --git a/utils/metered_cache.go b/utils/metered_cache.go index 148239dfc9..dfaeac7cca 100644 --- a/utils/metered_cache.go +++ b/utils/metered_cache.go @@ -9,7 +9,7 @@ import ( "time" "github.com/VictoriaMetrics/fastcache" - "github.com/ava-labs/coreth/metrics" + "github.com/ethereum/go-ethereum/metrics" ) // MeteredCache wraps *fastcache.Cache and periodically pulls stats from it. diff --git a/warp/handlers/signature_request_test.go b/warp/handlers/signature_request_test.go index 0688809ed9..5b30d7bc55 100644 --- a/warp/handlers/signature_request_test.go +++ b/warp/handlers/signature_request_test.go @@ -15,6 +15,7 @@ import ( avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" "github.com/ava-labs/coreth/plugin/evm/message" + "github.com/ava-labs/coreth/plugin/evm/testutils" "github.com/ava-labs/coreth/utils" "github.com/ava-labs/coreth/warp" "github.com/ava-labs/coreth/warp/warptest" @@ -22,6 +23,8 @@ import ( ) func TestMessageSignatureHandler(t *testing.T) { + testutils.WithMetrics(t) + database := memdb.New() snowCtx := utils.TestSnowContext() blsSecretKey, err := localsigner.New() @@ -126,6 +129,8 @@ func TestMessageSignatureHandler(t *testing.T) { } func TestBlockSignatureHandler(t *testing.T) { + testutils.WithMetrics(t) + database := memdb.New() snowCtx := utils.TestSnowContext() blsSecretKey, err := localsigner.New() diff --git a/warp/handlers/stats.go b/warp/handlers/stats.go index ef3f31ae9a..d81bce0e02 100644 --- a/warp/handlers/stats.go +++ b/warp/handlers/stats.go @@ -6,7 +6,7 @@ package handlers import ( "time" - "github.com/ava-labs/coreth/metrics" + "github.com/ethereum/go-ethereum/metrics" ) type handlerStats struct { diff --git a/warp/verifier_backend_test.go b/warp/verifier_backend_test.go index 4f6564cf36..718fd78dd1 100644 --- a/warp/verifier_backend_test.go +++ b/warp/verifier_backend_test.go @@ -17,6 +17,7 @@ import ( "github.com/ava-labs/avalanchego/utils/crypto/bls/signer/localsigner" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" + "github.com/ava-labs/coreth/plugin/evm/testutils" "github.com/ava-labs/coreth/utils" "github.com/ava-labs/coreth/warp/warptest" "github.com/stretchr/testify/require" @@ -24,6 +25,8 @@ import ( ) func TestAddressedCallSignatures(t *testing.T) { + testutils.WithMetrics(t) + database := memdb.New() snowCtx := utils.TestSnowContext() blsSecretKey, err := localsigner.New() @@ -138,6 +141,8 @@ func TestAddressedCallSignatures(t *testing.T) { } func TestBlockSignatures(t *testing.T) { + testutils.WithMetrics(t) + database := memdb.New() snowCtx := utils.TestSnowContext() blsSecretKey, err := localsigner.New() diff --git a/warp/verifier_stats.go b/warp/verifier_stats.go index 980d464429..a092751e8b 100644 --- a/warp/verifier_stats.go +++ b/warp/verifier_stats.go @@ -4,7 +4,7 @@ package warp import ( - "github.com/ava-labs/coreth/metrics" + "github.com/ethereum/go-ethereum/metrics" ) type verifierStats struct { From ab196794127c43df354a11469637999fdbd6172a Mon Sep 17 00:00:00 2001 From: Quentin Mc Gaw Date: Mon, 10 Feb 2025 15:29:02 +0100 Subject: [PATCH 38/69] chore(all): minimal changes for last libevm dependency - Uses tip of main libevm dependency + cherry picked commit: https://github.com/ava-labs/libevm/commit/d3f6a5e75e05bdef9416d68b7836fa54013d4f1c - Precompile legacy gas fix (done in https://github.com/ava-labs/libevm/commit/f906679f6fc71e972c7910951c759a5be75d69fa) - Added `HeaderExtra` not-implemented implementation - Minimal changes shamelessly copied over from #746 --- accounts/abi/bind/bind_test.go | 5 +++++ core/types/header_ext.go | 36 +++++++++++++++++++++++++++++++ core/types/state_account.go | 9 +++++--- go.mod | 2 ++ go.sum | 4 ++-- nativeasset/contract.go | 2 +- params/config_extra.go | 6 +++--- params/hooks_libevm.go | 7 +++--- precompile/contract/interfaces.go | 2 +- precompile/contract/mocks.go | 7 +++--- scripts/eth-allowed-packages.txt | 1 + scripts/tests.e2e.sh | 1 + 12 files changed, 65 insertions(+), 17 deletions(-) create mode 100644 core/types/header_ext.go diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index c1035f6b8a..e9a2467624 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -2179,6 +2179,11 @@ func golangBindings(t *testing.T, overload bool) { if out, err := replacer.CombinedOutput(); err != nil { t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out) } + replacer = exec.Command(gocmd, "mod", "edit", "-x", "-require", "github.com/ava-labs/libevm@v0.0.0", "-replace", "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250210135835-d3f6a5e75e05") + replacer.Dir = pkg + if out, err := replacer.CombinedOutput(); err != nil { + t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out) + } tidier := exec.Command(gocmd, "mod", "tidy", "-compat=1.22") tidier.Dir = pkg if out, err := tidier.CombinedOutput(); err != nil { diff --git a/core/types/header_ext.go b/core/types/header_ext.go new file mode 100644 index 0000000000..1096777d6f --- /dev/null +++ b/core/types/header_ext.go @@ -0,0 +1,36 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package types + +import ( + "io" + + ethtypes "github.com/ava-labs/libevm/core/types" + "github.com/ava-labs/libevm/rlp" +) + +// HeaderExtra is a struct that contains extra fields used by Avalanche +// in the block header. +type HeaderExtra struct { +} + +func (h *HeaderExtra) EncodeRLP(eth *ethtypes.Header, writer io.Writer) error { + panic("not implemented") +} + +func (h *HeaderExtra) DecodeRLP(eth *ethtypes.Header, stream *rlp.Stream) error { + panic("not implemented") +} + +func (h *HeaderExtra) MarshalJSON(eth *ethtypes.Header) ([]byte, error) { + panic("not implemented") +} + +func (h *HeaderExtra) UnmarshalJSON(eth *ethtypes.Header, input []byte) error { + panic("not implemented") +} + +func (h *HeaderExtra) PostCopy(dst *ethtypes.Header) { + panic("not implemented") +} diff --git a/core/types/state_account.go b/core/types/state_account.go index 9af3d4ce15..c0e3df824f 100644 --- a/core/types/state_account.go +++ b/core/types/state_account.go @@ -46,8 +46,11 @@ var ( type isMultiCoin bool -var IsMultiCoinPayloads = ethtypes.RegisterExtras[isMultiCoin]() +var ( + extras = ethtypes.RegisterExtras[ethtypes.NOOPHeaderHooks, *ethtypes.NOOPHeaderHooks, isMultiCoin]() + IsMultiCoinPayloads = extras.StateAccount +) -func IsMultiCoin(a ethtypes.ExtraPayloadCarrier) bool { - return bool(IsMultiCoinPayloads.FromPayloadCarrier(a)) +func IsMultiCoin(s ethtypes.StateOrSlimAccount) bool { + return bool(extras.StateAccount.Get(s)) } diff --git a/go.mod b/go.mod index 7b23e789b0..6e917bd14f 100644 --- a/go.mod +++ b/go.mod @@ -135,3 +135,5 @@ require ( gopkg.in/yaml.v3 v3.0.1 // indirect rsc.io/tmplfunc v0.0.3 // indirect ) + +replace github.com/ava-labs/libevm => github.com/ava-labs/libevm v0.0.0-20250210135835-d3f6a5e75e05 diff --git a/go.sum b/go.sum index 2c5b99975c..6b465ceb3f 100644 --- a/go.sum +++ b/go.sum @@ -58,8 +58,8 @@ github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/ava-labs/avalanchego v1.12.1-0.20250107220127-32f58b4fa9c8 h1:qN3MOBHB//Ynhgt5Vys3iVe42Sr0EWSeN18VL3ecXzE= github.com/ava-labs/avalanchego v1.12.1-0.20250107220127-32f58b4fa9c8/go.mod h1:2B7+E5neLvkOr2zursGhebjU26d4AfB7RazPxBs8hHg= -github.com/ava-labs/libevm v1.13.14-0.1.0.rc-2 h1:CVbn0hSsPCl6gCkTCnqwuN4vtJgdVbkCqLXzYAE7qF8= -github.com/ava-labs/libevm v1.13.14-0.1.0.rc-2/go.mod h1:yBctIV/wnxXTF38h95943jvpuk4aj07TrjbpoGor6LQ= +github.com/ava-labs/libevm v0.0.0-20250210135835-d3f6a5e75e05 h1:LzpeCE04Opu8tepYoA1xxdWCYZI7J0etGcBAzABt6j0= +github.com/ava-labs/libevm v0.0.0-20250210135835-d3f6a5e75e05/go.mod h1:M8TCw2g1D5GBB7hu7g1F4aot5bRHGSxnBawNVmHE9Z0= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/nativeasset/contract.go b/nativeasset/contract.go index e08e0d652e..523e55b33c 100644 --- a/nativeasset/contract.go +++ b/nativeasset/contract.go @@ -141,7 +141,7 @@ func (c *NativeAssetCall) Run(accessibleState contract.AccessibleState, caller c stateDB.SubBalanceMultiCoin(caller, assetID, assetAmount) stateDB.AddBalanceMultiCoin(to, assetID, assetAmount) - ret, remainingGas, err = accessibleState.Call(to, callData, remainingGas, new(uint256.Int), vm.WithUNSAFECallerAddressProxying()) + ret, err = accessibleState.Call(to, callData, remainingGas, new(uint256.Int), vm.WithUNSAFECallerAddressProxying()) // When an error was returned by the EVM or when setting the creation code // above we revert to the snapshot and consume any gas remaining. Additionally diff --git a/params/config_extra.go b/params/config_extra.go index a9e5b0bdd9..17cee401e0 100644 --- a/params/config_extra.go +++ b/params/config_extra.go @@ -59,10 +59,10 @@ func SetEthUpgrades(c *ChainConfig) { } func GetExtra(c *ChainConfig) *extras.ChainConfig { - ex := payloads.FromChainConfig(c) + ex := payloads.ChainConfig.Get(c) if ex == nil { ex = &extras.ChainConfig{} - payloads.SetOnChainConfig(c, ex) + payloads.ChainConfig.Set(c, ex) } return ex } @@ -75,7 +75,7 @@ func Copy(c *ChainConfig) ChainConfig { // WithExtra sets the extra payload on `c` and returns the modified argument. func WithExtra(c *ChainConfig, extra *extras.ChainConfig) *ChainConfig { - payloads.SetOnChainConfig(c, extra) + payloads.ChainConfig.Set(c, extra) return c } diff --git a/params/hooks_libevm.go b/params/hooks_libevm.go index b26a7a36b3..759bd189cb 100644 --- a/params/hooks_libevm.go +++ b/params/hooks_libevm.go @@ -16,6 +16,7 @@ import ( "github.com/ava-labs/libevm/common" "github.com/ava-labs/libevm/core/vm" "github.com/ava-labs/libevm/libevm" + "github.com/ava-labs/libevm/libevm/legacy" "github.com/holiman/uint256" "golang.org/x/exp/maps" ) @@ -23,7 +24,7 @@ import ( type RulesExtra extras.Rules func GetRulesExtra(r Rules) *extras.Rules { - rules := payloads.PointerFromRules(&r) + rules := payloads.Rules.GetPointer(&r) return (*extras.Rules)(rules) } @@ -125,7 +126,7 @@ func makePrecompile(contract contract.StatefulPrecompiledContract) libevm.Precom } return contract.Run(accessableState, env.Addresses().Caller, env.Addresses().Self, input, suppliedGas, env.ReadOnly()) } - return vm.NewStatefulPrecompile(run) + return vm.NewStatefulPrecompile(legacy.PrecompiledStatefulContract(run).Upgrade()) } func (r RulesExtra) PrecompileOverride(addr common.Address) (libevm.PrecompiledContract, bool) { @@ -171,7 +172,7 @@ func (a accessableState) GetSnowContext() *snow.Context { return GetExtra(a.env.ChainConfig()).SnowCtx } -func (a accessableState) Call(addr common.Address, input []byte, gas uint64, value *uint256.Int, opts ...vm.CallOption) (ret []byte, gasRemaining uint64, _ error) { +func (a accessableState) Call(addr common.Address, input []byte, gas uint64, value *uint256.Int, opts ...vm.CallOption) (ret []byte, err error) { return a.env.Call(addr, input, gas, value, opts...) } diff --git a/precompile/contract/interfaces.go b/precompile/contract/interfaces.go index 7de1423a02..a1ae9d5682 100644 --- a/precompile/contract/interfaces.go +++ b/precompile/contract/interfaces.go @@ -61,7 +61,7 @@ type AccessibleState interface { GetBlockContext() BlockContext GetSnowContext() *snow.Context GetChainConfig() precompileconfig.ChainConfig - Call(addr common.Address, input []byte, gas uint64, value *uint256.Int, opts ...vm.CallOption) (ret []byte, gasRemaining uint64, _ error) + Call(addr common.Address, input []byte, gas uint64, value *uint256.Int, opts ...vm.CallOption) (ret []byte, _ error) } // ConfigurationBlockContext defines the interface required to configure a precompile. diff --git a/precompile/contract/mocks.go b/precompile/contract/mocks.go index 6a83011623..6da91cc237 100644 --- a/precompile/contract/mocks.go +++ b/precompile/contract/mocks.go @@ -306,7 +306,7 @@ func (m *MockAccessibleState) EXPECT() *MockAccessibleStateMockRecorder { } // Call mocks base method. -func (m *MockAccessibleState) Call(addr common.Address, input []byte, gas uint64, value *uint256.Int, opts ...vm.CallOption) ([]byte, uint64, error) { +func (m *MockAccessibleState) Call(addr common.Address, input []byte, gas uint64, value *uint256.Int, opts ...vm.CallOption) ([]byte, error) { m.ctrl.T.Helper() varargs := []any{addr, input, gas, value} for _, a := range opts { @@ -314,9 +314,8 @@ func (m *MockAccessibleState) Call(addr common.Address, input []byte, gas uint64 } ret := m.ctrl.Call(m, "Call", varargs...) ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(uint64) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 + ret1, _ := ret[1].(error) + return ret0, ret1 } // Call indicates an expected call of Call. diff --git a/scripts/eth-allowed-packages.txt b/scripts/eth-allowed-packages.txt index 6f69e52bcd..0f200f77f5 100644 --- a/scripts/eth-allowed-packages.txt +++ b/scripts/eth-allowed-packages.txt @@ -25,6 +25,7 @@ "github.com/ava-labs/libevm/ethdb/pebble" "github.com/ava-labs/libevm/event" "github.com/ava-labs/libevm/libevm" +"github.com/ava-labs/libevm/libevm/legacy" "github.com/ava-labs/libevm/libevm/stateconf" "github.com/ava-labs/libevm/log" "github.com/ava-labs/libevm/params" diff --git a/scripts/tests.e2e.sh b/scripts/tests.e2e.sh index 85f5bd3d48..c54f521360 100755 --- a/scripts/tests.e2e.sh +++ b/scripts/tests.e2e.sh @@ -45,6 +45,7 @@ git checkout -B "test-${AVALANCHE_VERSION}" "${AVALANCHE_VERSION}" echo "updating coreth dependency to point to ${CORETH_PATH}" go mod edit -replace "github.com/ava-labs/coreth=${CORETH_PATH}" +go mod edit -replace "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250210135835-d3f6a5e75e05" go mod tidy echo "building avalanchego" From 986b18e773e916863692ef10527b02cc027e0c3e Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 11 Feb 2025 12:47:57 -0500 Subject: [PATCH 39/69] Implement ACP-176 math (#783) --- plugin/evm/acp176/acp176.go | 182 ++++++++ plugin/evm/acp176/acp176_test.go | 704 +++++++++++++++++++++++++++++++ 2 files changed, 886 insertions(+) create mode 100644 plugin/evm/acp176/acp176.go create mode 100644 plugin/evm/acp176/acp176_test.go diff --git a/plugin/evm/acp176/acp176.go b/plugin/evm/acp176/acp176.go new file mode 100644 index 0000000000..88b582749f --- /dev/null +++ b/plugin/evm/acp176/acp176.go @@ -0,0 +1,182 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +// ACP176 implements the fee logic specified here: +// https://github.com/avalanche-foundation/ACPs/blob/main/ACPs/176-dynamic-evm-gas-limit-and-price-discovery-updates/README.md +package acp176 + +import ( + "fmt" + "math" + "math/big" + "sort" + + "github.com/ava-labs/avalanchego/vms/components/gas" + "github.com/holiman/uint256" + + safemath "github.com/ava-labs/avalanchego/utils/math" +) + +const ( + MinTargetPerSecond = 1_000_000 // P + TargetConversion = MaxTargetChangeRate * MaxTargetExcessDiff // D + MaxTargetExcessDiff = 1 << 15 // Q + MinGasPrice = 1 // M + + TimeToFillCapacity = 10 // in seconds + TargetToMax = 2 // multiplier to convert from target per second to max per second + TargetToPriceUpdateConversion = 43 // 43s ~= 30s * ln(2) which makes the price double at most every ~30 seconds + MaxTargetChangeRate = 1024 // Controls the rate that the target can change per block. + + targetToMaxCapacity = TargetToMax * TimeToFillCapacity + maxTargetExcess = 1_024_950_627 // TargetConversion * ln(MaxUint64 / MinTargetPerSecond) + 1 +) + +// State represents the current state of the gas pricing and constraints. +type State struct { + Gas gas.State + TargetExcess gas.Gas // q +} + +// Target returns the target gas consumed per second, `T`. +// +// Target = MinTargetPerSecond * e^(TargetExcess / TargetConversion) +func (s *State) Target() gas.Gas { + return gas.Gas(gas.CalculatePrice( + MinTargetPerSecond, + s.TargetExcess, + TargetConversion, + )) +} + +// MaxCapacity returns the maximum possible accrued gas capacity, `C`. +func (s *State) MaxCapacity() gas.Gas { + targetPerSecond := s.Target() + maxCapacity, err := safemath.Mul(targetToMaxCapacity, targetPerSecond) + if err != nil { + maxCapacity = math.MaxUint64 + } + return maxCapacity +} + +// GasPrice returns the current required fee per gas. +// +// GasPrice = MinGasPrice * e^(Excess / (Target() * TargetToPriceUpdateConversion)) +func (s *State) GasPrice() gas.Price { + target := s.Target() + priceUpdateConversion, err := safemath.Mul(TargetToPriceUpdateConversion, target) // K + if err != nil { + priceUpdateConversion = math.MaxUint64 + } + + return gas.CalculatePrice(MinGasPrice, s.Gas.Excess, priceUpdateConversion) +} + +// AdvanceTime increases the gas capacity and decreases the gas excess based on +// the elapsed seconds. +func (s *State) AdvanceTime(seconds uint64) { + targetPerSecond := s.Target() + maxPerSecond, err := safemath.Mul(TargetToMax, targetPerSecond) // R + if err != nil { + maxPerSecond = math.MaxUint64 + } + maxCapacity, err := safemath.Mul(TimeToFillCapacity, maxPerSecond) // C + if err != nil { + maxCapacity = math.MaxUint64 + } + s.Gas = s.Gas.AdvanceTime( + maxCapacity, + maxPerSecond, + targetPerSecond, + seconds, + ) +} + +// ConsumeGas decreases the gas capacity and increases the gas excess by +// gasUsed + extraGasUsed. If the gas capacity is insufficient, an error is +// returned. +func (s *State) ConsumeGas( + gasUsed uint64, + extraGasUsed *big.Int, +) error { + newGas, err := s.Gas.ConsumeGas(gas.Gas(gasUsed)) + if err != nil { + return err + } + + if extraGasUsed == nil { + s.Gas = newGas + return nil + } + if !extraGasUsed.IsUint64() { + return fmt.Errorf("%w: extraGasUsed (%d) exceeds MaxUint64", + gas.ErrInsufficientCapacity, + extraGasUsed, + ) + } + newGas, err = newGas.ConsumeGas(gas.Gas(extraGasUsed.Uint64())) + if err != nil { + return err + } + + s.Gas = newGas + return nil +} + +// UpdateTargetExcess updates the targetExcess to be as close as possible to the +// desiredTargetExcess without exceeding the maximum targetExcess change. +func (s *State) UpdateTargetExcess(desiredTargetExcess gas.Gas) { + previousTargetPerSecond := s.Target() + s.TargetExcess = targetExcess(s.TargetExcess, desiredTargetExcess) + newTargetPerSecond := s.Target() + s.Gas.Excess = scaleExcess( + s.Gas.Excess, + newTargetPerSecond, + previousTargetPerSecond, + ) +} + +// DesiredTargetExcess calculates the optimal desiredTargetExcess given the +// desired target. +// +// This could be solved directly by calculating D * ln(desiredTarget / P) using +// floating point math. However, it introduces inaccuracies. So, we use a binary +// search to find the closest integer solution. +func DesiredTargetExcess(desiredTarget gas.Gas) gas.Gas { + return gas.Gas(sort.Search(maxTargetExcess, func(targetExcessGuess int) bool { + state := State{ + TargetExcess: gas.Gas(targetExcessGuess), + } + return state.Target() >= desiredTarget + })) +} + +// targetExcess calculates the optimal new targetExcess for a block proposer to +// include given the current and desired excess values. +func targetExcess(excess, desired gas.Gas) gas.Gas { + change := safemath.AbsDiff(excess, desired) + change = min(change, MaxTargetExcessDiff) + if excess < desired { + return excess + change + } + return excess - change +} + +// scaleExcess scales the excess during gas target modifications to keep the +// price constant. +func scaleExcess( + excess, + newTargetPerSecond, + previousTargetPerSecond gas.Gas, +) gas.Gas { + var bigExcess uint256.Int + bigExcess.SetUint64(uint64(excess)) + + var bigTarget uint256.Int + bigTarget.SetUint64(uint64(newTargetPerSecond)) + bigExcess.Mul(&bigExcess, &bigTarget) + + bigTarget.SetUint64(uint64(previousTargetPerSecond)) + bigExcess.Div(&bigExcess, &bigTarget) + return gas.Gas(bigExcess.Uint64()) +} diff --git a/plugin/evm/acp176/acp176_test.go b/plugin/evm/acp176/acp176_test.go new file mode 100644 index 0000000000..be509292ca --- /dev/null +++ b/plugin/evm/acp176/acp176_test.go @@ -0,0 +1,704 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package acp176 + +import ( + "math" + "math/big" + "testing" + + "github.com/ava-labs/avalanchego/vms/components/gas" + "github.com/ethereum/go-ethereum/common" + "github.com/stretchr/testify/require" +) + +const nAVAX = 1_000_000_000 + +var ( + readerTests = []struct { + name string + state State + skipTestDesiredTargetExcess bool + target gas.Gas + maxCapacity gas.Gas + gasPrice gas.Price + }{ + { + name: "zero", + state: State{ + Gas: gas.State{ + Excess: 0, + }, + TargetExcess: 0, + }, + target: MinTargetPerSecond, + maxCapacity: targetToMaxCapacity * MinTargetPerSecond, + gasPrice: MinGasPrice, + }, + { + name: "almost_excess_change", + state: State{ + Gas: gas.State{ + Excess: 29_805_331, // MinTargetPerSecond * ln(2) * TargetToPriceUpdateConversion + }, + TargetExcess: 33, // Largest excess that doesn't increase the target + }, + skipTestDesiredTargetExcess: true, + target: MinTargetPerSecond, + maxCapacity: targetToMaxCapacity * MinTargetPerSecond, + gasPrice: 2 * MinGasPrice, + }, + { + name: "small_excess_change", + state: State{ + Gas: gas.State{ + Excess: 29_805_362, // (MinTargetPerSecond + 1) * ln(2) * TargetToPriceUpdateConversion + }, + TargetExcess: 34, // Smallest excess that increases the target + }, + target: MinTargetPerSecond + 1, + maxCapacity: targetToMaxCapacity * (MinTargetPerSecond + 1), + gasPrice: 2 * MinGasPrice, + }, + { + name: "max_initial_excess_change", + state: State{ + Gas: gas.State{ + Excess: 47_286_485, // (MinTargetPerSecond + 977) * ln(3) * TargetToPriceUpdateConversion + }, + TargetExcess: MaxTargetExcessDiff, + }, + skipTestDesiredTargetExcess: true, + target: MinTargetPerSecond + 977, + maxCapacity: targetToMaxCapacity * (MinTargetPerSecond + 977), + gasPrice: 3 * MinGasPrice, + }, + { + name: "current_target", + state: State{ + Gas: gas.State{ + Excess: 1_336_650_647, // 1_500_000 * ln(nAVAX) * TargetToPriceUpdateConversion + }, + TargetExcess: 13_605_152, // 2^25 * ln(1.5) + }, + target: 1_500_000, + maxCapacity: targetToMaxCapacity * 1_500_000, + gasPrice: (nAVAX + 7) * MinGasPrice, // +7 due to approximation + }, + { + name: "3m_target", + state: State{ + Gas: gas.State{ + Excess: 3_267_368_247, // 3_000_000 * ln(100*nAVAX) * TargetToPriceUpdateConversion + }, + TargetExcess: 36_863_312, // 2^25 * ln(3) + }, + target: 3_000_000, + maxCapacity: targetToMaxCapacity * 3_000_000, + gasPrice: (100*nAVAX + 31) * MinGasPrice, // +31 due to approximation + }, + { + name: "6m_target", + state: State{ + Gas: gas.State{ + Excess: 6_534_736_494, // 6_000_000 * ln(100*nAVAX) * TargetToPriceUpdateConversion + }, + TargetExcess: 60_121_472, // 2^25 * ln(6) + }, + target: 6_000_000, + maxCapacity: targetToMaxCapacity * 6_000_000, + gasPrice: (100*nAVAX + 31) * MinGasPrice, // +31 due to approximation + }, + { + name: "10m_target", + state: State{ + Gas: gas.State{ + Excess: 10_891_227_490, // 10_000_000 * ln(100*nAVAX) * TargetToPriceUpdateConversion + }, + TargetExcess: 77_261_935, // 2^25 * ln(10) + }, + target: 10_000_000, + maxCapacity: targetToMaxCapacity * 10_000_000, + gasPrice: (100*nAVAX + 31) * MinGasPrice, // +31 due to approximation + }, + { + name: "100m_target", + state: State{ + Gas: gas.State{ + Excess: 108_912_274_899, // 100_000_000 * ln(100*nAVAX) * TargetToPriceUpdateConversion + }, + TargetExcess: 154_523_870, // 2^25 * ln(100) + }, + target: 100_000_000, + maxCapacity: targetToMaxCapacity * 100_000_000, + gasPrice: (100*nAVAX + 8) * MinGasPrice, // +8 due to approximation + }, + { + name: "low_1b_target", + state: State{ + Gas: gas.State{ + Excess: 1_089_122_722_848, // (1_000_000_000 - 24) * ln(100*nAVAX) * TargetToPriceUpdateConversion + }, + TargetExcess: 231_785_804, // 2^25 * ln(1000) + }, + target: 1_000_000_000 - 24, + maxCapacity: targetToMaxCapacity * (1_000_000_000 - 24), + gasPrice: (100*nAVAX + 1) * MinGasPrice, // +1 due to approximation + }, + { + name: "high_1b_target", + state: State{ + Gas: gas.State{ + Excess: 1_089_122_755_521, // (1_000_000_000 + 6) * ln(100*nAVAX) * TargetToPriceUpdateConversion + }, + TargetExcess: 231_785_805, // 2^25 * ln(1000) + 1 + }, + target: 1_000_000_000 + 6, + maxCapacity: targetToMaxCapacity * (1_000_000_000 + 6), + gasPrice: (100 * nAVAX) * MinGasPrice, + }, + { + name: "largest_max_capacity", + state: State{ + Gas: gas.State{ + Excess: math.MaxUint64, + }, + TargetExcess: 924430531, // 2^25 * ln(MaxUint64 / MinMaxCapacity) + }, + target: 922_337_190_378_117_171, + maxCapacity: 18_446_743_807_562_343_420, + gasPrice: 2 * MinGasPrice, + }, + { + name: "largest_int64_target", + state: State{ + Gas: gas.State{ + Excess: math.MaxUint64, + }, + TargetExcess: 1_001_692_466, // 2^25 * ln(MaxInt64 / MinTargetPerSecond) + }, + target: 9_223_371_923_824_614_091, + maxCapacity: math.MaxUint64, + gasPrice: 2 * MinGasPrice, + }, + { + name: "second_largest_uint64_target", + state: State{ + Gas: gas.State{ + Excess: math.MaxUint64, + }, + TargetExcess: 1_024_950_626, // 2^25 * ln(MaxUint64 / MinTargetPerSecond) + }, + target: 18_446_743_882_783_898_031, + maxCapacity: math.MaxUint64, + gasPrice: 2 * MinGasPrice, + }, + { + name: "largest_uint64_target", + state: State{ + Gas: gas.State{ + Excess: math.MaxUint64, + }, + TargetExcess: 1_024_950_627, // 2^25 * ln(MaxUint64 / MinTargetPerSecond) + 1 + }, + target: math.MaxUint64, + maxCapacity: math.MaxUint64, + gasPrice: 2 * MinGasPrice, + }, + { + name: "largest_excess", + state: State{ + Gas: gas.State{ + Excess: math.MaxUint64, + }, + TargetExcess: math.MaxUint64, + }, + skipTestDesiredTargetExcess: true, + target: math.MaxUint64, + maxCapacity: math.MaxUint64, + gasPrice: 2 * MinGasPrice, + }, + } + advanceTimeTests = []struct { + name string + initial State + seconds uint64 + expected State + }{ + { + name: "0_seconds", + initial: State{ + Gas: gas.State{ + Capacity: 0, + Excess: 2_000_000, + }, + // Set target to 1.5M per second + TargetExcess: 13_605_152, // 2^25 * ln(1.5) + }, + seconds: 0, + expected: State{ + Gas: gas.State{ + Capacity: 0, + Excess: 2_000_000, + }, + TargetExcess: 13_605_152, // unmodified + }, + }, + { + name: "1_seconds", + initial: State{ + Gas: gas.State{ + Capacity: 0, + Excess: 2_000_000, + }, + // Set target to 1.5M per second + TargetExcess: 13_605_152, // 2^25 * ln(1.5) + }, + seconds: 1, + expected: State{ + Gas: gas.State{ + Capacity: 3_000_000, + Excess: 500_000, + }, + TargetExcess: 13_605_152, // unmodified + }, + }, + { + name: "5_seconds", + initial: State{ + Gas: gas.State{ + Capacity: 0, + Excess: 15_000_000, + }, + // Set target to 1.5M per second + TargetExcess: 13_605_152, // 2^25 * ln(1.5) + }, + seconds: 5, + expected: State{ + Gas: gas.State{ + Capacity: 15_000_000, + Excess: 7_500_000, + }, + TargetExcess: 13_605_152, // unmodified + }, + }, + { + name: "0_seconds_over_capacity", + initial: State{ + Gas: gas.State{ + Capacity: 31_000_000, // Could happen if the targetExcess was modified + Excess: 2_000_000, + }, + // Set capacity to 30M + TargetExcess: 13_605_152, // 2^25 * ln(1.5) + }, + seconds: 0, + expected: State{ + Gas: gas.State{ + Capacity: 30_000_000, // capped at 30M + Excess: 2_000_000, // unmodified + }, + TargetExcess: 13_605_152, // unmodified + }, + }, + { + name: "hit_max_capacity_boundary", + initial: State{ + Gas: gas.State{ + Capacity: 0, // Could happen if the targetExcess was modified + Excess: math.MaxUint64, + }, + // Set MaxCapacity to MaxUint64 + TargetExcess: 924_430_532, // 2^25 * ln(MaxUint64 / MinMaxCapacity) + }, + seconds: 1, + expected: State{ + Gas: gas.State{ + Capacity: 1_844_674_435_731_815_790, // greater than MaxUint64/10 + Excess: math.MaxUint64 - 922_337_217_865_907_895, // MaxUint64 - capacity / TargetToMax + }, + TargetExcess: 924_430_532, // unmodified + }, + }, + { + name: "hit_max_rate_boundary", + initial: State{ + Gas: gas.State{ + Capacity: 0, // Could happen if the targetExcess was modified + Excess: math.MaxUint64, + }, + // Set MaxPerSecond to MaxUint64 + TargetExcess: 1_001_692_467, // 2^25 * ln(MaxUint64 / MinMaxPerSecond) + }, + seconds: 1, + expected: State{ + Gas: gas.State{ + Capacity: math.MaxUint64, // greater than MaxUint64/10 + Excess: 9_223_371_875_007_030_354, // less than MaxUint64/2 + }, + TargetExcess: 1_001_692_467, // unmodified + }, + }, + } + consumeGasTests = []struct { + name string + initial State + gasUsed uint64 + extraGasUsed *big.Int + expectedErr error + expected State + }{ + { + name: "no_gas_used", + initial: State{ + Gas: gas.State{ + Capacity: 1_000_000, + Excess: 2_000_000, + }, + }, + gasUsed: 0, + extraGasUsed: nil, + expected: State{ + Gas: gas.State{ + Capacity: 1_000_000, + Excess: 2_000_000, + }, + }, + }, + { + name: "some_gas_used", + initial: State{ + Gas: gas.State{ + Capacity: 1_000_000, + Excess: 2_000_000, + }, + }, + gasUsed: 100_000, + extraGasUsed: nil, + expected: State{ + Gas: gas.State{ + Capacity: 900_000, + Excess: 2_100_000, + }, + }, + }, + { + name: "some_extra_gas_used", + initial: State{ + Gas: gas.State{ + Capacity: 1_000_000, + Excess: 2_000_000, + }, + }, + gasUsed: 0, + extraGasUsed: big.NewInt(100_000), + expected: State{ + Gas: gas.State{ + Capacity: 900_000, + Excess: 2_100_000, + }, + }, + }, + { + name: "both_gas_used", + initial: State{ + Gas: gas.State{ + Capacity: 1_000_000, + Excess: 2_000_000, + }, + }, + gasUsed: 10_000, + extraGasUsed: big.NewInt(100_000), + expected: State{ + Gas: gas.State{ + Capacity: 890_000, + Excess: 2_110_000, + }, + }, + }, + { + name: "gas_used_capacity_exceeded", + initial: State{ + Gas: gas.State{ + Capacity: 1_000_000, + Excess: 2_000_000, + }, + }, + gasUsed: 1_000_001, + extraGasUsed: nil, + expectedErr: gas.ErrInsufficientCapacity, + expected: State{ + Gas: gas.State{ + Capacity: 1_000_000, + Excess: 2_000_000, + }, + }, + }, + { + name: "massive_extra_gas_used", + initial: State{ + Gas: gas.State{ + Capacity: 1_000_000, + Excess: 2_000_000, + }, + }, + gasUsed: 0, + extraGasUsed: new(big.Int).Lsh(common.Big1, 64), + expectedErr: gas.ErrInsufficientCapacity, + expected: State{ + Gas: gas.State{ + Capacity: 1_000_000, + Excess: 2_000_000, + }, + }, + }, + { + name: "extra_gas_used_capacity_exceeded", + initial: State{ + Gas: gas.State{ + Capacity: 1_000_000, + Excess: 2_000_000, + }, + }, + gasUsed: 0, + extraGasUsed: big.NewInt(1_000_001), + expectedErr: gas.ErrInsufficientCapacity, + expected: State{ + Gas: gas.State{ + Capacity: 1_000_000, + Excess: 2_000_000, + }, + }, + }, + } + updateTargetExcessTests = []struct { + name string + initial State + desiredTargetExcess gas.Gas + expected State + }{ + { + name: "no_change", + initial: State{ + Gas: gas.State{ + Excess: 2_000_000, + }, + TargetExcess: 0, + }, + desiredTargetExcess: 0, + expected: State{ + Gas: gas.State{ + Excess: 2_000_000, + }, + TargetExcess: 0, + }, + }, + { + name: "max_increase", + initial: State{ + Gas: gas.State{ + Excess: 2_000_000, + }, + TargetExcess: 0, + }, + desiredTargetExcess: MaxTargetExcessDiff + 1, + expected: State{ + Gas: gas.State{ + Excess: 2_001_954, // 2M * NewTarget / OldTarget + }, + TargetExcess: MaxTargetExcessDiff, // capped + }, + }, + { + name: "inverse_max_increase", + initial: State{ + Gas: gas.State{ + Excess: 2_001_954, + }, + TargetExcess: MaxTargetExcessDiff, + }, + desiredTargetExcess: 0, + expected: State{ + Gas: gas.State{ + Excess: 2_000_000, // inverse of max_increase + }, + TargetExcess: 0, + }, + }, + { + name: "max_decrease", + initial: State{ + Gas: gas.State{ + Excess: 2_000_000_000, + }, + TargetExcess: 2 * MaxTargetExcessDiff, + }, + desiredTargetExcess: 0, + expected: State{ + Gas: gas.State{ + Excess: 1_998_047_816, // 2M * NewTarget / OldTarget + }, + TargetExcess: MaxTargetExcessDiff, + }, + }, + { + name: "inverse_max_decrease", + initial: State{ + Gas: gas.State{ + Excess: 1_998_047_816, + }, + TargetExcess: MaxTargetExcessDiff, + }, + desiredTargetExcess: 2 * MaxTargetExcessDiff, + expected: State{ + Gas: gas.State{ + Excess: 1_999_999_999, // inverse of max_decrease -1 due to rounding error + }, + TargetExcess: 2 * MaxTargetExcessDiff, + }, + }, + } +) + +func TestTarget(t *testing.T) { + for _, test := range readerTests { + t.Run(test.name, func(t *testing.T) { + require.Equal(t, test.target, test.state.Target()) + }) + } +} + +func BenchmarkTarget(b *testing.B) { + for _, test := range readerTests { + b.Run(test.name, func(b *testing.B) { + for range b.N { + test.state.Target() + } + }) + } +} + +func TestMaxCapacity(t *testing.T) { + for _, test := range readerTests { + t.Run(test.name, func(t *testing.T) { + require.Equal(t, test.maxCapacity, test.state.MaxCapacity()) + }) + } +} + +func BenchmarkMaxCapacity(b *testing.B) { + for _, test := range readerTests { + b.Run(test.name, func(b *testing.B) { + for range b.N { + test.state.MaxCapacity() + } + }) + } +} + +func TestGasPrice(t *testing.T) { + for _, test := range readerTests { + t.Run(test.name, func(t *testing.T) { + require.Equal(t, test.gasPrice, test.state.GasPrice()) + }) + } +} + +func BenchmarkGasPrice(b *testing.B) { + for _, test := range readerTests { + b.Run(test.name, func(b *testing.B) { + for range b.N { + test.state.GasPrice() + } + }) + } +} + +func TestAdvanceTime(t *testing.T) { + for _, test := range advanceTimeTests { + t.Run(test.name, func(t *testing.T) { + initial := test.initial + initial.AdvanceTime(test.seconds) + require.Equal(t, test.expected, initial) + }) + } +} + +func BenchmarkAdvanceTime(b *testing.B) { + for _, test := range advanceTimeTests { + b.Run(test.name, func(b *testing.B) { + for range b.N { + initial := test.initial + initial.AdvanceTime(test.seconds) + } + }) + } +} + +func TestConsumeGas(t *testing.T) { + for _, test := range consumeGasTests { + t.Run(test.name, func(t *testing.T) { + initial := test.initial + err := initial.ConsumeGas(test.gasUsed, test.extraGasUsed) + require.ErrorIs(t, err, test.expectedErr) + require.Equal(t, test.expected, initial) + }) + } +} + +func BenchmarkConsumeGas(b *testing.B) { + for _, test := range consumeGasTests { + b.Run(test.name, func(b *testing.B) { + for range b.N { + initial := test.initial + _ = initial.ConsumeGas(test.gasUsed, test.extraGasUsed) + } + }) + } +} + +func TestUpdateTargetExcess(t *testing.T) { + for _, test := range updateTargetExcessTests { + t.Run(test.name, func(t *testing.T) { + initial := test.initial + initial.UpdateTargetExcess(test.desiredTargetExcess) + require.Equal(t, test.expected, initial) + }) + } +} + +func BenchmarkUpdateTargetExcess(b *testing.B) { + for _, test := range updateTargetExcessTests { + b.Run(test.name, func(b *testing.B) { + for range b.N { + initial := test.initial + initial.UpdateTargetExcess(test.desiredTargetExcess) + } + }) + } +} + +func TestDesiredTargetExcess(t *testing.T) { + for _, test := range readerTests { + if test.skipTestDesiredTargetExcess { + continue + } + t.Run(test.name, func(t *testing.T) { + require.Equal(t, test.state.TargetExcess, DesiredTargetExcess(test.target)) + }) + } +} + +func BenchmarkDesiredTargetExcess(b *testing.B) { + for _, test := range readerTests { + if test.skipTestDesiredTargetExcess { + continue + } + b.Run(test.name, func(b *testing.B) { + for range b.N { + DesiredTargetExcess(test.target) + } + }) + } +} From aa6bcf42c357e277e7e565ecc46d466e1ae36394 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 11 Feb 2025 13:16:29 -0500 Subject: [PATCH 40/69] Refactor `header.Extra` verification (#788) --- consensus/dummy/consensus.go | 25 +++----- plugin/evm/block_verification.go | 35 ++--------- plugin/evm/header/extra.go | 57 +++++++++++++++++ plugin/evm/header/extra_test.go | 103 +++++++++++++++++++++++++++++++ 4 files changed, 174 insertions(+), 46 deletions(-) create mode 100644 plugin/evm/header/extra.go create mode 100644 plugin/evm/header/extra_test.go diff --git a/consensus/dummy/consensus.go b/consensus/dummy/consensus.go index 1452335a95..7bfc69d08d 100644 --- a/consensus/dummy/consensus.go +++ b/consensus/dummy/consensus.go @@ -18,6 +18,8 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/trie" "github.com/ethereum/go-ethereum/common" + + customheader "github.com/ava-labs/coreth/plugin/evm/header" ) var ( @@ -212,25 +214,18 @@ func (eng *DummyEngine) verifyHeaderGasFields(config *params.ChainConfig, header // modified from consensus.go func (eng *DummyEngine) verifyHeader(chain consensus.ChainHeaderReader, header *types.Header, parent *types.Header, uncle bool) error { - config := chain.Config() // Ensure that we do not verify an uncle if uncle { return errUnclesUnsupported } - switch { - case config.IsDurango(header.Time): - if len(header.Extra) < params.DynamicFeeExtraDataSize { - return fmt.Errorf("expected extra-data field length >= %d, found %d", params.DynamicFeeExtraDataSize, len(header.Extra)) - } - case config.IsApricotPhase3(header.Time): - if len(header.Extra) != params.DynamicFeeExtraDataSize { - return fmt.Errorf("expected extra-data field to be: %d, but found %d", params.DynamicFeeExtraDataSize, len(header.Extra)) - } - default: - if uint64(len(header.Extra)) > params.MaximumExtraDataSize { - return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize) - } + + // Verify the extra data is well-formed. + config := chain.Config() + rules := config.GetAvalancheRules(header.Time) + if err := customheader.VerifyExtra(rules, header.Extra); err != nil { + return err } + // Ensure gas-related header fields are correct if err := eng.verifyHeaderGasFields(config, header, parent); err != nil { return err @@ -250,7 +245,7 @@ func (eng *DummyEngine) verifyHeader(chain consensus.ChainHeaderReader, header * return consensus.ErrInvalidNumber } // Verify the existence / non-existence of excessBlobGas - cancun := chain.Config().IsCancun(header.Number, header.Time) + cancun := config.IsCancun(header.Number, header.Time) if !cancun { switch { case header.ExcessBlobGas != nil: diff --git a/plugin/evm/block_verification.go b/plugin/evm/block_verification.go index f0f8db1658..7e97ddc7ac 100644 --- a/plugin/evm/block_verification.go +++ b/plugin/evm/block_verification.go @@ -15,6 +15,7 @@ import ( "github.com/ava-labs/coreth/constants" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/header" "github.com/ava-labs/coreth/trie" ) @@ -120,37 +121,9 @@ func (v blockValidator) SyntacticVerify(b *Block, rules params.Rules) error { } } - // Check that the size of the header's Extra data field is correct for [rules]. - headerExtraDataSize := len(ethHeader.Extra) - switch { - case rules.IsDurango: - if headerExtraDataSize < params.DynamicFeeExtraDataSize { - return fmt.Errorf( - "expected header ExtraData to be len >= %d but got %d", - params.DynamicFeeExtraDataSize, len(ethHeader.Extra), - ) - } - case rules.IsApricotPhase3: - if headerExtraDataSize != params.DynamicFeeExtraDataSize { - return fmt.Errorf( - "expected header ExtraData to be len %d but got %d", - params.DynamicFeeExtraDataSize, headerExtraDataSize, - ) - } - case rules.IsApricotPhase1: - if headerExtraDataSize != 0 { - return fmt.Errorf( - "expected header ExtraData to be 0 but got %d", - headerExtraDataSize, - ) - } - default: - if uint64(headerExtraDataSize) > params.MaximumExtraDataSize { - return fmt.Errorf( - "expected header ExtraData to be <= %d but got %d", - params.MaximumExtraDataSize, headerExtraDataSize, - ) - } + // Verify the extra data is well-formed. + if err := header.VerifyExtra(rules.AvalancheRules, ethHeader.Extra); err != nil { + return err } if b.ethBlock.Version() != 0 { diff --git a/plugin/evm/header/extra.go b/plugin/evm/header/extra.go new file mode 100644 index 0000000000..abe0bd3f1a --- /dev/null +++ b/plugin/evm/header/extra.go @@ -0,0 +1,57 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package header + +import ( + "errors" + "fmt" + + "github.com/ava-labs/coreth/params" +) + +var errInvalidExtraLength = errors.New("invalid header.Extra length") + +// VerifyExtra verifies that the header's Extra field is correctly formatted for +// [rules]. +func VerifyExtra(rules params.AvalancheRules, extra []byte) error { + extraLen := len(extra) + switch { + case rules.IsDurango: + if extraLen < params.DynamicFeeExtraDataSize { + return fmt.Errorf( + "%w: expected >= %d but got %d", + errInvalidExtraLength, + params.DynamicFeeExtraDataSize, + extraLen, + ) + } + case rules.IsApricotPhase3: + if extraLen != params.DynamicFeeExtraDataSize { + return fmt.Errorf( + "%w: expected %d but got %d", + errInvalidExtraLength, + params.DynamicFeeExtraDataSize, + extraLen, + ) + } + case rules.IsApricotPhase1: + if extraLen != 0 { + return fmt.Errorf( + "%w: expected 0 but got %d", + errInvalidExtraLength, + extraLen, + ) + } + default: + if uint64(extraLen) > params.MaximumExtraDataSize { + return fmt.Errorf( + "%w: expected <= %d but got %d", + errInvalidExtraLength, + params.MaximumExtraDataSize, + extraLen, + ) + } + } + return nil +} diff --git a/plugin/evm/header/extra_test.go b/plugin/evm/header/extra_test.go new file mode 100644 index 0000000000..f11e5d5780 --- /dev/null +++ b/plugin/evm/header/extra_test.go @@ -0,0 +1,103 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package header + +import ( + "testing" + + "github.com/ava-labs/coreth/params" + "github.com/stretchr/testify/require" +) + +func TestVerifyExtra(t *testing.T) { + tests := []struct { + name string + rules params.AvalancheRules + extra []byte + expected error + }{ + { + name: "initial_valid", + rules: params.AvalancheRules{}, + extra: make([]byte, params.MaximumExtraDataSize), + expected: nil, + }, + { + name: "initial_invalid", + rules: params.AvalancheRules{}, + extra: make([]byte, params.MaximumExtraDataSize+1), + expected: errInvalidExtraLength, + }, + { + name: "ap1_valid", + rules: params.AvalancheRules{ + IsApricotPhase1: true, + }, + extra: nil, + expected: nil, + }, + { + name: "ap1_invalid", + rules: params.AvalancheRules{ + IsApricotPhase1: true, + }, + extra: make([]byte, 1), + expected: errInvalidExtraLength, + }, + { + name: "ap3_valid", + rules: params.AvalancheRules{ + IsApricotPhase3: true, + }, + extra: make([]byte, params.DynamicFeeExtraDataSize), + expected: nil, + }, + { + name: "ap3_invalid_less", + rules: params.AvalancheRules{ + IsApricotPhase3: true, + }, + extra: make([]byte, params.DynamicFeeExtraDataSize-1), + expected: errInvalidExtraLength, + }, + { + name: "ap3_invalid_more", + rules: params.AvalancheRules{ + IsApricotPhase3: true, + }, + extra: make([]byte, params.DynamicFeeExtraDataSize+1), + expected: errInvalidExtraLength, + }, + { + name: "durango_valid_min", + rules: params.AvalancheRules{ + IsDurango: true, + }, + extra: make([]byte, params.DynamicFeeExtraDataSize), + expected: nil, + }, + { + name: "durango_valid_extra", + rules: params.AvalancheRules{ + IsDurango: true, + }, + extra: make([]byte, params.DynamicFeeExtraDataSize+1), + expected: nil, + }, + { + name: "durango_invalid", + rules: params.AvalancheRules{ + IsDurango: true, + }, + extra: make([]byte, params.DynamicFeeExtraDataSize-1), + expected: errInvalidExtraLength, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := VerifyExtra(test.rules, test.extra) + require.ErrorIs(t, err, test.expected) + }) + } +} From fe9ce0008b8a49ae154d32a66952025fb57f3bc2 Mon Sep 17 00:00:00 2001 From: Quentin Mc Gaw Date: Wed, 12 Feb 2025 13:53:00 +0100 Subject: [PATCH 41/69] Bump libevm dependency to current main At commit https://github.com/ava-labs/libevm/pull/104/commits/9c7285a21b7169d260977f1cff8d56fc92907cf8 --- accounts/abi/bind/bind_test.go | 2 +- core/types/state_account.go | 6 +++++- go.mod | 2 +- go.sum | 4 ++-- scripts/tests.e2e.sh | 2 +- 5 files changed, 10 insertions(+), 6 deletions(-) diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index e9a2467624..8a54f4e420 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -2179,7 +2179,7 @@ func golangBindings(t *testing.T, overload bool) { if out, err := replacer.CombinedOutput(); err != nil { t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out) } - replacer = exec.Command(gocmd, "mod", "edit", "-x", "-require", "github.com/ava-labs/libevm@v0.0.0", "-replace", "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250210135835-d3f6a5e75e05") + replacer = exec.Command(gocmd, "mod", "edit", "-x", "-require", "github.com/ava-labs/libevm@v0.0.0", "-replace", "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250212124953-9c7285a21b71") replacer.Dir = pkg if out, err := replacer.CombinedOutput(); err != nil { t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out) diff --git a/core/types/state_account.go b/core/types/state_account.go index c0e3df824f..b443332030 100644 --- a/core/types/state_account.go +++ b/core/types/state_account.go @@ -47,7 +47,11 @@ var ( type isMultiCoin bool var ( - extras = ethtypes.RegisterExtras[ethtypes.NOOPHeaderHooks, *ethtypes.NOOPHeaderHooks, isMultiCoin]() + extras = ethtypes.RegisterExtras[ + ethtypes.NOOPHeaderHooks, *ethtypes.NOOPHeaderHooks, + ethtypes.NOOPBodyHooks, *ethtypes.NOOPBodyHooks, + isMultiCoin, + ]() IsMultiCoinPayloads = extras.StateAccount ) diff --git a/go.mod b/go.mod index 6e917bd14f..0318e08c69 100644 --- a/go.mod +++ b/go.mod @@ -136,4 +136,4 @@ require ( rsc.io/tmplfunc v0.0.3 // indirect ) -replace github.com/ava-labs/libevm => github.com/ava-labs/libevm v0.0.0-20250210135835-d3f6a5e75e05 +replace github.com/ava-labs/libevm => github.com/ava-labs/libevm v0.0.0-20250212124953-9c7285a21b71 diff --git a/go.sum b/go.sum index 6b465ceb3f..9ae4b445f3 100644 --- a/go.sum +++ b/go.sum @@ -58,8 +58,8 @@ github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/ava-labs/avalanchego v1.12.1-0.20250107220127-32f58b4fa9c8 h1:qN3MOBHB//Ynhgt5Vys3iVe42Sr0EWSeN18VL3ecXzE= github.com/ava-labs/avalanchego v1.12.1-0.20250107220127-32f58b4fa9c8/go.mod h1:2B7+E5neLvkOr2zursGhebjU26d4AfB7RazPxBs8hHg= -github.com/ava-labs/libevm v0.0.0-20250210135835-d3f6a5e75e05 h1:LzpeCE04Opu8tepYoA1xxdWCYZI7J0etGcBAzABt6j0= -github.com/ava-labs/libevm v0.0.0-20250210135835-d3f6a5e75e05/go.mod h1:M8TCw2g1D5GBB7hu7g1F4aot5bRHGSxnBawNVmHE9Z0= +github.com/ava-labs/libevm v0.0.0-20250212124953-9c7285a21b71 h1:C8qlqwg/QPnfJCh7ACTFkfXrMh5Q98revSv0R+PRG88= +github.com/ava-labs/libevm v0.0.0-20250212124953-9c7285a21b71/go.mod h1:xi9AcwLOv3gUYYSuRYxXKVmLMFTSM4g0m4cpvC5X8DU= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/scripts/tests.e2e.sh b/scripts/tests.e2e.sh index c54f521360..ad218a1f57 100755 --- a/scripts/tests.e2e.sh +++ b/scripts/tests.e2e.sh @@ -45,7 +45,7 @@ git checkout -B "test-${AVALANCHE_VERSION}" "${AVALANCHE_VERSION}" echo "updating coreth dependency to point to ${CORETH_PATH}" go mod edit -replace "github.com/ava-labs/coreth=${CORETH_PATH}" -go mod edit -replace "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250210135835-d3f6a5e75e05" +go mod edit -replace "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250212124953-9c7285a21b71" go mod tidy echo "building avalanchego" From 4e68587d34d923183866d1e9b768f7fdcaf75a2f Mon Sep 17 00:00:00 2001 From: Quentin Mc Gaw Date: Thu, 13 Feb 2025 17:49:28 +0100 Subject: [PATCH 42/69] Bump libevm dependency to current main At commit https://github.com/ava-labs/libevm/pull/104/commits/19ec675e01c43f37629264089e78ce8f012ad8a5 --- accounts/abi/bind/bind_test.go | 2 +- core/types/header_ext.go | 4 ++-- go.mod | 2 +- go.sum | 4 ++-- scripts/tests.e2e.sh | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index 8a54f4e420..ef02f473d3 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -2179,7 +2179,7 @@ func golangBindings(t *testing.T, overload bool) { if out, err := replacer.CombinedOutput(); err != nil { t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out) } - replacer = exec.Command(gocmd, "mod", "edit", "-x", "-require", "github.com/ava-labs/libevm@v0.0.0", "-replace", "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250212124953-9c7285a21b71") + replacer = exec.Command(gocmd, "mod", "edit", "-x", "-require", "github.com/ava-labs/libevm@v0.0.0", "-replace", "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250213164614-19ec675e01c4") replacer.Dir = pkg if out, err := replacer.CombinedOutput(); err != nil { t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out) diff --git a/core/types/header_ext.go b/core/types/header_ext.go index 1096777d6f..e680ee7798 100644 --- a/core/types/header_ext.go +++ b/core/types/header_ext.go @@ -23,11 +23,11 @@ func (h *HeaderExtra) DecodeRLP(eth *ethtypes.Header, stream *rlp.Stream) error panic("not implemented") } -func (h *HeaderExtra) MarshalJSON(eth *ethtypes.Header) ([]byte, error) { +func (h *HeaderExtra) EncodeJSON(eth *ethtypes.Header) ([]byte, error) { panic("not implemented") } -func (h *HeaderExtra) UnmarshalJSON(eth *ethtypes.Header, input []byte) error { +func (h *HeaderExtra) DecodeJSON(eth *ethtypes.Header, input []byte) error { panic("not implemented") } diff --git a/go.mod b/go.mod index 0318e08c69..dc675e4f18 100644 --- a/go.mod +++ b/go.mod @@ -136,4 +136,4 @@ require ( rsc.io/tmplfunc v0.0.3 // indirect ) -replace github.com/ava-labs/libevm => github.com/ava-labs/libevm v0.0.0-20250212124953-9c7285a21b71 +replace github.com/ava-labs/libevm => github.com/ava-labs/libevm v0.0.0-20250213164614-19ec675e01c4 diff --git a/go.sum b/go.sum index 9ae4b445f3..890178a227 100644 --- a/go.sum +++ b/go.sum @@ -58,8 +58,8 @@ github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/ava-labs/avalanchego v1.12.1-0.20250107220127-32f58b4fa9c8 h1:qN3MOBHB//Ynhgt5Vys3iVe42Sr0EWSeN18VL3ecXzE= github.com/ava-labs/avalanchego v1.12.1-0.20250107220127-32f58b4fa9c8/go.mod h1:2B7+E5neLvkOr2zursGhebjU26d4AfB7RazPxBs8hHg= -github.com/ava-labs/libevm v0.0.0-20250212124953-9c7285a21b71 h1:C8qlqwg/QPnfJCh7ACTFkfXrMh5Q98revSv0R+PRG88= -github.com/ava-labs/libevm v0.0.0-20250212124953-9c7285a21b71/go.mod h1:xi9AcwLOv3gUYYSuRYxXKVmLMFTSM4g0m4cpvC5X8DU= +github.com/ava-labs/libevm v0.0.0-20250213164614-19ec675e01c4 h1:nk6q9a1XoLp8Gnce8kEl3PpE6Xmpgc3QJKFnyt11M1g= +github.com/ava-labs/libevm v0.0.0-20250213164614-19ec675e01c4/go.mod h1:xi9AcwLOv3gUYYSuRYxXKVmLMFTSM4g0m4cpvC5X8DU= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/scripts/tests.e2e.sh b/scripts/tests.e2e.sh index ad218a1f57..fbdaf9d59d 100755 --- a/scripts/tests.e2e.sh +++ b/scripts/tests.e2e.sh @@ -45,7 +45,7 @@ git checkout -B "test-${AVALANCHE_VERSION}" "${AVALANCHE_VERSION}" echo "updating coreth dependency to point to ${CORETH_PATH}" go mod edit -replace "github.com/ava-labs/coreth=${CORETH_PATH}" -go mod edit -replace "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250212124953-9c7285a21b71" +go mod edit -replace "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250213164614-19ec675e01c4" go mod tidy echo "building avalanchego" From c5296afa12c4919b27f925e1af3c57174288eaa1 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Thu, 13 Feb 2025 12:33:40 -0500 Subject: [PATCH 43/69] Implement `eth_suggestPriceOptions` (#789) --- internal/ethapi/api.coreth.go | 134 +++++++++++++++++++++++++++++ internal/ethapi/api.coreth_test.go | 130 ++++++++++++++++++++++++++++ 2 files changed, 264 insertions(+) create mode 100644 internal/ethapi/api.coreth.go create mode 100644 internal/ethapi/api.coreth_test.go diff --git a/internal/ethapi/api.coreth.go b/internal/ethapi/api.coreth.go new file mode 100644 index 0000000000..07c285c45e --- /dev/null +++ b/internal/ethapi/api.coreth.go @@ -0,0 +1,134 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package ethapi + +import ( + "context" + "fmt" + "math/big" + + "github.com/ava-labs/coreth/params" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/common/math" +) + +const ( + nAVAX = 1_000_000_000 + + minBaseFee = params.EtnaMinBaseFee // 1 nAVAX + maxNormalBaseFee = 100 * nAVAX + + minGasTip = 1 // 1 wei + maxNormalGasTip = 20 * nAVAX + + slowFeeNumerator = 19 // 19/20 = 0.95 + fastFeeNumerator = 21 // 21/20 = 1.05 + feeDenominator = 20 +) + +var ( + bigMinBaseFee = big.NewInt(minBaseFee) + bigMaxNormalBaseFee = big.NewInt(maxNormalBaseFee) + + bigMinGasTip = big.NewInt(minGasTip) + bigMaxNormalGasTip = big.NewInt(maxNormalGasTip) + + bigSlowFeeNumerator = big.NewInt(slowFeeNumerator) + bigFastFeeNumerator = big.NewInt(fastFeeNumerator) + bigFeeDenominator = big.NewInt(feeDenominator) +) + +type Price struct { + GasTip *hexutil.Big `json:"maxPriorityFeePerGas"` + GasFee *hexutil.Big `json:"maxFeePerGas"` +} + +type PriceOptions struct { + Slow *Price `json:"slow"` + Normal *Price `json:"normal"` + Fast *Price `json:"fast"` +} + +// SuggestPriceOptions returns suggestions for what to display to a user for +// current transaction fees. +func (s *EthereumAPI) SuggestPriceOptions(ctx context.Context) (*PriceOptions, error) { + baseFee, err := s.b.EstimateBaseFee(ctx) + if err != nil { + return nil, fmt.Errorf("failed to estimate base fee: %w", err) + } + gasTip, err := s.b.SuggestGasTipCap(ctx) + if err != nil { + return nil, fmt.Errorf("failed to suggest gas tip cap: %w", err) + } + + // If the chain isn't running with dynamic fees, return nil. + if baseFee == nil || gasTip == nil { + return nil, nil + } + + baseFees := calculateFeeSpeeds( + bigMinBaseFee, + baseFee, + bigMaxNormalBaseFee, + ) + gasTips := calculateFeeSpeeds( + bigMinGasTip, + gasTip, + bigMaxNormalGasTip, + ) + slowGasFee := new(big.Int).Add(baseFees.slow, gasTips.slow) + normalGasFee := new(big.Int).Add(baseFees.normal, gasTips.normal) + fastGasFee := new(big.Int).Add(baseFees.fast, gasTips.fast) + return &PriceOptions{ + Slow: &Price{ + GasTip: (*hexutil.Big)(gasTips.slow), + GasFee: (*hexutil.Big)(slowGasFee), + }, + Normal: &Price{ + GasTip: (*hexutil.Big)(gasTips.normal), + GasFee: (*hexutil.Big)(normalGasFee), + }, + Fast: &Price{ + GasTip: (*hexutil.Big)(gasTips.fast), + GasFee: (*hexutil.Big)(fastGasFee), + }, + }, nil +} + +type feeSpeeds struct { + slow *big.Int + normal *big.Int + fast *big.Int +} + +// calculateFeeSpeeds returns the slow, normal, and fast price options for a +// given min, estimate, and max, +// +// slow = max(0.95 * min(estimate, maxFee), minFee) +// normal = min(estimate, maxFee) +// fast = 1.05 * estimate +func calculateFeeSpeeds( + minFee *big.Int, + estimate *big.Int, + maxFee *big.Int, +) feeSpeeds { + // Cap the fee to keep slow and normal options reasonable during fee spikes. + cappedFee := math.BigMin(estimate, maxFee) + + slowFee := new(big.Int).Set(cappedFee) + slowFee.Mul(slowFee, bigSlowFeeNumerator) + slowFee.Div(slowFee, bigFeeDenominator) + slowFee = math.BigMax(slowFee, minFee) + + normalFee := cappedFee + + fastFee := new(big.Int).Set(estimate) + fastFee.Mul(fastFee, bigFastFeeNumerator) + fastFee.Div(fastFee, bigFeeDenominator) + return feeSpeeds{ + slow: slowFee, + normal: normalFee, + fast: fastFee, + } +} diff --git a/internal/ethapi/api.coreth_test.go b/internal/ethapi/api.coreth_test.go new file mode 100644 index 0000000000..e23341a3c3 --- /dev/null +++ b/internal/ethapi/api.coreth_test.go @@ -0,0 +1,130 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package ethapi + +import ( + "context" + "math/big" + "testing" + + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/stretchr/testify/require" +) + +type testSuggestPriceOptionsBackend struct { + Backend // embed the interface to avoid implementing unused methods + + estimateBaseFee *big.Int + suggestGasTipCap *big.Int +} + +func (b *testSuggestPriceOptionsBackend) EstimateBaseFee(context.Context) (*big.Int, error) { + return b.estimateBaseFee, nil +} + +func (b *testSuggestPriceOptionsBackend) SuggestGasTipCap(context.Context) (*big.Int, error) { + return b.suggestGasTipCap, nil +} + +func TestSuggestPriceOptions(t *testing.T) { + tests := []struct { + name string + estimateBaseFee *big.Int + suggestGasTipCap *big.Int + want *PriceOptions + }{ + { + name: "nil_base_fee", + estimateBaseFee: nil, + suggestGasTipCap: common.Big1, + want: nil, + }, + { + name: "nil_tip_cap", + estimateBaseFee: common.Big1, + suggestGasTipCap: nil, + want: nil, + }, + { + name: "minimum_values", + estimateBaseFee: bigMinBaseFee, + suggestGasTipCap: bigMinGasTip, + want: &PriceOptions{ + Slow: newPrice( + minGasTip, + minBaseFee+minGasTip, + ), + Normal: newPrice( + minGasTip, + minBaseFee+minGasTip, + ), + Fast: newPrice( + minGasTip, + (fastFeeNumerator*minBaseFee)/feeDenominator+(fastFeeNumerator*minGasTip)/feeDenominator, + ), + }, + }, + { + name: "maximum_values", + estimateBaseFee: bigMaxNormalBaseFee, + suggestGasTipCap: bigMaxNormalGasTip, + want: &PriceOptions{ + Slow: newPrice( + (slowFeeNumerator*maxNormalGasTip)/feeDenominator, + (slowFeeNumerator*maxNormalBaseFee)/feeDenominator+(slowFeeNumerator*maxNormalGasTip)/feeDenominator, + ), + Normal: newPrice( + maxNormalGasTip, + maxNormalBaseFee+maxNormalGasTip, + ), + Fast: newPrice( + (fastFeeNumerator*maxNormalGasTip)/feeDenominator, + (fastFeeNumerator*maxNormalBaseFee)/feeDenominator+(fastFeeNumerator*maxNormalGasTip)/feeDenominator, + ), + }, + }, + { + name: "double_maximum_values", + estimateBaseFee: big.NewInt(2 * maxNormalBaseFee), + suggestGasTipCap: big.NewInt(2 * maxNormalGasTip), + want: &PriceOptions{ + Slow: newPrice( + (slowFeeNumerator*maxNormalGasTip)/feeDenominator, + (slowFeeNumerator*maxNormalBaseFee)/feeDenominator+(slowFeeNumerator*maxNormalGasTip)/feeDenominator, + ), + Normal: newPrice( + maxNormalGasTip, + maxNormalBaseFee+maxNormalGasTip, + ), + Fast: newPrice( + (fastFeeNumerator*2*maxNormalGasTip)/feeDenominator, + (fastFeeNumerator*2*maxNormalBaseFee)/feeDenominator+(fastFeeNumerator*2*maxNormalGasTip)/feeDenominator, + ), + }, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require := require.New(t) + + backend := &testSuggestPriceOptionsBackend{ + estimateBaseFee: test.estimateBaseFee, + suggestGasTipCap: test.suggestGasTipCap, + } + api := NewEthereumAPI(backend) + + got, err := api.SuggestPriceOptions(context.Background()) + require.NoError(err) + require.Equal(test.want, got) + }) + } +} + +func newPrice(gasTip, gasFee int64) *Price { + return &Price{ + GasTip: (*hexutil.Big)(big.NewInt(gasTip)), + GasFee: (*hexutil.Big)(big.NewInt(gasFee)), + } +} From fca99effa9abd0057c40fccb5b5f4e31d86b9737 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Thu, 13 Feb 2025 12:50:19 -0500 Subject: [PATCH 44/69] Remove `header.Extra` from `EstimateNextBaseFee` (#793) --- consensus/dummy/dynamic_fees.go | 5 +++-- core/txpool/blobpool/blobpool.go | 4 ++-- core/txpool/legacypool/legacypool.go | 2 +- eth/gasprice/gasprice.go | 3 +-- plugin/evm/vm.go | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/consensus/dummy/dynamic_fees.go b/consensus/dummy/dynamic_fees.go index 7402195b9e..38b0ac2ffc 100644 --- a/consensus/dummy/dynamic_fees.go +++ b/consensus/dummy/dynamic_fees.go @@ -169,11 +169,12 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin // If [timestamp] is less than the timestamp of [parent], then it uses the same timestamp as parent. // Warning: This function should only be used in estimation and should not be used when calculating the canonical // base fee for a subsequent block. -func EstimateNextBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uint64) ([]byte, *big.Int, error) { +func EstimateNextBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uint64) (*big.Int, error) { if timestamp < parent.Time { timestamp = parent.Time } - return CalcBaseFee(config, parent, timestamp) + _, baseFee, err := CalcBaseFee(config, parent, timestamp) + return baseFee, err } // selectBigWithinBounds returns [value] if it is within the bounds: diff --git a/core/txpool/blobpool/blobpool.go b/core/txpool/blobpool/blobpool.go index 27f81faed5..3a4b4cd156 100644 --- a/core/txpool/blobpool/blobpool.go +++ b/core/txpool/blobpool/blobpool.go @@ -410,7 +410,7 @@ func (p *BlobPool) Init(gasTip uint64, head *types.Header, reserve txpool.Addres for addr := range p.index { p.recheck(addr, nil) } - _, baseFee, err := dummy.EstimateNextBaseFee( + baseFee, err := dummy.EstimateNextBaseFee( p.chain.Config(), p.head, uint64(time.Now().Unix()), @@ -840,7 +840,7 @@ func (p *BlobPool) Reset(oldHead, newHead *types.Header) { if p.chain.Config().IsCancun(p.head.Number, p.head.Time) { p.limbo.finalize(p.chain.CurrentFinalBlock()) } - _, baseFeeBig, err := dummy.EstimateNextBaseFee( + baseFeeBig, err := dummy.EstimateNextBaseFee( p.chain.Config(), p.head, uint64(time.Now().Unix()), diff --git a/core/txpool/legacypool/legacypool.go b/core/txpool/legacypool/legacypool.go index 8f4a31427e..4e3ea2a323 100644 --- a/core/txpool/legacypool/legacypool.go +++ b/core/txpool/legacypool/legacypool.go @@ -1816,7 +1816,7 @@ func (pool *LegacyPool) updateBaseFee() { // assumes lock is already held func (pool *LegacyPool) updateBaseFeeAt(head *types.Header) error { - _, baseFeeEstimate, err := dummy.EstimateNextBaseFee(pool.chainconfig, head, uint64(time.Now().Unix())) + baseFeeEstimate, err := dummy.EstimateNextBaseFee(pool.chainconfig, head, uint64(time.Now().Unix())) if err != nil { return err } diff --git a/eth/gasprice/gasprice.go b/eth/gasprice/gasprice.go index 31a2c7b554..934c6167c0 100644 --- a/eth/gasprice/gasprice.go +++ b/eth/gasprice/gasprice.go @@ -252,8 +252,7 @@ func (oracle *Oracle) estimateNextBaseFee(ctx context.Context) (*big.Int, error) // If the block does have a baseFee, calculate the next base fee // based on the current time and add it to the tip to estimate the // total gas price estimate. - _, nextBaseFee, err := dummy.EstimateNextBaseFee(oracle.backend.ChainConfig(), header, oracle.clock.Unix()) - return nextBaseFee, err + return dummy.EstimateNextBaseFee(oracle.backend.ChainConfig(), header, oracle.clock.Unix()) } // SuggestPrice returns an estimated price for legacy transactions. diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index d02d4229a7..9b54b2cfdc 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -1587,7 +1587,7 @@ func (vm *VM) verifyTxAtTip(tx *atomic.Tx) error { var nextBaseFee *big.Int timestamp := uint64(vm.clock.Time().Unix()) if vm.chainConfig.IsApricotPhase3(timestamp) { - _, nextBaseFee, err = dummy.EstimateNextBaseFee(vm.chainConfig, parentHeader, timestamp) + nextBaseFee, err = dummy.EstimateNextBaseFee(vm.chainConfig, parentHeader, timestamp) if err != nil { // Return extremely detailed error since CalcBaseFee should never encounter an issue here return fmt.Errorf("failed to calculate base fee with parent timestamp (%d), parent ExtraData: (0x%x), and current timestamp (%d): %w", parentHeader.Time, parentHeader.Extra, timestamp, err) From b9890a7d6be65e2e54364762858a8b3c2471d439 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Thu, 13 Feb 2025 13:25:46 -0500 Subject: [PATCH 45/69] Refactor `BlockGasCost` calculations (#792) --- consensus/dummy/consensus.go | 85 +++++------- consensus/dummy/consensus_test.go | 72 ++++------ consensus/dummy/dynamic_fees.go | 98 +++++--------- consensus/dummy/dynamic_fees_test.go | 102 -------------- plugin/evm/ap4/cost.go | 66 ++++++++++ plugin/evm/ap4/cost_test.go | 77 +++++++++++ plugin/evm/header/block_gas_cost.go | 68 ++++++++++ plugin/evm/header/block_gas_cost_test.go | 161 +++++++++++++++++++++++ utils/numbers.go | 9 ++ utils/numbers_test.go | 51 +++++++ 10 files changed, 524 insertions(+), 265 deletions(-) create mode 100644 plugin/evm/ap4/cost.go create mode 100644 plugin/evm/ap4/cost_test.go create mode 100644 plugin/evm/header/block_gas_cost.go create mode 100644 plugin/evm/header/block_gas_cost_test.go create mode 100644 utils/numbers_test.go diff --git a/consensus/dummy/consensus.go b/consensus/dummy/consensus.go index 7bfc69d08d..34a13d3075 100644 --- a/consensus/dummy/consensus.go +++ b/consensus/dummy/consensus.go @@ -17,6 +17,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/trie" + "github.com/ava-labs/coreth/utils" "github.com/ethereum/go-ethereum/common" customheader "github.com/ava-labs/coreth/plugin/evm/header" @@ -28,7 +29,6 @@ var ( errInvalidBlockTime = errors.New("timestamp less than parent's") errUnclesUnsupported = errors.New("uncles unsupported") errBlockGasCostNil = errors.New("block gas cost is nil") - errBlockGasCostTooLarge = errors.New("block gas cost is not uint64") errBaseFeeNil = errors.New("base fee is nil") errExtDataGasUsedNil = errors.New("extDataGasUsed is nil") errExtDataGasUsedTooLarge = errors.New("extDataGasUsed is not uint64") @@ -180,27 +180,15 @@ func (eng *DummyEngine) verifyHeaderGasFields(config *params.ChainConfig, header } // Enforce BlockGasCost constraints - blockGasCostStep := ApricotPhase4BlockGasCostStep - if config.IsApricotPhase5(header.Time) { - blockGasCostStep = ApricotPhase5BlockGasCostStep - } - expectedBlockGasCost := calcBlockGasCost( - ApricotPhase4TargetBlockRate, - ApricotPhase4MinBlockGasCost, - ApricotPhase4MaxBlockGasCost, - blockGasCostStep, - parent.BlockGasCost, - parent.Time, header.Time, + expectedBlockGasCost := customheader.BlockGasCost( + config, + parent, + header.Time, ) - if header.BlockGasCost == nil { - return errBlockGasCostNil - } - if !header.BlockGasCost.IsUint64() { - return errBlockGasCostTooLarge - } - if header.BlockGasCost.Cmp(expectedBlockGasCost) != 0 { + if !utils.BigEqualUint64(header.BlockGasCost, expectedBlockGasCost) { return fmt.Errorf("invalid block gas cost: have %d, want %d", header.BlockGasCost, expectedBlockGasCost) } + // ExtDataGasUsed correctness is checked during block validation // (when the validator has access to the block contents) if header.ExtDataGasUsed == nil { @@ -387,7 +375,10 @@ func (eng *DummyEngine) Finalize(chain consensus.ChainHeaderReader, block *types return err } } - if chain.Config().IsApricotPhase4(block.Time()) { + + config := chain.Config() + timestamp := block.Time() + if config.IsApricotPhase4(timestamp) { // Validate extDataGasUsed and BlockGasCost match expectations // // NOTE: This is a duplicate check of what is already performed in @@ -398,28 +389,22 @@ func (eng *DummyEngine) Finalize(chain consensus.ChainHeaderReader, block *types if blockExtDataGasUsed := block.ExtDataGasUsed(); blockExtDataGasUsed == nil || !blockExtDataGasUsed.IsUint64() || blockExtDataGasUsed.Cmp(extDataGasUsed) != 0 { return fmt.Errorf("invalid extDataGasUsed: have %d, want %d", blockExtDataGasUsed, extDataGasUsed) } - blockGasCostStep := ApricotPhase4BlockGasCostStep - if chain.Config().IsApricotPhase5(block.Time()) { - blockGasCostStep = ApricotPhase5BlockGasCostStep - } - // Calculate the expected blockGasCost for this block. - // Note: this is a deterministic transtion that defines an exact block fee for this block. - blockGasCost := calcBlockGasCost( - ApricotPhase4TargetBlockRate, - ApricotPhase4MinBlockGasCost, - ApricotPhase4MaxBlockGasCost, - blockGasCostStep, - parent.BlockGasCost, - parent.Time, block.Time(), + + // Verify the BlockGasCost set in the header matches the expected value. + blockGasCost := block.BlockGasCost() + expectedBlockGasCost := customheader.BlockGasCost( + config, + parent, + timestamp, ) - // Verify the BlockGasCost set in the header matches the calculated value. - if blockBlockGasCost := block.BlockGasCost(); blockBlockGasCost == nil || !blockBlockGasCost.IsUint64() || blockBlockGasCost.Cmp(blockGasCost) != 0 { - return fmt.Errorf("invalid blockGasCost: have %d, want %d", blockBlockGasCost, blockGasCost) + if !utils.BigEqualUint64(blockGasCost, expectedBlockGasCost) { + return fmt.Errorf("invalid blockGasCost: have %d, want %d", blockGasCost, expectedBlockGasCost) } + // Verify the block fee was paid. if err := eng.verifyBlockFee( block.BaseFee(), - block.BlockGasCost(), + blockGasCost, block.Transactions(), receipts, contribution, @@ -445,24 +430,22 @@ func (eng *DummyEngine) FinalizeAndAssemble(chain consensus.ChainHeaderReader, h return nil, err } } - if chain.Config().IsApricotPhase4(header.Time) { + + config := chain.Config() + if config.IsApricotPhase4(header.Time) { header.ExtDataGasUsed = extDataGasUsed if header.ExtDataGasUsed == nil { header.ExtDataGasUsed = new(big.Int).Set(common.Big0) } - blockGasCostStep := ApricotPhase4BlockGasCostStep - if chain.Config().IsApricotPhase5(header.Time) { - blockGasCostStep = ApricotPhase5BlockGasCostStep - } + // Calculate the required block gas cost for this block. - header.BlockGasCost = calcBlockGasCost( - ApricotPhase4TargetBlockRate, - ApricotPhase4MinBlockGasCost, - ApricotPhase4MaxBlockGasCost, - blockGasCostStep, - parent.BlockGasCost, - parent.Time, header.Time, + blockGasCost := customheader.BlockGasCost( + config, + parent, + header.Time, ) + header.BlockGasCost = new(big.Int).SetUint64(blockGasCost) + // Verify that this block covers the block fee. if err := eng.verifyBlockFee( header.BaseFee, @@ -475,12 +458,12 @@ func (eng *DummyEngine) FinalizeAndAssemble(chain consensus.ChainHeaderReader, h } } // commit the final state root - header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) + header.Root = state.IntermediateRoot(config.IsEIP158(header.Number)) // 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), + extraData, config.IsApricotPhase1(header.Time), ), nil } diff --git a/consensus/dummy/consensus_test.go b/consensus/dummy/consensus_test.go index 64a8439817..418c4ecc3f 100644 --- a/consensus/dummy/consensus_test.go +++ b/consensus/dummy/consensus_test.go @@ -9,24 +9,25 @@ import ( "testing" "github.com/ava-labs/coreth/core/types" + "github.com/ava-labs/coreth/plugin/evm/ap4" + "github.com/ava-labs/coreth/plugin/evm/header" "github.com/ethereum/go-ethereum/common" ) func TestVerifyBlockFee(t *testing.T) { tests := map[string]struct { - baseFee *big.Int - parentBlockGasCost *big.Int - parentTime, currentTime uint64 - txs []*types.Transaction - receipts []*types.Receipt - extraStateContribution *big.Int - shouldErr bool + baseFee *big.Int + parentBlockGasCost *big.Int + timeElapsed uint64 + txs []*types.Transaction + receipts []*types.Receipt + extraStateContribution *big.Int + shouldErr bool }{ "tx only base fee": { baseFee: big.NewInt(100), parentBlockGasCost: big.NewInt(0), - parentTime: 10, - currentTime: 10, + timeElapsed: 0, txs: []*types.Transaction{ types.NewTransaction(0, common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"), big.NewInt(0), 100, big.NewInt(100), nil), }, @@ -39,8 +40,7 @@ func TestVerifyBlockFee(t *testing.T) { "tx covers exactly block fee": { baseFee: big.NewInt(100), parentBlockGasCost: big.NewInt(0), - parentTime: 10, - currentTime: 10, + timeElapsed: 0, txs: []*types.Transaction{ types.NewTransaction(0, common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"), big.NewInt(0), 100_000, big.NewInt(200), nil), }, @@ -53,8 +53,7 @@ func TestVerifyBlockFee(t *testing.T) { "txs share block fee": { baseFee: big.NewInt(100), parentBlockGasCost: big.NewInt(0), - parentTime: 10, - currentTime: 10, + timeElapsed: 0, txs: []*types.Transaction{ types.NewTransaction(0, common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"), big.NewInt(0), 100_000, big.NewInt(200), nil), types.NewTransaction(1, common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"), big.NewInt(0), 100_000, big.NewInt(100), nil), @@ -69,8 +68,7 @@ func TestVerifyBlockFee(t *testing.T) { "txs split block fee": { baseFee: big.NewInt(100), parentBlockGasCost: big.NewInt(0), - parentTime: 10, - currentTime: 10, + timeElapsed: 0, txs: []*types.Transaction{ types.NewTransaction(0, common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"), big.NewInt(0), 100_000, big.NewInt(150), nil), types.NewTransaction(1, common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"), big.NewInt(0), 100_000, big.NewInt(150), nil), @@ -85,8 +83,7 @@ func TestVerifyBlockFee(t *testing.T) { "split block fee with extra state contribution": { baseFee: big.NewInt(100), parentBlockGasCost: big.NewInt(0), - parentTime: 10, - currentTime: 10, + timeElapsed: 0, txs: []*types.Transaction{ types.NewTransaction(0, common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"), big.NewInt(0), 100_000, big.NewInt(150), nil), }, @@ -99,8 +96,7 @@ func TestVerifyBlockFee(t *testing.T) { "extra state contribution insufficient": { baseFee: big.NewInt(100), parentBlockGasCost: big.NewInt(0), - parentTime: 10, - currentTime: 10, + timeElapsed: 0, txs: nil, receipts: nil, extraStateContribution: big.NewInt(9_999_999), @@ -109,8 +105,7 @@ func TestVerifyBlockFee(t *testing.T) { "negative extra state contribution": { baseFee: big.NewInt(100), parentBlockGasCost: big.NewInt(0), - parentTime: 10, - currentTime: 10, + timeElapsed: 0, txs: nil, receipts: nil, extraStateContribution: big.NewInt(-1), @@ -119,8 +114,7 @@ func TestVerifyBlockFee(t *testing.T) { "extra state contribution covers block fee": { baseFee: big.NewInt(100), parentBlockGasCost: big.NewInt(0), - parentTime: 10, - currentTime: 10, + timeElapsed: 0, txs: nil, receipts: nil, extraStateContribution: big.NewInt(10_000_000), @@ -129,8 +123,7 @@ func TestVerifyBlockFee(t *testing.T) { "extra state contribution covers more than block fee": { baseFee: big.NewInt(100), parentBlockGasCost: big.NewInt(0), - parentTime: 10, - currentTime: 10, + timeElapsed: 0, txs: nil, receipts: nil, extraStateContribution: big.NewInt(10_000_001), @@ -139,8 +132,7 @@ func TestVerifyBlockFee(t *testing.T) { "tx only base fee after full time window": { baseFee: big.NewInt(100), parentBlockGasCost: big.NewInt(500_000), - parentTime: 10, - currentTime: 22, // 2s target + 10 + timeElapsed: ap4.TargetBlockRate + 10, txs: []*types.Transaction{ types.NewTransaction(0, common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"), big.NewInt(0), 100, big.NewInt(100), nil), }, @@ -153,8 +145,7 @@ func TestVerifyBlockFee(t *testing.T) { "tx only base fee after large time window": { baseFee: big.NewInt(100), parentBlockGasCost: big.NewInt(100_000), - parentTime: 0, - currentTime: math.MaxUint64, + timeElapsed: math.MaxUint64, txs: []*types.Transaction{ types.NewTransaction(0, common.HexToAddress("7ef5a6135f1fd6a02593eedc869c6d41d934aef8"), big.NewInt(0), 100, big.NewInt(100), nil), }, @@ -164,30 +155,19 @@ func TestVerifyBlockFee(t *testing.T) { extraStateContribution: nil, shouldErr: false, }, - "parent time > current time": { - baseFee: big.NewInt(100), - parentBlockGasCost: big.NewInt(0), - parentTime: 11, - currentTime: 10, - txs: nil, - receipts: nil, - extraStateContribution: big.NewInt(10_000_000), - shouldErr: false, - }, } for name, test := range tests { t.Run(name, func(t *testing.T) { - blockGasCost := calcBlockGasCost( - ApricotPhase4TargetBlockRate, - ApricotPhase4MinBlockGasCost, - ApricotPhase4MaxBlockGasCost, - ApricotPhase4BlockGasCostStep, + blockGasCost := header.BlockGasCostWithStep( test.parentBlockGasCost, - test.parentTime, test.currentTime, + ap4.BlockGasCostStep, + test.timeElapsed, ) + bigBlockGasCost := new(big.Int).SetUint64(blockGasCost) + engine := NewFaker() - if err := engine.verifyBlockFee(test.baseFee, blockGasCost, test.txs, test.receipts, test.extraStateContribution); err != nil { + if err := engine.verifyBlockFee(test.baseFee, bigBlockGasCost, test.txs, test.receipts, test.extraStateContribution); err != nil { if !test.shouldErr { t.Fatalf("Unexpected error: %s", err) } diff --git a/consensus/dummy/dynamic_fees.go b/consensus/dummy/dynamic_fees.go index 38b0ac2ffc..eab34a54fb 100644 --- a/consensus/dummy/dynamic_fees.go +++ b/consensus/dummy/dynamic_fees.go @@ -9,10 +9,14 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/ap4" + "github.com/ava-labs/coreth/plugin/evm/header" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/math" ) +const ApricotPhase3BlockGasFee = 1_000_000 + var ( ApricotPhase3MinBaseFee = big.NewInt(params.ApricotPhase3MinBaseFee) ApricotPhase3MaxBaseFee = big.NewInt(params.ApricotPhase3MaxBaseFee) @@ -23,13 +27,6 @@ var ( ApricotPhase4BaseFeeChangeDenominator = new(big.Int).SetUint64(params.ApricotPhase4BaseFeeChangeDenominator) ApricotPhase5BaseFeeChangeDenominator = new(big.Int).SetUint64(params.ApricotPhase5BaseFeeChangeDenominator) - - ApricotPhase3BlockGasFee uint64 = 1_000_000 - ApricotPhase4MinBlockGasCost = new(big.Int).Set(common.Big0) - ApricotPhase4MaxBlockGasCost = big.NewInt(1_000_000) - ApricotPhase4BlockGasCostStep = big.NewInt(50_000) - ApricotPhase4TargetBlockRate uint64 = 2 // in seconds - ApricotPhase5BlockGasCostStep = big.NewInt(200_000) ) // CalcBaseFee takes the previous header and the timestamp of its child block @@ -56,6 +53,11 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin return nil, nil, err } + if timestamp < parent.Time { + return nil, nil, fmt.Errorf("cannot calculate base fee for timestamp %d prior to parent timestamp %d", timestamp, parent.Time) + } + timeElapsed := timestamp - parent.Time + // If AP5, use a less responsive BaseFeeChangeDenominator and a higher gas // block limit var ( @@ -83,14 +85,16 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin case isApricotPhase4: // The blockGasCost is paid by the effective tips in the block using // the block's value of baseFee. - blockGasCost = calcBlockGasCost( - ApricotPhase4TargetBlockRate, - ApricotPhase4MinBlockGasCost, - ApricotPhase4MaxBlockGasCost, - ApricotPhase4BlockGasCostStep, + // + // Although the child block may be in AP5 here, the blockGasCost is + // still calculated using the AP4 step. This is different than the + // actual BlockGasCost calculation used for the child block. This + // behavior is kept to preserve the original behavior of this function. + blockGasCost = header.BlockGasCostWithStep( parent.BlockGasCost, - parent.Time, timestamp, - ).Uint64() + ap4.BlockGasCostStep, + timeElapsed, + ) // On the boundary of AP3 and AP4 or at the start of a new network, the // parent may not have a populated ExtDataGasUsed. @@ -104,14 +108,9 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin // Compute the new state of the gas rolling window. dynamicFeeWindow.Add(parent.GasUsed, parentExtraStateGasUsed, blockGasCost) - if timestamp < parent.Time { - return nil, nil, fmt.Errorf("cannot calculate base fee for timestamp %d prior to parent timestamp %d", timestamp, parent.Time) - } - roll := timestamp - parent.Time - - // roll the window over by the difference between the timestamps to generate - // the new rollup window. - dynamicFeeWindow.Shift(roll) + // roll the window over by the timeElapsed to generate the new rollup + // window. + dynamicFeeWindow.Shift(timeElapsed) dynamicFeeWindowBytes := dynamicFeeWindow.Bytes() // Calculate the amount of gas consumed within the rollup window. @@ -138,13 +137,17 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin num.Div(num, parentGasTargetBig) num.Div(num, baseFeeChangeDenominator) baseFeeDelta := math.BigMax(num, common.Big1) - // If [roll] is greater than [rollupWindow], apply the state transition to the base fee to account - // for the interval during which no blocks were produced. - // We use roll/rollupWindow, so that the transition is applied for every [rollupWindow] seconds - // that has elapsed between the parent and this block. - if roll > params.RollupWindow { - // Note: roll/rollupWindow must be greater than 1 since we've checked that roll > rollupWindow - baseFeeDelta = new(big.Int).Mul(baseFeeDelta, new(big.Int).SetUint64(roll/params.RollupWindow)) + // If timeElapsed is greater than [params.RollupWindow], apply the + // state transition to the base fee to account for the interval during + // which no blocks were produced. + // + // We use timeElapsed/params.RollupWindow, so that the transition is + // applied for every [params.RollupWindow] seconds that has elapsed + // between the parent and this block. + if timeElapsed > params.RollupWindow { + // Note: timeElapsed/params.RollupWindow must be at least 1 since + // we've checked that timeElapsed > params.RollupWindow + baseFeeDelta = new(big.Int).Mul(baseFeeDelta, new(big.Int).SetUint64(timeElapsed/params.RollupWindow)) } baseFee.Sub(baseFee, baseFeeDelta) } @@ -191,43 +194,6 @@ func selectBigWithinBounds(lowerBound, value, upperBound *big.Int) *big.Int { } } -// calcBlockGasCost calculates the required block gas cost. If [parentTime] -// > [currentTime], the timeElapsed will be treated as 0. -func calcBlockGasCost( - targetBlockRate uint64, - minBlockGasCost *big.Int, - maxBlockGasCost *big.Int, - blockGasCostStep *big.Int, - parentBlockGasCost *big.Int, - parentTime, currentTime uint64, -) *big.Int { - // Handle AP3/AP4 boundary by returning the minimum value as the boundary. - if parentBlockGasCost == nil { - return new(big.Int).Set(minBlockGasCost) - } - - // Treat an invalid parent/current time combination as 0 elapsed time. - var timeElapsed uint64 - if parentTime <= currentTime { - timeElapsed = currentTime - parentTime - } - - var blockGasCost *big.Int - if timeElapsed < targetBlockRate { - blockGasCostDelta := new(big.Int).Mul(blockGasCostStep, new(big.Int).SetUint64(targetBlockRate-timeElapsed)) - blockGasCost = new(big.Int).Add(parentBlockGasCost, blockGasCostDelta) - } else { - blockGasCostDelta := new(big.Int).Mul(blockGasCostStep, new(big.Int).SetUint64(timeElapsed-targetBlockRate)) - blockGasCost = new(big.Int).Sub(parentBlockGasCost, blockGasCostDelta) - } - - blockGasCost = selectBigWithinBounds(minBlockGasCost, blockGasCost, maxBlockGasCost) - if !blockGasCost.IsUint64() { - blockGasCost = new(big.Int).SetUint64(math.MaxUint64) - } - return blockGasCost -} - // MinRequiredTip is the estimated minimum tip a transaction would have // needed to pay to be included in a given block (assuming it paid a tip // proportional to its gas usage). In reality, there is no minimum tip that diff --git a/consensus/dummy/dynamic_fees_test.go b/consensus/dummy/dynamic_fees_test.go index 6207c01ed6..5ccb0a1f16 100644 --- a/consensus/dummy/dynamic_fees_test.go +++ b/consensus/dummy/dynamic_fees_test.go @@ -313,108 +313,6 @@ func TestCalcBaseFeeAP4(t *testing.T) { } } -func TestCalcBlockGasCost(t *testing.T) { - tests := map[string]struct { - parentBlockGasCost *big.Int - parentTime, currentTime uint64 - - expected *big.Int - }{ - "Nil parentBlockGasCost": { - parentBlockGasCost: nil, - parentTime: 1, - currentTime: 1, - expected: ApricotPhase4MinBlockGasCost, - }, - "Same timestamp from 0": { - parentBlockGasCost: big.NewInt(0), - parentTime: 1, - currentTime: 1, - expected: big.NewInt(100_000), - }, - "1s from 0": { - parentBlockGasCost: big.NewInt(0), - parentTime: 1, - currentTime: 2, - expected: big.NewInt(50_000), - }, - "Same timestamp from non-zero": { - parentBlockGasCost: big.NewInt(50_000), - parentTime: 1, - currentTime: 1, - expected: big.NewInt(150_000), - }, - "0s Difference (MAX)": { - parentBlockGasCost: big.NewInt(1_000_000), - parentTime: 1, - currentTime: 1, - expected: big.NewInt(1_000_000), - }, - "1s Difference (MAX)": { - parentBlockGasCost: big.NewInt(1_000_000), - parentTime: 1, - currentTime: 2, - expected: big.NewInt(1_000_000), - }, - "2s Difference": { - parentBlockGasCost: big.NewInt(900_000), - parentTime: 1, - currentTime: 3, - expected: big.NewInt(900_000), - }, - "3s Difference": { - parentBlockGasCost: big.NewInt(1_000_000), - parentTime: 1, - currentTime: 4, - expected: big.NewInt(950_000), - }, - "10s Difference": { - parentBlockGasCost: big.NewInt(1_000_000), - parentTime: 1, - currentTime: 11, - expected: big.NewInt(600_000), - }, - "20s Difference": { - parentBlockGasCost: big.NewInt(1_000_000), - parentTime: 1, - currentTime: 21, - expected: big.NewInt(100_000), - }, - "22s Difference": { - parentBlockGasCost: big.NewInt(1_000_000), - parentTime: 1, - currentTime: 23, - expected: big.NewInt(0), - }, - "23s Difference": { - parentBlockGasCost: big.NewInt(1_000_000), - parentTime: 1, - currentTime: 24, - expected: big.NewInt(0), - }, - "-1s Difference": { - parentBlockGasCost: big.NewInt(50_000), - parentTime: 1, - currentTime: 0, - expected: big.NewInt(150_000), - }, - } - - for name, test := range tests { - t.Run(name, func(t *testing.T) { - assert.Zero(t, test.expected.Cmp(calcBlockGasCost( - ApricotPhase4TargetBlockRate, - ApricotPhase4MinBlockGasCost, - ApricotPhase4MaxBlockGasCost, - ApricotPhase4BlockGasCostStep, - test.parentBlockGasCost, - test.parentTime, - test.currentTime, - ))) - }) - } -} - func TestDynamicFeesEtna(t *testing.T) { require := require.New(t) header := &types.Header{ diff --git a/plugin/evm/ap4/cost.go b/plugin/evm/ap4/cost.go new file mode 100644 index 0000000000..396aaa06b4 --- /dev/null +++ b/plugin/evm/ap4/cost.go @@ -0,0 +1,66 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +// AP4 implements the block gas cost logic activated by the Apricot Phase 4 +// upgrade. +package ap4 + +import ( + "math" + + safemath "github.com/ava-labs/avalanchego/utils/math" +) + +const ( + MinBlockGasCost = 0 + MaxBlockGasCost = 1_000_000 + TargetBlockRate = 2 // in seconds + + // BlockGasCostStep is the rate at which the block gas cost changes per + // second. + // + // This value was modified by the Apricot Phase 5 upgrade. + BlockGasCostStep = 50_000 +) + +// BlockGasCost calculates the required block gas cost. +// +// cost = parentCost + step * (TargetBlockRate - timeElapsed) +// +// The returned cost is clamped to [MinBlockGasCost, MaxBlockGasCost]. +func BlockGasCost( + parentCost uint64, + step uint64, + timeElapsed uint64, +) uint64 { + deviation := safemath.AbsDiff(TargetBlockRate, timeElapsed) + change, err := safemath.Mul(step, deviation) + if err != nil { + change = math.MaxUint64 + } + + var ( + op = safemath.Add[uint64] + defaultCost uint64 = MaxBlockGasCost + ) + if timeElapsed > TargetBlockRate { + op = safemath.Sub + defaultCost = MinBlockGasCost + } + + cost, err := op(parentCost, change) + if err != nil { + cost = defaultCost + } + + switch { + case cost < MinBlockGasCost: + // This is technically dead code because [MinBlockGasCost] is 0, but it + // makes the code more clear. + return MinBlockGasCost + case cost > MaxBlockGasCost: + return MaxBlockGasCost + default: + return cost + } +} diff --git a/plugin/evm/ap4/cost_test.go b/plugin/evm/ap4/cost_test.go new file mode 100644 index 0000000000..87e8edece1 --- /dev/null +++ b/plugin/evm/ap4/cost_test.go @@ -0,0 +1,77 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package ap4 + +import ( + "math" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBlockGasCost(t *testing.T) { + tests := []struct { + name string + parentCost uint64 + step uint64 + timeElapsed uint64 + want uint64 + }{ + { + name: "timeElapsed_under_target", + parentCost: 500, + step: 100, + timeElapsed: 0, + want: 500 + 100*TargetBlockRate, + }, + { + name: "timeElapsed_at_target", + parentCost: 3, + step: 100, + timeElapsed: TargetBlockRate, + want: 3, + }, + { + name: "timeElapsed_over_target", + parentCost: 500, + step: 100, + timeElapsed: 2 * TargetBlockRate, + want: 500 - 100*TargetBlockRate, + }, + { + name: "change_overflow", + parentCost: 500, + step: math.MaxUint64, + timeElapsed: 0, + want: MaxBlockGasCost, + }, + { + name: "cost_overflow", + parentCost: math.MaxUint64, + step: 1, + timeElapsed: 0, + want: MaxBlockGasCost, + }, + { + name: "clamp_to_max", + parentCost: MaxBlockGasCost, + step: 100, + timeElapsed: TargetBlockRate - 1, + want: MaxBlockGasCost, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require.Equal( + t, + test.want, + BlockGasCost( + test.parentCost, + test.step, + test.timeElapsed, + ), + ) + }) + } +} diff --git a/plugin/evm/header/block_gas_cost.go b/plugin/evm/header/block_gas_cost.go new file mode 100644 index 0000000000..468c7d0ba5 --- /dev/null +++ b/plugin/evm/header/block_gas_cost.go @@ -0,0 +1,68 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package header + +import ( + "math/big" + + "github.com/ava-labs/coreth/core/types" + "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/ap4" +) + +// ApricotPhase5BlockGasCostStep is the rate at which the block gas cost changes +// per second as of the Apricot Phase 5 upgrade. +// +// This value modifies the previously used [ap4.BlockGasCostStep]. +const ApricotPhase5BlockGasCostStep = 200_000 + +// BlockGasCost calculates the required block gas cost based on the parent +// header and the timestamp of the new block. +func BlockGasCost( + config *params.ChainConfig, + parent *types.Header, + timestamp uint64, +) uint64 { + step := uint64(ap4.BlockGasCostStep) + if config.IsApricotPhase5(timestamp) { + step = ApricotPhase5BlockGasCostStep + } + // Treat an invalid parent/current time combination as 0 elapsed time. + // + // TODO: Does it even make sense to handle this? The timestamp should be + // verified to ensure this never happens. + var timeElapsed uint64 + if parent.Time <= timestamp { + timeElapsed = timestamp - parent.Time + } + return BlockGasCostWithStep( + parent.BlockGasCost, + step, + timeElapsed, + ) +} + +// BlockGasCostWithStep calculates the required block gas cost based on the +// parent cost and the time difference between the parent block and new block. +// +// This is a helper function that allows the caller to manually specify the step +// value to use. +func BlockGasCostWithStep( + parentCost *big.Int, + step uint64, + timeElapsed uint64, +) uint64 { + // Handle AP3/AP4 boundary by returning the minimum value as the boundary. + if parentCost == nil { + return ap4.MinBlockGasCost + } + + // [ap4.MaxBlockGasCost] is <= MaxUint64, so we know that parentCost is + // always going to be a valid uint64. + return ap4.BlockGasCost( + parentCost.Uint64(), + step, + timeElapsed, + ) +} diff --git a/plugin/evm/header/block_gas_cost_test.go b/plugin/evm/header/block_gas_cost_test.go new file mode 100644 index 0000000000..ec67ca1953 --- /dev/null +++ b/plugin/evm/header/block_gas_cost_test.go @@ -0,0 +1,161 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package header + +import ( + "math/big" + "testing" + + "github.com/ava-labs/coreth/core/types" + "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/ap4" + "github.com/ava-labs/coreth/utils" + "github.com/stretchr/testify/assert" +) + +func TestBlockGasCost(t *testing.T) { + tests := []struct { + name string + apricotPhase5BlockTimestamp *uint64 + parentTime uint64 + parentCost *big.Int + timestamp uint64 + expected uint64 + }{ + { + name: "normal_ap4", + parentTime: 10, + parentCost: big.NewInt(ap4.MaxBlockGasCost), + timestamp: 10 + ap4.TargetBlockRate + 1, + expected: ap4.MaxBlockGasCost - ap4.BlockGasCostStep, + }, + { + name: "normal_ap5", + apricotPhase5BlockTimestamp: utils.NewUint64(0), + parentTime: 10, + parentCost: big.NewInt(ap4.MaxBlockGasCost), + timestamp: 10 + ap4.TargetBlockRate + 1, + expected: ap4.MaxBlockGasCost - ApricotPhase5BlockGasCostStep, + }, + { + name: "negative_time_elapsed", + parentTime: 10, + parentCost: big.NewInt(ap4.MinBlockGasCost), + timestamp: 9, + expected: ap4.MinBlockGasCost + ap4.BlockGasCostStep*ap4.TargetBlockRate, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + config := ¶ms.ChainConfig{ + NetworkUpgrades: params.NetworkUpgrades{ + ApricotPhase5BlockTimestamp: test.apricotPhase5BlockTimestamp, + }, + } + parent := &types.Header{ + Time: test.parentTime, + BlockGasCost: test.parentCost, + } + + assert.Equal(t, test.expected, BlockGasCost( + config, + parent, + test.timestamp, + )) + }) + } +} + +func TestBlockGasCostWithStep(t *testing.T) { + tests := []struct { + name string + parentCost *big.Int + timeElapsed uint64 + expected uint64 + }{ + { + name: "nil_parentCost", + parentCost: nil, + timeElapsed: 0, + expected: ap4.MinBlockGasCost, + }, + { + name: "timeElapsed_0", + parentCost: big.NewInt(0), + timeElapsed: 0, + expected: ap4.TargetBlockRate * ap4.BlockGasCostStep, + }, + { + name: "timeElapsed_1", + parentCost: big.NewInt(0), + timeElapsed: 1, + expected: (ap4.TargetBlockRate - 1) * ap4.BlockGasCostStep, + }, + { + name: "timeElapsed_0_with_parentCost", + parentCost: big.NewInt(50_000), + timeElapsed: 0, + expected: 50_000 + ap4.TargetBlockRate*ap4.BlockGasCostStep, + }, + { + name: "timeElapsed_0_with_max_parentCost", + parentCost: big.NewInt(ap4.MaxBlockGasCost), + timeElapsed: 0, + expected: ap4.MaxBlockGasCost, + }, + { + name: "timeElapsed_1_with_max_parentCost", + parentCost: big.NewInt(ap4.MaxBlockGasCost), + timeElapsed: 1, + expected: ap4.MaxBlockGasCost, + }, + { + name: "timeElapsed_at_target", + parentCost: big.NewInt(900_000), + timeElapsed: ap4.TargetBlockRate, + expected: 900_000, + }, + { + name: "timeElapsed_over_target_3", + parentCost: big.NewInt(ap4.MaxBlockGasCost), + timeElapsed: 3, + expected: ap4.MaxBlockGasCost - (3-ap4.TargetBlockRate)*ap4.BlockGasCostStep, + }, + { + name: "timeElapsed_over_target_10", + parentCost: big.NewInt(ap4.MaxBlockGasCost), + timeElapsed: 10, + expected: ap4.MaxBlockGasCost - (10-ap4.TargetBlockRate)*ap4.BlockGasCostStep, + }, + { + name: "timeElapsed_over_target_20", + parentCost: big.NewInt(ap4.MaxBlockGasCost), + timeElapsed: 20, + expected: ap4.MaxBlockGasCost - (20-ap4.TargetBlockRate)*ap4.BlockGasCostStep, + }, + { + name: "timeElapsed_over_target_22", + parentCost: big.NewInt(ap4.MaxBlockGasCost), + timeElapsed: 22, + expected: ap4.MaxBlockGasCost - (22-ap4.TargetBlockRate)*ap4.BlockGasCostStep, + }, + { + name: "timeElapsed_large_clamped_to_0", + parentCost: big.NewInt(ap4.MaxBlockGasCost), + timeElapsed: 23, + expected: 0, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + assert.Equal(t, test.expected, BlockGasCostWithStep( + test.parentCost, + ap4.BlockGasCostStep, + test.timeElapsed, + )) + }) + } +} diff --git a/utils/numbers.go b/utils/numbers.go index a6be2341fb..4843716ddb 100644 --- a/utils/numbers.go +++ b/utils/numbers.go @@ -4,6 +4,7 @@ package utils import ( + "math/big" "time" ) @@ -27,3 +28,11 @@ func Uint64PtrEqual(x, y *uint64) bool { } return *x == *y } + +// BigEqualUint64 returns true if a is equal to b. If a is nil or not a uint64, +// it returns false. +func BigEqualUint64(a *big.Int, b uint64) bool { + return a != nil && + a.IsUint64() && + a.Uint64() == b +} diff --git a/utils/numbers_test.go b/utils/numbers_test.go new file mode 100644 index 0000000000..e2f6750247 --- /dev/null +++ b/utils/numbers_test.go @@ -0,0 +1,51 @@ +// (c) 2025, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package utils + +import ( + "math/big" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestBigEqualUint64(t *testing.T) { + tests := []struct { + name string + a *big.Int + b uint64 + want bool + }{ + { + name: "nil", + a: nil, + b: 0, + want: false, + }, + { + name: "not_uint64", + a: big.NewInt(-1), + b: 0, + want: false, + }, + { + name: "equal", + a: big.NewInt(1), + b: 1, + want: true, + }, + { + name: "not_equal", + a: big.NewInt(1), + b: 2, + want: false, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := BigEqualUint64(test.a, test.b) + assert.Equal(t, test.want, got) + }) + } +} From e50d59d8361e085b6ba8c6f5b42cbbcbc6187d06 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Thu, 13 Feb 2025 14:27:40 -0500 Subject: [PATCH 46/69] Cleanup header gas verification (#794) --- consensus/dummy/consensus.go | 26 +++++++------------- consensus/dummy/dynamic_fees.go | 7 ++++-- utils/numbers.go | 9 +++++++ utils/numbers_test.go | 42 +++++++++++++++++++++++++++++++++ 4 files changed, 64 insertions(+), 20 deletions(-) diff --git a/consensus/dummy/consensus.go b/consensus/dummy/consensus.go index 34a13d3075..f3fd98c075 100644 --- a/consensus/dummy/consensus.go +++ b/consensus/dummy/consensus.go @@ -10,6 +10,7 @@ import ( "math/big" "time" + "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/coreth/consensus" "github.com/ava-labs/coreth/consensus/misc/eip4844" @@ -131,13 +132,9 @@ func (eng *DummyEngine) verifyHeaderGasFields(config *params.ChainConfig, header } } else { // Verify that the gas limit remains within allowed bounds - diff := int64(parent.GasLimit) - int64(header.GasLimit) - if diff < 0 { - diff *= -1 - } + diff := math.AbsDiff(parent.GasLimit, header.GasLimit) limit := parent.GasLimit / params.GasLimitBoundDivisor - - if uint64(diff) >= limit || header.GasLimit < params.MinGasLimit { + if diff >= limit || header.GasLimit < params.MinGasLimit { return fmt.Errorf("invalid gas limit: have %d, want %d += %d", header.GasLimit, parent.GasLimit, limit) } } @@ -148,22 +145,15 @@ func (eng *DummyEngine) verifyHeaderGasFields(config *params.ChainConfig, header return fmt.Errorf("invalid baseFee before fork: have %d, want ", header.BaseFee) } } else { - // Verify baseFee and rollupWindow encoding as part of header verification - // starting in AP3 - expectedRollupWindowBytes, expectedBaseFee, err := CalcBaseFee(config, parent, header.Time) + // Verify header.Extra and header.BaseFee match their expected values. + expectedExtraPrefix, expectedBaseFee, err := CalcBaseFee(config, parent, header.Time) if err != nil { return fmt.Errorf("failed to calculate base fee: %w", err) } - if len(header.Extra) < len(expectedRollupWindowBytes) || !bytes.Equal(expectedRollupWindowBytes, header.Extra[:len(expectedRollupWindowBytes)]) { - return fmt.Errorf("expected rollup window bytes: %x, found %x", expectedRollupWindowBytes, header.Extra) - } - if header.BaseFee == nil { - return errors.New("expected baseFee to be non-nil") - } - if bfLen := header.BaseFee.BitLen(); bfLen > 256 { - return fmt.Errorf("too large base fee: bitlen %d", bfLen) + if !bytes.HasPrefix(header.Extra, expectedExtraPrefix) { + return fmt.Errorf("expected header.Extra to have prefix: %x, found %x", expectedExtraPrefix, header.Extra) } - if header.BaseFee.Cmp(expectedBaseFee) != 0 { + if !utils.BigEqual(header.BaseFee, expectedBaseFee) { return fmt.Errorf("expected base fee (%d), found (%d)", expectedBaseFee, header.BaseFee) } } diff --git a/consensus/dummy/dynamic_fees.go b/consensus/dummy/dynamic_fees.go index eab34a54fb..d58441273f 100644 --- a/consensus/dummy/dynamic_fees.go +++ b/consensus/dummy/dynamic_fees.go @@ -18,6 +18,9 @@ import ( const ApricotPhase3BlockGasFee = 1_000_000 var ( + MaxUint256Plus1 = new(big.Int).Lsh(common.Big1, 256) + MaxUint256 = new(big.Int).Sub(MaxUint256Plus1, common.Big1) + ApricotPhase3MinBaseFee = big.NewInt(params.ApricotPhase3MinBaseFee) ApricotPhase3MaxBaseFee = big.NewInt(params.ApricotPhase3MaxBaseFee) ApricotPhase4MinBaseFee = big.NewInt(params.ApricotPhase4MinBaseFee) @@ -155,9 +158,9 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin // Ensure that the base fee does not increase/decrease outside of the bounds switch { case isEtna: - baseFee = selectBigWithinBounds(EtnaMinBaseFee, baseFee, nil) + baseFee = selectBigWithinBounds(EtnaMinBaseFee, baseFee, MaxUint256) case isApricotPhase5: - baseFee = selectBigWithinBounds(ApricotPhase4MinBaseFee, baseFee, nil) + baseFee = selectBigWithinBounds(ApricotPhase4MinBaseFee, baseFee, MaxUint256) case isApricotPhase4: baseFee = selectBigWithinBounds(ApricotPhase4MinBaseFee, baseFee, ApricotPhase4MaxBaseFee) default: diff --git a/utils/numbers.go b/utils/numbers.go index 4843716ddb..e9d4df0fa0 100644 --- a/utils/numbers.go +++ b/utils/numbers.go @@ -29,6 +29,15 @@ func Uint64PtrEqual(x, y *uint64) bool { return *x == *y } +// BigEqual returns true if a is equal to b. If a and b are nil, it returns +// true. +func BigEqual(a, b *big.Int) bool { + if a == nil || b == nil { + return a == b + } + return a.Cmp(b) == 0 +} + // BigEqualUint64 returns true if a is equal to b. If a is nil or not a uint64, // it returns false. func BigEqualUint64(a *big.Int, b uint64) bool { diff --git a/utils/numbers_test.go b/utils/numbers_test.go index e2f6750247..c664f6b2e5 100644 --- a/utils/numbers_test.go +++ b/utils/numbers_test.go @@ -10,6 +10,48 @@ import ( "github.com/stretchr/testify/assert" ) +func TestBigEqual(t *testing.T) { + tests := []struct { + name string + a *big.Int + b *big.Int + want bool + }{ + { + name: "nil_nil", + a: nil, + b: nil, + want: true, + }, + { + name: "0_nil", + a: big.NewInt(0), + b: nil, + want: false, + }, + { + name: "0_1", + a: big.NewInt(0), + b: big.NewInt(1), + want: false, + }, + { + name: "1_1", + a: big.NewInt(1), + b: big.NewInt(1), + want: true, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + assert := assert.New(t) + + assert.Equal(test.want, BigEqual(test.a, test.b)) + assert.Equal(test.want, BigEqual(test.b, test.a)) + }) + } +} + func TestBigEqualUint64(t *testing.T) { tests := []struct { name string From 32a879f66442b12f9f1fd46a96cb240990ba2f93 Mon Sep 17 00:00:00 2001 From: Quentin Mc Gaw Date: Fri, 14 Feb 2025 09:21:48 +0100 Subject: [PATCH 47/69] Bump libevm dependency to current main At commit https://github.com/ava-labs/libevm/pull/104/commits/bd9b506d6610f644fbd6ea1f51de08987e7a8f0f --- accounts/abi/bind/bind_test.go | 2 +- core/types/state_account.go | 2 +- go.mod | 2 +- go.sum | 4 ++-- scripts/tests.e2e.sh | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index ef02f473d3..ec5fc354fd 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -2179,7 +2179,7 @@ func golangBindings(t *testing.T, overload bool) { if out, err := replacer.CombinedOutput(); err != nil { t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out) } - replacer = exec.Command(gocmd, "mod", "edit", "-x", "-require", "github.com/ava-labs/libevm@v0.0.0", "-replace", "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250213164614-19ec675e01c4") + replacer = exec.Command(gocmd, "mod", "edit", "-x", "-require", "github.com/ava-labs/libevm@v0.0.0", "-replace", "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250214081829-bd9b506d6610") replacer.Dir = pkg if out, err := replacer.CombinedOutput(); err != nil { t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out) diff --git a/core/types/state_account.go b/core/types/state_account.go index b443332030..0c3cb7ab8d 100644 --- a/core/types/state_account.go +++ b/core/types/state_account.go @@ -49,7 +49,7 @@ type isMultiCoin bool var ( extras = ethtypes.RegisterExtras[ ethtypes.NOOPHeaderHooks, *ethtypes.NOOPHeaderHooks, - ethtypes.NOOPBodyHooks, *ethtypes.NOOPBodyHooks, + ethtypes.NOOPBlockBodyHooks, *ethtypes.NOOPBlockBodyHooks, isMultiCoin, ]() IsMultiCoinPayloads = extras.StateAccount diff --git a/go.mod b/go.mod index dc675e4f18..5e54e2f4e4 100644 --- a/go.mod +++ b/go.mod @@ -136,4 +136,4 @@ require ( rsc.io/tmplfunc v0.0.3 // indirect ) -replace github.com/ava-labs/libevm => github.com/ava-labs/libevm v0.0.0-20250213164614-19ec675e01c4 +replace github.com/ava-labs/libevm => github.com/ava-labs/libevm v0.0.0-20250214081829-bd9b506d6610 diff --git a/go.sum b/go.sum index 890178a227..41b18e6733 100644 --- a/go.sum +++ b/go.sum @@ -58,8 +58,8 @@ github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/ava-labs/avalanchego v1.12.1-0.20250107220127-32f58b4fa9c8 h1:qN3MOBHB//Ynhgt5Vys3iVe42Sr0EWSeN18VL3ecXzE= github.com/ava-labs/avalanchego v1.12.1-0.20250107220127-32f58b4fa9c8/go.mod h1:2B7+E5neLvkOr2zursGhebjU26d4AfB7RazPxBs8hHg= -github.com/ava-labs/libevm v0.0.0-20250213164614-19ec675e01c4 h1:nk6q9a1XoLp8Gnce8kEl3PpE6Xmpgc3QJKFnyt11M1g= -github.com/ava-labs/libevm v0.0.0-20250213164614-19ec675e01c4/go.mod h1:xi9AcwLOv3gUYYSuRYxXKVmLMFTSM4g0m4cpvC5X8DU= +github.com/ava-labs/libevm v0.0.0-20250214081829-bd9b506d6610 h1:88qJrHnjK2rmGroP1DoIoqSkga0/2yJmL/LnnIaujrw= +github.com/ava-labs/libevm v0.0.0-20250214081829-bd9b506d6610/go.mod h1:xi9AcwLOv3gUYYSuRYxXKVmLMFTSM4g0m4cpvC5X8DU= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/scripts/tests.e2e.sh b/scripts/tests.e2e.sh index fbdaf9d59d..1108129d20 100755 --- a/scripts/tests.e2e.sh +++ b/scripts/tests.e2e.sh @@ -45,7 +45,7 @@ git checkout -B "test-${AVALANCHE_VERSION}" "${AVALANCHE_VERSION}" echo "updating coreth dependency to point to ${CORETH_PATH}" go mod edit -replace "github.com/ava-labs/coreth=${CORETH_PATH}" -go mod edit -replace "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250213164614-19ec675e01c4" +go mod edit -replace "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250214081829-bd9b506d6610" go mod tidy echo "building avalanchego" From 266add14c4db05afc2571ed70ebd826366699070 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Fri, 14 Feb 2025 06:26:12 -0800 Subject: [PATCH 48/69] cleanup: chain config changes for similarty with subnet-evm (#798) Co-authored-by: Ceyhun Onur --- .../internal/tracetest/calltrace_test.go | 4 +- go.mod | 2 +- go.sum | 4 +- params/config.go | 60 +++++++++---------- params/config_extra.go | 36 ++++------- params/network_upgrades.go | 2 +- plugin/evm/vm.go | 9 +-- scripts/versions.sh | 2 +- 8 files changed, 50 insertions(+), 69 deletions(-) diff --git a/eth/tracers/internal/tracetest/calltrace_test.go b/eth/tracers/internal/tracetest/calltrace_test.go index 87c6ff5979..8166a3b045 100644 --- a/eth/tracers/internal/tracetest/calltrace_test.go +++ b/eth/tracers/internal/tracetest/calltrace_test.go @@ -34,8 +34,6 @@ import ( "strings" "testing" - "github.com/ava-labs/avalanchego/upgrade" - "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" @@ -272,7 +270,7 @@ func benchTracer(tracerName string, test *callTracerTest, b *testing.B) { func TestInternals(t *testing.T) { var ( - config = params.GetChainConfig(upgrade.GetConfig(constants.MainnetID), params.AvalancheMainnetChainID) + config = params.TestLaunchConfig to = common.HexToAddress("0x00000000000000000000000000000000deadbeef") origin = common.HexToAddress("0x00000000000000000000000000000000feed") txContext = vm.TxContext{ diff --git a/go.mod b/go.mod index 05ca39ac03..c082259171 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.22.8 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.12.3-warp-verify4 + github.com/ava-labs/avalanchego v1.12.3-0.20250213211448-ecd0efda0c2c github.com/cespare/cp v0.1.0 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 diff --git a/go.sum b/go.sum index 168caf4a40..fa777c4ea4 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,8 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/avalanchego v1.12.3-warp-verify4 h1:8YsFAZUC7PyvgZVpZe+kwpHBa7p1e3pDedS8/NeXQhU= -github.com/ava-labs/avalanchego v1.12.3-warp-verify4/go.mod h1:Er2qCyxI4qQKDlNjwwWdOa+/cxCbuEy/z8WgxtXy0N0= +github.com/ava-labs/avalanchego v1.12.3-0.20250213211448-ecd0efda0c2c h1:0m7VsyPVJmKRRyWrR+o5jq88Mzgths4i+g6PCmuVuyU= +github.com/ava-labs/avalanchego v1.12.3-0.20250213211448-ecd0efda0c2c/go.mod h1:PkpeGfEdsTccz87SDHidto21U5+BSBGZ+BNPW6Zplbc= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/params/config.go b/params/config.go index f95a815ef4..6186a946d8 100644 --- a/params/config.go +++ b/params/config.go @@ -52,8 +52,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -85,8 +85,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -116,8 +116,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -147,8 +147,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -179,8 +179,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -212,8 +212,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -245,8 +245,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -278,8 +278,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -311,8 +311,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -344,8 +344,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -377,8 +377,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -410,8 +410,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -443,8 +443,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -477,8 +477,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), @@ -512,8 +512,8 @@ var ( AvalancheContext: AvalancheContext{utils.TestSnowContext()}, ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), - DAOForkBlock: nil, - DAOForkSupport: false, + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, EIP150Block: big.NewInt(0), EIP155Block: big.NewInt(0), EIP158Block: big.NewInt(0), diff --git a/params/config_extra.go b/params/config_extra.go index abe6ed7bb0..9d5be4bfa9 100644 --- a/params/config_extra.go +++ b/params/config_extra.go @@ -35,11 +35,20 @@ type AvalancheContext struct { // SetEthUpgrades enables Etheruem network upgrades using the same time as // the Avalanche network upgrade that enables them. -// -// TODO: Prior to Cancun, Avalanche upgrades are referenced inline in the -// code in place of their Ethereum counterparts. The original Ethereum names -// should be restored for maintainability. func (c *ChainConfig) SetEthUpgrades() { + // Set Ethereum block upgrades to initially activated as they were already activated on launch. + c.HomesteadBlock = big.NewInt(0) + c.DAOForkBlock = big.NewInt(0) + c.DAOForkSupport = true + c.EIP150Block = big.NewInt(0) + c.EIP155Block = big.NewInt(0) + c.EIP158Block = big.NewInt(0) + c.ByzantiumBlock = big.NewInt(0) + c.ConstantinopleBlock = big.NewInt(0) + c.PetersburgBlock = big.NewInt(0) + c.IstanbulBlock = big.NewInt(0) + c.MuirGlacierBlock = big.NewInt(0) + if c.ChainID != nil && AvalancheFujiChainID.Cmp(c.ChainID) == 0 { c.BerlinBlock = big.NewInt(184985) // https://testnet.snowtrace.io/block/184985?chainid=43113, AP2 activation block c.LondonBlock = big.NewInt(805078) // https://testnet.snowtrace.io/block/805078?chainid=43113, AP3 activation block @@ -178,25 +187,6 @@ func (c *ChainConfig) ToWithUpgradesJSON() *ChainConfigWithUpgradesJSON { } } -func GetChainConfig(agoUpgrade upgrade.Config, chainID *big.Int) *ChainConfig { - c := &ChainConfig{ - ChainID: chainID, - HomesteadBlock: big.NewInt(0), - DAOForkBlock: big.NewInt(0), - DAOForkSupport: true, - EIP150Block: big.NewInt(0), - EIP155Block: big.NewInt(0), - EIP158Block: big.NewInt(0), - ByzantiumBlock: big.NewInt(0), - ConstantinopleBlock: big.NewInt(0), - PetersburgBlock: big.NewInt(0), - IstanbulBlock: big.NewInt(0), - MuirGlacierBlock: big.NewInt(0), - NetworkUpgrades: getNetworkUpgrades(agoUpgrade), - } - return c -} - func (r *Rules) PredicatersExist() bool { return len(r.Predicaters) > 0 } diff --git a/params/network_upgrades.go b/params/network_upgrades.go index c01b1e084c..c51a27bb41 100644 --- a/params/network_upgrades.go +++ b/params/network_upgrades.go @@ -208,7 +208,7 @@ func (n *NetworkUpgrades) Description() string { return banner } -func getNetworkUpgrades(agoUpgrade upgrade.Config) NetworkUpgrades { +func GetNetworkUpgrades(agoUpgrade upgrade.Config) NetworkUpgrades { return NetworkUpgrades{ ApricotPhase1BlockTimestamp: utils.TimeToNewUint64(agoUpgrade.ApricotPhase1Time), ApricotPhase2BlockTimestamp: utils.TimeToNewUint64(agoUpgrade.ApricotPhase2Time), diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 9b54b2cfdc..94df9198f3 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -410,25 +410,18 @@ func (vm *VM) Initialize( } var extDataHashes map[common.Hash]common.Hash - var chainID *big.Int // Set the chain config for mainnet/fuji chain IDs switch chainCtx.NetworkID { case avalanchegoConstants.MainnetID: - chainID = params.AvalancheMainnetChainID extDataHashes = mainnetExtDataHashes case avalanchegoConstants.FujiID: - chainID = params.AvalancheFujiChainID extDataHashes = fujiExtDataHashes - case avalanchegoConstants.LocalID: - chainID = params.AvalancheLocalChainID - default: - chainID = g.Config.ChainID } // if the chainCtx.NetworkUpgrades is not empty, set the chain config // normally it should not be empty, but some tests may not set it if chainCtx.NetworkUpgrades != (upgrade.Config{}) { - g.Config = params.GetChainConfig(chainCtx.NetworkUpgrades, new(big.Int).Set(chainID)) + g.Config.NetworkUpgrades = params.GetNetworkUpgrades(chainCtx.NetworkUpgrades) } // If the Durango is activated, activate the Warp Precompile at the same time diff --git a/scripts/versions.sh b/scripts/versions.sh index 12aed7d162..3c1ada0a27 100644 --- a/scripts/versions.sh +++ b/scripts/versions.sh @@ -6,4 +6,4 @@ set -euo pipefail # Don't export them as they're used in the context of other calls -AVALANCHE_VERSION=${AVALANCHE_VERSION:-'2eea9338'} +AVALANCHE_VERSION=${AVALANCHE_VERSION:-'ecd0efda'} From 20387de4a3402b40a27534cdd8d533d4ed2fb36a Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Fri, 14 Feb 2025 07:12:15 -0800 Subject: [PATCH 49/69] ci: bump avalanchego to master (#799) --- go.mod | 2 +- go.sum | 4 ++-- scripts/versions.sh | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index c082259171..37f94451a6 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.22.8 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.12.3-0.20250213211448-ecd0efda0c2c + github.com/ava-labs/avalanchego v1.12.3-0.20250213221544-df1bf8c8a6cf github.com/cespare/cp v0.1.0 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 diff --git a/go.sum b/go.sum index fa777c4ea4..a5038c5855 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,8 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/avalanchego v1.12.3-0.20250213211448-ecd0efda0c2c h1:0m7VsyPVJmKRRyWrR+o5jq88Mzgths4i+g6PCmuVuyU= -github.com/ava-labs/avalanchego v1.12.3-0.20250213211448-ecd0efda0c2c/go.mod h1:PkpeGfEdsTccz87SDHidto21U5+BSBGZ+BNPW6Zplbc= +github.com/ava-labs/avalanchego v1.12.3-0.20250213221544-df1bf8c8a6cf h1:4aq9V24PsH92vDSQTBx+uhm60BTeaNcXg/7FreQ8Q3M= +github.com/ava-labs/avalanchego v1.12.3-0.20250213221544-df1bf8c8a6cf/go.mod h1:PkpeGfEdsTccz87SDHidto21U5+BSBGZ+BNPW6Zplbc= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/scripts/versions.sh b/scripts/versions.sh index 3c1ada0a27..19de222a17 100644 --- a/scripts/versions.sh +++ b/scripts/versions.sh @@ -6,4 +6,4 @@ set -euo pipefail # Don't export them as they're used in the context of other calls -AVALANCHE_VERSION=${AVALANCHE_VERSION:-'ecd0efda'} +AVALANCHE_VERSION=${AVALANCHE_VERSION:-'df1bf8c8'} From a9437e4252ee30226811e50a31d061f7028b608f Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Fri, 14 Feb 2025 10:46:13 -0500 Subject: [PATCH 50/69] Ensure CalcBaseFee is only called with a sufficient timestamp (#797) --- consensus/dummy/dynamic_fees.go | 28 ++++++++---- consensus/dummy/dynamic_fees_test.go | 68 ++++++++++++++++++++++++++++ params/avalanche_params.go | 8 ++-- 3 files changed, 90 insertions(+), 14 deletions(-) diff --git a/consensus/dummy/dynamic_fees.go b/consensus/dummy/dynamic_fees.go index d58441273f..f9176dc7ed 100644 --- a/consensus/dummy/dynamic_fees.go +++ b/consensus/dummy/dynamic_fees.go @@ -4,6 +4,7 @@ package dummy import ( + "errors" "fmt" "math/big" @@ -30,6 +31,8 @@ var ( ApricotPhase4BaseFeeChangeDenominator = new(big.Int).SetUint64(params.ApricotPhase4BaseFeeChangeDenominator) ApricotPhase5BaseFeeChangeDenominator = new(big.Int).SetUint64(params.ApricotPhase5BaseFeeChangeDenominator) + + errEstimateBaseFeeWithoutActivation = errors.New("cannot estimate base fee for chain without apricot phase 3 scheduled") ) // CalcBaseFee takes the previous header and the timestamp of its child block @@ -64,9 +67,9 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin // If AP5, use a less responsive BaseFeeChangeDenominator and a higher gas // block limit var ( - baseFee = new(big.Int).Set(parent.BaseFee) - baseFeeChangeDenominator = ApricotPhase4BaseFeeChangeDenominator - parentGasTarget = params.ApricotPhase3TargetGas + baseFee = new(big.Int).Set(parent.BaseFee) + baseFeeChangeDenominator = ApricotPhase4BaseFeeChangeDenominator + parentGasTarget uint64 = params.ApricotPhase3TargetGas ) if isApricotPhase5 { baseFeeChangeDenominator = ApricotPhase5BaseFeeChangeDenominator @@ -170,15 +173,20 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin return dynamicFeeWindowBytes, baseFee, nil } -// EstimateNextBaseFee attempts to estimate the next base fee based on a block with [parent] being built at -// [timestamp]. -// If [timestamp] is less than the timestamp of [parent], then it uses the same timestamp as parent. -// Warning: This function should only be used in estimation and should not be used when calculating the canonical -// base fee for a subsequent block. +// EstimateNextBaseFee attempts to estimate the base fee of a block built at +// `timestamp` on top of `parent`. +// +// If timestamp is before parent.Time or the AP3 activation time, then timestamp +// is set to the maximum of parent.Time and the AP3 activation time. +// +// Warning: This function should only be used in estimation and should not be +// used when calculating the canonical base fee for a block. func EstimateNextBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uint64) (*big.Int, error) { - if timestamp < parent.Time { - timestamp = parent.Time + if config.ApricotPhase3BlockTimestamp == nil { + return nil, errEstimateBaseFeeWithoutActivation } + + timestamp = max(timestamp, parent.Time, *config.ApricotPhase3BlockTimestamp) _, baseFee, err := CalcBaseFee(config, parent, timestamp) return baseFee, err } diff --git a/consensus/dummy/dynamic_fees_test.go b/consensus/dummy/dynamic_fees_test.go index 5ccb0a1f16..4957ccc816 100644 --- a/consensus/dummy/dynamic_fees_test.go +++ b/consensus/dummy/dynamic_fees_test.go @@ -355,3 +355,71 @@ func TestCalcBaseFeeRegression(t *testing.T) { require.NoError(t, err) require.Equalf(t, 0, common.Big1.Cmp(big.NewInt(1)), "big1 should be 1, got %s", common.Big1) } + +func TestEstimateNextBaseFee(t *testing.T) { + tests := []struct { + name string + + upgrades params.NetworkUpgrades + + parentTime uint64 + parentNumber int64 + parentExtra []byte + parentBaseFee *big.Int + parentGasUsed uint64 + parentExtDataGasUsed *big.Int + + timestamp uint64 + + want *big.Int + wantErr error + }{ + { + name: "ap3", + upgrades: params.TestApricotPhase3Config.NetworkUpgrades, + parentNumber: 1, + parentExtra: (&DynamicFeeWindow{}).Bytes(), + parentBaseFee: big.NewInt(params.ApricotPhase3MaxBaseFee), + timestamp: 1, + want: func() *big.Int { + const ( + gasTarget = params.ApricotPhase3TargetGas + gasUsed = ApricotPhase3BlockGasFee + amountUnderTarget = gasTarget - gasUsed + parentBaseFee = params.ApricotPhase3MaxBaseFee + smoothingFactor = params.ApricotPhase4BaseFeeChangeDenominator + baseFeeFractionUnderTarget = amountUnderTarget * parentBaseFee / gasTarget + delta = baseFeeFractionUnderTarget / smoothingFactor + baseFee = parentBaseFee - delta + ) + return big.NewInt(baseFee) + }(), + }, + { + name: "ap3_not_scheduled", + upgrades: params.TestApricotPhase2Config.NetworkUpgrades, + wantErr: errEstimateBaseFeeWithoutActivation, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require := require.New(t) + + config := ¶ms.ChainConfig{ + NetworkUpgrades: test.upgrades, + } + parentHeader := &types.Header{ + Time: test.parentTime, + Number: big.NewInt(test.parentNumber), + Extra: test.parentExtra, + BaseFee: test.parentBaseFee, + GasUsed: test.parentGasUsed, + ExtDataGasUsed: test.parentExtDataGasUsed, + } + + got, err := EstimateNextBaseFee(config, parentHeader, test.timestamp) + require.ErrorIs(err, test.wantErr) + require.Equal(test.want, got) + }) + } +} diff --git a/params/avalanche_params.go b/params/avalanche_params.go index 0d23acf765..ceb699b0ca 100644 --- a/params/avalanche_params.go +++ b/params/avalanche_params.go @@ -23,13 +23,13 @@ const ( CortinaGasLimit uint64 = 15_000_000 ApricotPhase3MinBaseFee int64 = 75 * GWei - ApricotPhase3MaxBaseFee int64 = 225 * GWei + ApricotPhase3MaxBaseFee = 225 * GWei ApricotPhase3InitialBaseFee int64 = 225 * GWei - ApricotPhase3TargetGas uint64 = 10_000_000 + ApricotPhase3TargetGas = 10_000_000 ApricotPhase4MinBaseFee int64 = 25 * GWei ApricotPhase4MaxBaseFee int64 = 1_000 * GWei - ApricotPhase4BaseFeeChangeDenominator uint64 = 12 - ApricotPhase5TargetGas uint64 = 15_000_000 + ApricotPhase4BaseFeeChangeDenominator = 12 + ApricotPhase5TargetGas = 15_000_000 ApricotPhase5BaseFeeChangeDenominator uint64 = 36 EtnaMinBaseFee int64 = GWei From ea21f92c1d74991cdf1f29944308be4622be5df5 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Fri, 14 Feb 2025 11:03:53 -0800 Subject: [PATCH 51/69] fix(internal/ethapi): fix nil block in debug apis (#796) Signed-off-by: Darioush Jalali Co-authored-by: Sina M <1591639+s1na@users.noreply.github.com> Co-authored-by: Quentin McGaw --- internal/ethapi/api.go | 6 +++--- internal/ethapi/api_extra.go | 9 +++++++-- internal/ethapi/api_extra_test.go | 4 ++-- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 9e7ad54dde..f9101825ea 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -2019,7 +2019,7 @@ func (api *DebugAPI) GetRawHeader(ctx context.Context, blockNrOrHash rpc.BlockNu hash = h } else { block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash) - if err != nil { + if block == nil || err != nil { return nil, err } hash = block.Hash() @@ -2038,7 +2038,7 @@ func (api *DebugAPI) GetRawBlock(ctx context.Context, blockNrOrHash rpc.BlockNum hash = h } else { block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash) - if err != nil { + if block == nil || err != nil { return nil, err } hash = block.Hash() @@ -2057,7 +2057,7 @@ func (api *DebugAPI) GetRawReceipts(ctx context.Context, blockNrOrHash rpc.Block hash = h } else { block, err := api.b.BlockByNumberOrHash(ctx, blockNrOrHash) - if err != nil { + if block == nil || err != nil { return nil, err } hash = block.Hash() diff --git a/internal/ethapi/api_extra.go b/internal/ethapi/api_extra.go index 63cf84f48e..44a6fa37cb 100644 --- a/internal/ethapi/api_extra.go +++ b/internal/ethapi/api_extra.go @@ -5,6 +5,7 @@ package ethapi import ( "context" + "errors" "fmt" "github.com/ava-labs/coreth/core" @@ -113,12 +114,16 @@ func (s *BlockChainAPI) stateQueryBlockNumberAllowed(blockNumOrHash rpc.BlockNum var number uint64 if blockNumOrHash.BlockNumber != nil { number = uint64(blockNumOrHash.BlockNumber.Int64()) - } else { - block, err := s.b.BlockByNumberOrHash(context.Background(), blockNumOrHash) + } else if blockHash, ok := blockNumOrHash.Hash(); ok { + block, err := s.b.BlockByHash(context.Background(), blockHash) if err != nil { return fmt.Errorf("failed to get block from hash: %s", err) + } else if block == nil { + return fmt.Errorf("block from hash %s doesn't exist", blockHash) } number = block.NumberU64() + } else { + return errors.New("block number or hash not provided") } var oldestAllowed uint64 diff --git a/internal/ethapi/api_extra_test.go b/internal/ethapi/api_extra_test.go index 28843b4cb6..5d72617662 100644 --- a/internal/ethapi/api_extra_test.go +++ b/internal/ethapi/api_extra_test.go @@ -69,7 +69,7 @@ func TestBlockChainAPI_stateQueryBlockNumberAllowed(t *testing.T) { backend.EXPECT().HistoricalProofQueryWindow().Return(queryWindow) backend.EXPECT().LastAcceptedBlock().Return(makeBlockWithNumber(2200)) backend.EXPECT(). - BlockByNumberOrHash(gomock.Any(), gomock.Any()). + BlockByHash(gomock.Any(), gomock.Any()). Return(makeBlockWithNumber(2000), nil) return backend }, @@ -82,7 +82,7 @@ func TestBlockChainAPI_stateQueryBlockNumberAllowed(t *testing.T) { backend.EXPECT().HistoricalProofQueryWindow().Return(queryWindow) backend.EXPECT().LastAcceptedBlock().Return(makeBlockWithNumber(2200)) backend.EXPECT(). - BlockByNumberOrHash(gomock.Any(), gomock.Any()). + BlockByHash(gomock.Any(), gomock.Any()). Return(nil, fmt.Errorf("test error")) return backend }, From ea5897be29d479b8005f92477c1dbbc1ff5498c8 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Mon, 17 Feb 2025 07:35:44 -0800 Subject: [PATCH 52/69] cleanup(miner): remove unused code (#795) --- miner/ordering_ext.go | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 miner/ordering_ext.go diff --git a/miner/ordering_ext.go b/miner/ordering_ext.go deleted file mode 100644 index f9ce97ce90..0000000000 --- a/miner/ordering_ext.go +++ /dev/null @@ -1,15 +0,0 @@ -package miner - -import ( - "math/big" - - "github.com/ava-labs/coreth/core/txpool" - "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" -) - -type TransactionsByPriceAndNonce = transactionsByPriceAndNonce - -func NewTransactionsByPriceAndNonce(signer types.Signer, txs map[common.Address][]*txpool.LazyTransaction, baseFee *big.Int) *TransactionsByPriceAndNonce { - return newTransactionsByPriceAndNonce(signer, txs, baseFee) -} From 6060a4a6a6d399fe43e3c6b4866cc30d026ca021 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Mon, 17 Feb 2025 11:28:34 -0800 Subject: [PATCH 53/69] ci: bump golang to 1.23.6 (#805) Co-authored-by: Martin HS Co-authored-by: Marius van der Wijden Co-authored-by: Quentin McGaw --- .github/workflows/ci.yml | 2 +- .golangci.yml | 16 +++++++++++----- RELEASES.md | 2 ++ accounts/abi/abi_test.go | 1 - accounts/abi/bind/bind.go | 2 +- accounts/abi/event_test.go | 1 - accounts/abi/pack_test.go | 1 - accounts/abi/reflect_test.go | 1 - accounts/abi/topics_test.go | 3 --- accounts/abi/unpack_test.go | 3 +-- core/blockchain_test.go | 1 - core/predicate_check_test.go | 1 - core/rawdb/accessors_chain_test.go | 6 +++--- core/types/transaction_test.go | 2 -- eth/filters/api.go | 1 - eth/tracers/internal/tracetest/calltrace_test.go | 2 -- .../internal/tracetest/flat_calltrace_test.go | 1 - eth/tracers/internal/tracetest/prestate_test.go | 1 - eth/tracers/logger/logger.go | 2 +- go.mod | 4 ++-- go.sum | 4 ++-- plugin/evm/atomic_trie_test.go | 1 - plugin/evm/prestate_tracer_test.go | 1 - plugin/evm/vm_test.go | 1 - rpc/client_test.go | 1 - rpc/types_test.go | 1 - 26 files changed, 24 insertions(+), 38 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9b180a501d..71741d8eb9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: - version: v1.56 + version: v1.63 working-directory: . args: --timeout 3m skip-pkg-cache: true diff --git a/.golangci.yml b/.golangci.yml index c6c8d5748a..ace8a22dad 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -3,11 +3,6 @@ run: timeout: 10m tests: true - # default is true. Enables skipping of directories: - # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ - skip-dirs-use-default: true - # Include non-test files tagged as test-only. - # Context: https://github.com/ava-labs/avalanchego/pull/3173 linters: disable-all: true @@ -18,8 +13,19 @@ linters: - ineffassign - misspell - unconvert + - typecheck - unused + # - staticcheck + - bidichk + - durationcheck + - copyloopvar - whitespace + # - revive # only certain checks enabled + - durationcheck + - gocheckcompilerdirectives + - reassign + - mirror + - tenv linters-settings: gofmt: diff --git a/RELEASES.md b/RELEASES.md index 628e454843..0cce20cbc4 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,6 +1,8 @@ # Release Notes ## Pending Release +- Bump golang version to v1.23.6 +- Bump golangci-lint to v1.63 and add linters ## [v0.14.1](https://github.com/ava-labs/coreth/releases/tag/v0.14.1) diff --git a/accounts/abi/abi_test.go b/accounts/abi/abi_test.go index 68052e639a..023ff5cc4e 100644 --- a/accounts/abi/abi_test.go +++ b/accounts/abi/abi_test.go @@ -1210,7 +1210,6 @@ func TestUnpackRevert(t *testing.T) { {"4e487b7100000000000000000000000000000000000000000000000000000000000000ff", "unknown panic code: 0xff", nil}, } for index, c := range cases { - index, c := index, c t.Run(fmt.Sprintf("case %d", index), func(t *testing.T) { t.Parallel() got, err := UnpackRevert(common.Hex2Bytes(c.input)) diff --git a/accounts/abi/bind/bind.go b/accounts/abi/bind/bind.go index 0a4223c5e5..3dfbb6d243 100644 --- a/accounts/abi/bind/bind.go +++ b/accounts/abi/bind/bind.go @@ -262,7 +262,7 @@ func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string] } // Parse library references. for pattern, name := range libs { - matched, err := regexp.Match("__\\$"+pattern+"\\$__", []byte(contracts[types[i]].InputBin)) + matched, err := regexp.MatchString("__\\$"+pattern+"\\$__", contracts[types[i]].InputBin) if err != nil { log.Error("Could not search for pattern", "pattern", pattern, "contract", contracts[types[i]], "err", err) } diff --git a/accounts/abi/event_test.go b/accounts/abi/event_test.go index a967decd52..4a254e9950 100644 --- a/accounts/abi/event_test.go +++ b/accounts/abi/event_test.go @@ -341,7 +341,6 @@ func TestEventTupleUnpack(t *testing.T) { for _, tc := range testCases { assert := assert.New(t) - tc := tc t.Run(tc.name, func(t *testing.T) { err := unpackTestEventData(tc.dest, tc.data, tc.jsonLog, assert) if tc.error == "" { diff --git a/accounts/abi/pack_test.go b/accounts/abi/pack_test.go index 47d4931698..b13de922a5 100644 --- a/accounts/abi/pack_test.go +++ b/accounts/abi/pack_test.go @@ -44,7 +44,6 @@ import ( func TestPack(t *testing.T) { t.Parallel() for i, test := range packUnpackTests { - i, test := i, test t.Run(strconv.Itoa(i), func(t *testing.T) { t.Parallel() encb, err := hex.DecodeString(test.packed) diff --git a/accounts/abi/reflect_test.go b/accounts/abi/reflect_test.go index 5d90cdb763..624032968d 100644 --- a/accounts/abi/reflect_test.go +++ b/accounts/abi/reflect_test.go @@ -182,7 +182,6 @@ var reflectTests = []reflectTest{ func TestReflectNameToStruct(t *testing.T) { t.Parallel() for _, test := range reflectTests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() m, err := mapArgNamesToStructFields(test.args, reflect.ValueOf(test.struc)) diff --git a/accounts/abi/topics_test.go b/accounts/abi/topics_test.go index 70522b6ce6..53e4327bf6 100644 --- a/accounts/abi/topics_test.go +++ b/accounts/abi/topics_test.go @@ -147,7 +147,6 @@ func TestMakeTopics(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() got, err := MakeTopics(tt.args.query...) @@ -383,7 +382,6 @@ func TestParseTopics(t *testing.T) { tests := setupTopicsTests() for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() createObj := tt.args.createObj() @@ -403,7 +401,6 @@ func TestParseTopicsIntoMap(t *testing.T) { tests := setupTopicsTests() for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() outMap := make(map[string]interface{}) diff --git a/accounts/abi/unpack_test.go b/accounts/abi/unpack_test.go index 0b4224efa5..d7f383a731 100644 --- a/accounts/abi/unpack_test.go +++ b/accounts/abi/unpack_test.go @@ -399,7 +399,6 @@ func TestMethodMultiReturn(t *testing.T) { "Can not unpack into a slice with wrong types", }} for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { require := require.New(t) err := abi.UnpackIntoInterface(tc.dest, "multi", data) @@ -957,7 +956,7 @@ func TestOOMMaliciousInput(t *testing.T) { } encb, err := hex.DecodeString(test.enc) if err != nil { - t.Fatalf("invalid hex: %s" + test.enc) + t.Fatalf("invalid hex: %s", test.enc) } _, err = abi.Methods["method"].Outputs.UnpackValues(encb) if err == nil { diff --git a/core/blockchain_test.go b/core/blockchain_test.go index 601cb12f02..7460efd92e 100644 --- a/core/blockchain_test.go +++ b/core/blockchain_test.go @@ -290,7 +290,6 @@ func TestBlockChainOfflinePruningUngracefulShutdown(t *testing.T) { return createBlockChain(db, pruningConfig, gspec, lastAcceptedHash) } for _, tt := range tests { - tt := tt t.Run(tt.Name, func(t *testing.T) { t.Parallel() tt.testFunc(t, create) diff --git a/core/predicate_check_test.go b/core/predicate_check_test.go index 3d98416fc3..3c17aac698 100644 --- a/core/predicate_check_test.go +++ b/core/predicate_check_test.go @@ -293,7 +293,6 @@ func TestCheckPredicate(t *testing.T) { expectedErr: ErrIntrinsicGas, }, } { - test := test t.Run(name, func(t *testing.T) { require := require.New(t) // Create the rules from TestChainConfig and update the predicates based on the test params diff --git a/core/rawdb/accessors_chain_test.go b/core/rawdb/accessors_chain_test.go index 27c7cf4a95..1157eee792 100644 --- a/core/rawdb/accessors_chain_test.go +++ b/core/rawdb/accessors_chain_test.go @@ -291,10 +291,10 @@ func TestBlockReceiptStorage(t *testing.T) { // Insert the receipt slice into the database and check presence WriteReceipts(db, hash, 0, receipts) if rs := ReadReceipts(db, hash, 0, 0, params.TestChainConfig); len(rs) == 0 { - t.Fatalf("no receipts returned") + t.Fatal("no receipts returned") } else { if err := checkReceiptsRLP(rs, receipts); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } } // Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed) @@ -308,7 +308,7 @@ func TestBlockReceiptStorage(t *testing.T) { } // Ensure that receipts without metadata can be returned without the block body too if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } // Sanity check that body and header alone without the receipt is a full purge WriteHeader(db, header) diff --git a/core/types/transaction_test.go b/core/types/transaction_test.go index 4471a6ba45..02ea3d16a4 100644 --- a/core/types/transaction_test.go +++ b/core/types/transaction_test.go @@ -520,9 +520,7 @@ func TestYParityJSONUnmarshalling(t *testing.T) { DynamicFeeTxType, BlobTxType, } { - txType := txType for _, test := range tests { - test := test t.Run(fmt.Sprintf("txType=%d: %s", txType, test.name), func(t *testing.T) { // Copy the base json testJson := make(map[string]interface{}) diff --git a/eth/filters/api.go b/eth/filters/api.go index 2416e91061..fb8178ed63 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -350,7 +350,6 @@ func (api *FilterAPI) Logs(ctx context.Context, crit FilterCriteria) (*rpc.Subsc select { case logs := <-matchedLogs: for _, log := range logs { - log := log notifier.Notify(rpcSub.ID, &log) } case <-rpcSub.Err(): // client send an unsubscribe request diff --git a/eth/tracers/internal/tracetest/calltrace_test.go b/eth/tracers/internal/tracetest/calltrace_test.go index 8166a3b045..075a804f18 100644 --- a/eth/tracers/internal/tracetest/calltrace_test.go +++ b/eth/tracers/internal/tracetest/calltrace_test.go @@ -113,7 +113,6 @@ func testCallTracer(tracerName string, dirPath string, t *testing.T) { if !strings.HasSuffix(file.Name(), ".json") { continue } - file := file // capture range variable t.Run(camel(strings.TrimSuffix(file.Name(), ".json")), func(t *testing.T) { t.Parallel() @@ -205,7 +204,6 @@ func BenchmarkTracers(b *testing.B) { if !strings.HasSuffix(file.Name(), ".json") { continue } - file := file // capture range variable b.Run(camel(strings.TrimSuffix(file.Name(), ".json")), func(b *testing.B) { blob, err := os.ReadFile(filepath.Join("testdata", "call_tracer", file.Name())) if err != nil { diff --git a/eth/tracers/internal/tracetest/flat_calltrace_test.go b/eth/tracers/internal/tracetest/flat_calltrace_test.go index 9305bf7150..b9be17981b 100644 --- a/eth/tracers/internal/tracetest/flat_calltrace_test.go +++ b/eth/tracers/internal/tracetest/flat_calltrace_test.go @@ -167,7 +167,6 @@ func testFlatCallTracer(tracerName string, dirPath string, t *testing.T) { if !strings.HasSuffix(file.Name(), ".json") { continue } - file := file // capture range variable t.Run(camel(strings.TrimSuffix(file.Name(), ".json")), func(t *testing.T) { t.Parallel() diff --git a/eth/tracers/internal/tracetest/prestate_test.go b/eth/tracers/internal/tracetest/prestate_test.go index 7f659d6f71..fd4231b002 100644 --- a/eth/tracers/internal/tracetest/prestate_test.go +++ b/eth/tracers/internal/tracetest/prestate_test.go @@ -83,7 +83,6 @@ func testPrestateDiffTracer(tracerName string, dirPath string, t *testing.T) { if !strings.HasSuffix(file.Name(), ".json") { continue } - file := file // capture range variable t.Run(camel(strings.TrimSuffix(file.Name(), ".json")), func(t *testing.T) { t.Parallel() diff --git a/eth/tracers/logger/logger.go b/eth/tracers/logger/logger.go index d94ffd3cf7..c6d3f1b0fb 100644 --- a/eth/tracers/logger/logger.go +++ b/eth/tracers/logger/logger.go @@ -446,7 +446,7 @@ func formatLogs(logs []StructLog) []StructLogRes { } formatted[index].Stack = &stack } - if trace.ReturnData != nil && len(trace.ReturnData) > 0 { + if len(trace.ReturnData) > 0 { formatted[index].ReturnData = hexutil.Bytes(trace.ReturnData).String() } if trace.Memory != nil { diff --git a/go.mod b/go.mod index 37f94451a6..f3257ce832 100644 --- a/go.mod +++ b/go.mod @@ -1,10 +1,10 @@ module github.com/ava-labs/coreth -go 1.22.8 +go 1.23.6 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.12.3-0.20250213221544-df1bf8c8a6cf + github.com/ava-labs/avalanchego v1.12.3-0.20250216200402-d76684b684f1 github.com/cespare/cp v0.1.0 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 diff --git a/go.sum b/go.sum index a5038c5855..6ae24cb046 100644 --- a/go.sum +++ b/go.sum @@ -54,8 +54,8 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/avalanchego v1.12.3-0.20250213221544-df1bf8c8a6cf h1:4aq9V24PsH92vDSQTBx+uhm60BTeaNcXg/7FreQ8Q3M= -github.com/ava-labs/avalanchego v1.12.3-0.20250213221544-df1bf8c8a6cf/go.mod h1:PkpeGfEdsTccz87SDHidto21U5+BSBGZ+BNPW6Zplbc= +github.com/ava-labs/avalanchego v1.12.3-0.20250216200402-d76684b684f1 h1:bp+RMUpgUX2HL22FnArOMkhg9IaGjA7xHExAH3zy3Og= +github.com/ava-labs/avalanchego v1.12.3-0.20250216200402-d76684b684f1/go.mod h1:kjz2dtxgb9UiSzCDMon8AqFpsRPb9SGGW9F6tsKwufc= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/plugin/evm/atomic_trie_test.go b/plugin/evm/atomic_trie_test.go index 71d62ef7ca..1a065d4530 100644 --- a/plugin/evm/atomic_trie_test.go +++ b/plugin/evm/atomic_trie_test.go @@ -706,7 +706,6 @@ func TestAtomicTrie_AcceptTrie(t *testing.T) { } for name, testCase := range testCases { - testCase := testCase // capture range variable for running tests with Go < 1.22 t.Run(name, func(t *testing.T) { t.Parallel() diff --git a/plugin/evm/prestate_tracer_test.go b/plugin/evm/prestate_tracer_test.go index 097155a8ae..511098bb62 100644 --- a/plugin/evm/prestate_tracer_test.go +++ b/plugin/evm/prestate_tracer_test.go @@ -37,7 +37,6 @@ func testPrestateDiffTracer(tracerName string, dirPath string, t *testing.T) { if !strings.HasSuffix(file.Name(), ".json") { continue } - file := file // capture range variable t.Run(camel(strings.TrimSuffix(file.Name(), ".json")), func(t *testing.T) { t.Parallel() diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 9fb8949c9a..0f54053cef 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -1136,7 +1136,6 @@ func TestConflictingImportTxsAcrossBlocks(t *testing.T) { "apricotPhase4": genesisJSONApricotPhase4, "apricotPhase5": genesisJSONApricotPhase5, } { - genesis := genesis t.Run(name, func(t *testing.T) { testConflictingImportTxs(t, genesis) }) diff --git a/rpc/client_test.go b/rpc/client_test.go index eec18afb8f..97bc69e61b 100644 --- a/rpc/client_test.go +++ b/rpc/client_test.go @@ -723,7 +723,6 @@ func TestClientHTTP(t *testing.T) { ) defer client.Close() for i := range results { - i := i go func() { errc <- client.Call(&results[i], "test_echo", wantResult.String, wantResult.Int, wantResult.Args) }() diff --git a/rpc/types_test.go b/rpc/types_test.go index a255c1e9f7..779b23296f 100644 --- a/rpc/types_test.go +++ b/rpc/types_test.go @@ -145,7 +145,6 @@ func TestBlockNumberOrHash_WithNumber_MarshalAndUnmarshal(t *testing.T) { {"earliest", int64(EarliestBlockNumber)}, } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { bnh := BlockNumberOrHashWithNumber(BlockNumber(test.number)) marshalled, err := json.Marshal(bnh) From a8710a495821d9b93a7cdaa87696cea6010f7c77 Mon Sep 17 00:00:00 2001 From: Quentin Mc Gaw Date: Mon, 17 Feb 2025 21:27:27 +0100 Subject: [PATCH 54/69] Bump libevm to v1.13.14-0.1.0.rc-2 --- accounts/abi/bind/bind_test.go | 5 ----- go.mod | 8 ++++---- go.sum | 4 ++-- scripts/tests.e2e.sh | 1 - 4 files changed, 6 insertions(+), 12 deletions(-) diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index ec5fc354fd..c1035f6b8a 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -2179,11 +2179,6 @@ func golangBindings(t *testing.T, overload bool) { if out, err := replacer.CombinedOutput(); err != nil { t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out) } - replacer = exec.Command(gocmd, "mod", "edit", "-x", "-require", "github.com/ava-labs/libevm@v0.0.0", "-replace", "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250214081829-bd9b506d6610") - replacer.Dir = pkg - if out, err := replacer.CombinedOutput(); err != nil { - t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out) - } tidier := exec.Command(gocmd, "mod", "tidy", "-compat=1.22") tidier.Dir = pkg if out, err := tidier.CombinedOutput(); err != nil { diff --git a/go.mod b/go.mod index 5e54e2f4e4..e498b18a3e 100644 --- a/go.mod +++ b/go.mod @@ -1,11 +1,13 @@ module github.com/ava-labs/coreth -go 1.22.8 +go 1.23 + +toolchain go1.23.6 require ( github.com/VictoriaMetrics/fastcache v1.12.1 github.com/ava-labs/avalanchego v1.12.1-0.20250107220127-32f58b4fa9c8 - github.com/ava-labs/libevm v1.13.14-0.1.0.rc-2 + github.com/ava-labs/libevm v1.13.14-0.2.0.rc.3 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 github.com/deckarep/golang-set/v2 v2.1.0 @@ -135,5 +137,3 @@ require ( gopkg.in/yaml.v3 v3.0.1 // indirect rsc.io/tmplfunc v0.0.3 // indirect ) - -replace github.com/ava-labs/libevm => github.com/ava-labs/libevm v0.0.0-20250214081829-bd9b506d6610 diff --git a/go.sum b/go.sum index 41b18e6733..ee1a057217 100644 --- a/go.sum +++ b/go.sum @@ -58,8 +58,8 @@ github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/ava-labs/avalanchego v1.12.1-0.20250107220127-32f58b4fa9c8 h1:qN3MOBHB//Ynhgt5Vys3iVe42Sr0EWSeN18VL3ecXzE= github.com/ava-labs/avalanchego v1.12.1-0.20250107220127-32f58b4fa9c8/go.mod h1:2B7+E5neLvkOr2zursGhebjU26d4AfB7RazPxBs8hHg= -github.com/ava-labs/libevm v0.0.0-20250214081829-bd9b506d6610 h1:88qJrHnjK2rmGroP1DoIoqSkga0/2yJmL/LnnIaujrw= -github.com/ava-labs/libevm v0.0.0-20250214081829-bd9b506d6610/go.mod h1:xi9AcwLOv3gUYYSuRYxXKVmLMFTSM4g0m4cpvC5X8DU= +github.com/ava-labs/libevm v1.13.14-0.2.0.rc.3 h1:1CWGo2icnX9dRqGQl7CFywYGIZWxe+ucy0w8NAsVTWE= +github.com/ava-labs/libevm v1.13.14-0.2.0.rc.3/go.mod h1:+Iol+sVQ1KyoBsHf3veyrBmHCXr3xXRWq6ZXkgVfNLU= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= diff --git a/scripts/tests.e2e.sh b/scripts/tests.e2e.sh index 1108129d20..85f5bd3d48 100755 --- a/scripts/tests.e2e.sh +++ b/scripts/tests.e2e.sh @@ -45,7 +45,6 @@ git checkout -B "test-${AVALANCHE_VERSION}" "${AVALANCHE_VERSION}" echo "updating coreth dependency to point to ${CORETH_PATH}" go mod edit -replace "github.com/ava-labs/coreth=${CORETH_PATH}" -go mod edit -replace "github.com/ava-labs/libevm=github.com/ava-labs/libevm@v0.0.0-20250214081829-bd9b506d6610" go mod tidy echo "building avalanchego" From 7ae03b19a88209b29f0a1b8c0cad9afce84f4ec7 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 18 Feb 2025 11:40:51 -0500 Subject: [PATCH 55/69] Split `CalcExtraData` out of `CalcBaseFee` (#802) --- consensus/dummy/consensus.go | 12 +- consensus/dummy/dynamic_fees.go | 205 ++++++++++++++++---------- consensus/dummy/dynamic_fees_test.go | 22 ++- core/chain_makers.go | 6 +- core/state_processor_test.go | 3 +- core/txpool/blobpool/blobpool_test.go | 2 +- miner/worker.go | 6 +- 7 files changed, 165 insertions(+), 91 deletions(-) diff --git a/consensus/dummy/consensus.go b/consensus/dummy/consensus.go index f3fd98c075..02c89a8790 100644 --- a/consensus/dummy/consensus.go +++ b/consensus/dummy/consensus.go @@ -145,14 +145,20 @@ func (eng *DummyEngine) verifyHeaderGasFields(config *params.ChainConfig, header return fmt.Errorf("invalid baseFee before fork: have %d, want ", header.BaseFee) } } else { - // Verify header.Extra and header.BaseFee match their expected values. - expectedExtraPrefix, expectedBaseFee, err := CalcBaseFee(config, parent, header.Time) + // Verify header.Extra matches the expected value. + expectedExtraPrefix, err := CalcExtraPrefix(config, parent, header.Time) if err != nil { - return fmt.Errorf("failed to calculate base fee: %w", err) + return fmt.Errorf("failed to calculate extra prefix: %w", err) } if !bytes.HasPrefix(header.Extra, expectedExtraPrefix) { return fmt.Errorf("expected header.Extra to have prefix: %x, found %x", expectedExtraPrefix, header.Extra) } + + // Verify header.BaseFee matches the expected value. + expectedBaseFee, err := CalcBaseFee(config, parent, header.Time) + if err != nil { + return fmt.Errorf("failed to calculate base fee: %w", err) + } if !utils.BigEqual(header.BaseFee, expectedBaseFee) { return fmt.Errorf("expected base fee (%d), found (%d)", expectedBaseFee, header.BaseFee) } diff --git a/consensus/dummy/dynamic_fees.go b/consensus/dummy/dynamic_fees.go index f9176dc7ed..694b74d6e7 100644 --- a/consensus/dummy/dynamic_fees.go +++ b/consensus/dummy/dynamic_fees.go @@ -35,39 +35,39 @@ var ( errEstimateBaseFeeWithoutActivation = errors.New("cannot estimate base fee for chain without apricot phase 3 scheduled") ) +// CalcExtraPrefix takes the previous header and the timestamp of its child +// block and calculates the expected extra prefix for the child block. +// +// CalcExtraPrefix should only be called if timestamp >= config.ApricotPhase3Timestamp +func CalcExtraPrefix( + config *params.ChainConfig, + parent *types.Header, + timestamp uint64, +) ([]byte, error) { + window, err := calcFeeWindow(config, parent, timestamp) + return window.Bytes(), err +} + // CalcBaseFee takes the previous header and the timestamp of its child block -// and calculates the expected base fee as well as the encoding of the past -// pricing information for the child block. -// CalcBaseFee should only be called if [timestamp] >= [config.ApricotPhase3Timestamp] -func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uint64) ([]byte, *big.Int, error) { +// and calculates the expected base fee for the child block. +// +// CalcBaseFee should only be called if timestamp >= config.ApricotPhase3Timestamp +func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uint64) (*big.Int, error) { // If the current block is the first EIP-1559 block, or it is the genesis block // return the initial slice and initial base fee. - var ( - isApricotPhase3 = config.IsApricotPhase3(parent.Time) - isApricotPhase4 = config.IsApricotPhase4(parent.Time) - isApricotPhase5 = config.IsApricotPhase5(parent.Time) - isEtna = config.IsEtna(parent.Time) - ) - if !isApricotPhase3 || parent.Number.Cmp(common.Big0) == 0 { - initialSlice := (&DynamicFeeWindow{}).Bytes() - initialBaseFee := big.NewInt(params.ApricotPhase3InitialBaseFee) - return initialSlice, initialBaseFee, nil + if !config.IsApricotPhase3(parent.Time) || parent.Number.Cmp(common.Big0) == 0 { + return big.NewInt(params.ApricotPhase3InitialBaseFee), nil } - dynamicFeeWindow, err := ParseDynamicFeeWindow(parent.Extra) + dynamicFeeWindow, err := calcFeeWindow(config, parent, timestamp) if err != nil { - return nil, nil, err + return nil, err } - if timestamp < parent.Time { - return nil, nil, fmt.Errorf("cannot calculate base fee for timestamp %d prior to parent timestamp %d", timestamp, parent.Time) - } - timeElapsed := timestamp - parent.Time - // If AP5, use a less responsive BaseFeeChangeDenominator and a higher gas // block limit var ( - baseFee = new(big.Int).Set(parent.BaseFee) + isApricotPhase5 = config.IsApricotPhase5(parent.Time) baseFeeChangeDenominator = ApricotPhase4BaseFeeChangeDenominator parentGasTarget uint64 = params.ApricotPhase3TargetGas ) @@ -75,58 +75,20 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin baseFeeChangeDenominator = ApricotPhase5BaseFeeChangeDenominator parentGasTarget = params.ApricotPhase5TargetGas } - parentGasTargetBig := new(big.Int).SetUint64(parentGasTarget) - - // Add in parent's consumed gas - var blockGasCost, parentExtraStateGasUsed uint64 - switch { - case isApricotPhase5: - // blockGasCost has been removed in AP5, so it is left as 0. - - // At the start of a new network, the parent - // may not have a populated ExtDataGasUsed. - if parent.ExtDataGasUsed != nil { - parentExtraStateGasUsed = parent.ExtDataGasUsed.Uint64() - } - case isApricotPhase4: - // The blockGasCost is paid by the effective tips in the block using - // the block's value of baseFee. - // - // Although the child block may be in AP5 here, the blockGasCost is - // still calculated using the AP4 step. This is different than the - // actual BlockGasCost calculation used for the child block. This - // behavior is kept to preserve the original behavior of this function. - blockGasCost = header.BlockGasCostWithStep( - parent.BlockGasCost, - ap4.BlockGasCostStep, - timeElapsed, - ) - - // On the boundary of AP3 and AP4 or at the start of a new network, the - // parent may not have a populated ExtDataGasUsed. - if parent.ExtDataGasUsed != nil { - parentExtraStateGasUsed = parent.ExtDataGasUsed.Uint64() - } - default: - blockGasCost = ApricotPhase3BlockGasFee - } - - // Compute the new state of the gas rolling window. - dynamicFeeWindow.Add(parent.GasUsed, parentExtraStateGasUsed, blockGasCost) - - // roll the window over by the timeElapsed to generate the new rollup - // window. - dynamicFeeWindow.Shift(timeElapsed) - dynamicFeeWindowBytes := dynamicFeeWindow.Bytes() // Calculate the amount of gas consumed within the rollup window. - totalGas := dynamicFeeWindow.Sum() + var ( + baseFee = new(big.Int).Set(parent.BaseFee) + totalGas = dynamicFeeWindow.Sum() + ) if totalGas == parentGasTarget { - return dynamicFeeWindowBytes, baseFee, nil + return baseFee, nil } - num := new(big.Int) - + var ( + num = new(big.Int) + parentGasTargetBig = new(big.Int).SetUint64(parentGasTarget) + ) if totalGas > parentGasTarget { // If the parent block used more gas than its target, the baseFee should increase. num.SetUint64(totalGas - parentGasTarget) @@ -143,6 +105,16 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin num.Div(num, parentGasTargetBig) num.Div(num, baseFeeChangeDenominator) baseFeeDelta := math.BigMax(num, common.Big1) + + if timestamp < parent.Time { + // This should never happen as the fee window calculations should + // have already failed, but it is kept for clarity. + return nil, fmt.Errorf("cannot calculate base fee for timestamp %d prior to parent timestamp %d", + timestamp, + parent.Time, + ) + } + // If timeElapsed is greater than [params.RollupWindow], apply the // state transition to the base fee to account for the interval during // which no blocks were produced. @@ -150,27 +122,105 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin // We use timeElapsed/params.RollupWindow, so that the transition is // applied for every [params.RollupWindow] seconds that has elapsed // between the parent and this block. - if timeElapsed > params.RollupWindow { - // Note: timeElapsed/params.RollupWindow must be at least 1 since - // we've checked that timeElapsed > params.RollupWindow - baseFeeDelta = new(big.Int).Mul(baseFeeDelta, new(big.Int).SetUint64(timeElapsed/params.RollupWindow)) + var ( + timeElapsed = timestamp - parent.Time + windowsElapsed = timeElapsed / params.RollupWindow + ) + if windowsElapsed > 1 { + bigWindowsElapsed := new(big.Int).SetUint64(windowsElapsed) + // Because baseFeeDelta could actually be [common.Big1], we must not + // modify the existing value of `baseFeeDelta` but instead allocate + // a new one. + baseFeeDelta = new(big.Int).Mul(baseFeeDelta, bigWindowsElapsed) } baseFee.Sub(baseFee, baseFeeDelta) } // Ensure that the base fee does not increase/decrease outside of the bounds switch { - case isEtna: + case config.IsEtna(parent.Time): baseFee = selectBigWithinBounds(EtnaMinBaseFee, baseFee, MaxUint256) case isApricotPhase5: baseFee = selectBigWithinBounds(ApricotPhase4MinBaseFee, baseFee, MaxUint256) - case isApricotPhase4: + case config.IsApricotPhase4(parent.Time): baseFee = selectBigWithinBounds(ApricotPhase4MinBaseFee, baseFee, ApricotPhase4MaxBaseFee) default: baseFee = selectBigWithinBounds(ApricotPhase3MinBaseFee, baseFee, ApricotPhase3MaxBaseFee) } - return dynamicFeeWindowBytes, baseFee, nil + return baseFee, nil +} + +// calcFeeWindow takes the previous header and the timestamp of its child block +// and calculates the expected fee window. +// +// calcFeeWindow should only be called if timestamp >= config.ApricotPhase3Timestamp +func calcFeeWindow( + config *params.ChainConfig, + parent *types.Header, + timestamp uint64, +) (DynamicFeeWindow, error) { + // If the current block is the first EIP-1559 block, or it is the genesis block + // return the initial window. + if !config.IsApricotPhase3(parent.Time) || parent.Number.Cmp(common.Big0) == 0 { + return DynamicFeeWindow{}, nil + } + + dynamicFeeWindow, err := ParseDynamicFeeWindow(parent.Extra) + if err != nil { + return DynamicFeeWindow{}, err + } + + if timestamp < parent.Time { + return DynamicFeeWindow{}, fmt.Errorf("cannot calculate fee window for timestamp %d prior to parent timestamp %d", + timestamp, + parent.Time, + ) + } + timeElapsed := timestamp - parent.Time + + // Add in parent's consumed gas + var blockGasCost, parentExtraStateGasUsed uint64 + switch { + case config.IsApricotPhase5(parent.Time): + // blockGasCost is not included in the fee window after AP5, so it is + // left as 0. + + // At the start of a new network, the parent + // may not have a populated ExtDataGasUsed. + if parent.ExtDataGasUsed != nil { + parentExtraStateGasUsed = parent.ExtDataGasUsed.Uint64() + } + case config.IsApricotPhase4(parent.Time): + // The blockGasCost is paid by the effective tips in the block using + // the block's value of baseFee. + // + // Although the child block may be in AP5 here, the blockGasCost is + // still calculated using the AP4 step. This is different than the + // actual BlockGasCost calculation used for the child block. This + // behavior is kept to preserve the original behavior of this function. + blockGasCost = header.BlockGasCostWithStep( + parent.BlockGasCost, + ap4.BlockGasCostStep, + timeElapsed, + ) + + // On the boundary of AP3 and AP4 or at the start of a new network, the + // parent may not have a populated ExtDataGasUsed. + if parent.ExtDataGasUsed != nil { + parentExtraStateGasUsed = parent.ExtDataGasUsed.Uint64() + } + default: + blockGasCost = ApricotPhase3BlockGasFee + } + + // Compute the new state of the gas rolling window. + dynamicFeeWindow.Add(parent.GasUsed, parentExtraStateGasUsed, blockGasCost) + + // roll the window over by the timeElapsed to generate the new rollup + // window. + dynamicFeeWindow.Shift(timeElapsed) + return dynamicFeeWindow, nil } // EstimateNextBaseFee attempts to estimate the base fee of a block built at @@ -187,8 +237,7 @@ func EstimateNextBaseFee(config *params.ChainConfig, parent *types.Header, times } timestamp = max(timestamp, parent.Time, *config.ApricotPhase3BlockTimestamp) - _, baseFee, err := CalcBaseFee(config, parent, timestamp) - return baseFee, err + return CalcBaseFee(config, parent, timestamp) } // selectBigWithinBounds returns [value] if it is within the bounds: diff --git a/consensus/dummy/dynamic_fees_test.go b/consensus/dummy/dynamic_fees_test.go index 4957ccc816..543c1051a0 100644 --- a/consensus/dummy/dynamic_fees_test.go +++ b/consensus/dummy/dynamic_fees_test.go @@ -128,7 +128,11 @@ func testDynamicFeesStaysWithinRange(t *testing.T, test test) { } for index, block := range blocks[1:] { - nextExtraData, nextBaseFee, err := CalcBaseFee(params.TestApricotPhase3Config, header, block.timestamp) + nextExtraData, err := CalcExtraPrefix(params.TestApricotPhase3Config, header, block.timestamp) + if err != nil { + t.Fatalf("Failed to calculate extra prefix at index %d: %s", index, err) + } + nextBaseFee, err := CalcBaseFee(params.TestApricotPhase3Config, header, block.timestamp) if err != nil { t.Fatalf("Failed to calculate base fee at index %d: %s", index, err) } @@ -286,7 +290,9 @@ func TestCalcBaseFeeAP4(t *testing.T) { for index, event := range events { block := event.block - nextExtraData, nextBaseFee, err := CalcBaseFee(params.TestApricotPhase4Config, header, block.timestamp) + nextExtraData, err := CalcExtraPrefix(params.TestApricotPhase4Config, header, block.timestamp) + assert.NoError(t, err) + nextBaseFee, err := CalcBaseFee(params.TestApricotPhase4Config, header, block.timestamp) assert.NoError(t, err) log.Info("Update", "baseFee", nextBaseFee) header = &types.Header{ @@ -297,7 +303,9 @@ func TestCalcBaseFeeAP4(t *testing.T) { Extra: nextExtraData, } - nextExtraData, nextBaseFee, err = CalcBaseFee(params.TestApricotPhase4Config, extDataHeader, block.timestamp) + nextExtraData, err = CalcExtraPrefix(params.TestApricotPhase4Config, extDataHeader, block.timestamp) + assert.NoError(t, err) + nextBaseFee, err = CalcBaseFee(params.TestApricotPhase4Config, extDataHeader, block.timestamp) assert.NoError(t, err) log.Info("Update", "baseFee (w/extData)", nextBaseFee) extDataHeader = &types.Header{ @@ -320,7 +328,9 @@ func TestDynamicFeesEtna(t *testing.T) { } timestamp := uint64(1) - extra, nextBaseFee, err := CalcBaseFee(params.TestEtnaChainConfig, header, timestamp) + extra, err := CalcExtraPrefix(params.TestEtnaChainConfig, header, timestamp) + require.NoError(err) + nextBaseFee, err := CalcBaseFee(params.TestEtnaChainConfig, header, timestamp) require.NoError(err) // Genesis matches the initial base fee require.Equal(params.ApricotPhase3InitialBaseFee, nextBaseFee.Int64()) @@ -332,7 +342,7 @@ func TestDynamicFeesEtna(t *testing.T) { BaseFee: nextBaseFee, Extra: extra, } - _, nextBaseFee, err = CalcBaseFee(params.TestEtnaChainConfig, header, timestamp) + nextBaseFee, err = CalcBaseFee(params.TestEtnaChainConfig, header, timestamp) require.NoError(err) // After some time has passed in the Etna phase, the base fee should drop // lower than the prior base fee minimum. @@ -351,7 +361,7 @@ func TestCalcBaseFeeRegression(t *testing.T) { Extra: make([]byte, params.DynamicFeeExtraDataSize), } - _, _, err := CalcBaseFee(params.TestChainConfig, parentHeader, timestamp) + _, err := CalcBaseFee(params.TestChainConfig, parentHeader, timestamp) require.NoError(t, err) require.Equalf(t, 0, common.Big1.Cmp(big.NewInt(1)), "big1 should be 1, got %s", common.Big1) } diff --git a/core/chain_makers.go b/core/chain_makers.go index d5ffd53074..f40a3eaf7e 100644 --- a/core/chain_makers.go +++ b/core/chain_makers.go @@ -393,7 +393,11 @@ func (cm *chainMaker) makeHeader(parent *types.Block, gap uint64, state *state.S } if cm.config.IsApricotPhase3(time) { var err error - header.Extra, header.BaseFee, err = dummy.CalcBaseFee(cm.config, parent.Header(), time) + header.Extra, err = dummy.CalcExtraPrefix(cm.config, parent.Header(), time) + if err != nil { + panic(err) + } + header.BaseFee, err = dummy.CalcBaseFee(cm.config, parent.Header(), time) if err != nil { panic(err) } diff --git a/core/state_processor_test.go b/core/state_processor_test.go index 5392ad4427..a837211205 100644 --- a/core/state_processor_test.go +++ b/core/state_processor_test.go @@ -368,7 +368,8 @@ func GenerateBadBlock(parent *types.Block, engine consensus.Engine, txs types.Tr UncleHash: types.EmptyUncleHash, } if config.IsApricotPhase3(header.Time) { - header.Extra, header.BaseFee, _ = dummy.CalcBaseFee(config, parent.Header(), header.Time) + header.Extra, _ = dummy.CalcExtraPrefix(config, parent.Header(), header.Time) + header.BaseFee, _ = dummy.CalcBaseFee(config, parent.Header(), header.Time) } if config.IsApricotPhase4(header.Time) { header.BlockGasCost = big.NewInt(0) diff --git a/core/txpool/blobpool/blobpool_test.go b/core/txpool/blobpool/blobpool_test.go index 0e993ca9dc..542a559b4b 100644 --- a/core/txpool/blobpool/blobpool_test.go +++ b/core/txpool/blobpool/blobpool_test.go @@ -121,7 +121,7 @@ func (bc *testBlockChain) CurrentBlock() *types.Header { BaseFee: mid, Extra: make([]byte, params.DynamicFeeExtraDataSize), } - _, baseFee, err := dummy.CalcBaseFee( + baseFee, err := dummy.CalcBaseFee( bc.config, parent, blockTime, ) if err != nil { diff --git a/miner/worker.go b/miner/worker.go index 96ab02c23d..4febfb4dc9 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -167,7 +167,11 @@ func (w *worker) commitNewWork(predicateContext *precompileconfig.PredicateConte // Set BaseFee and Extra data field if we are post ApricotPhase3 if w.chainConfig.IsApricotPhase3(timestamp) { var err error - header.Extra, header.BaseFee, err = dummy.CalcBaseFee(w.chainConfig, parent, timestamp) + header.Extra, err = dummy.CalcExtraPrefix(w.chainConfig, parent, timestamp) + if err != nil { + return nil, fmt.Errorf("failed to calculate new extra prefix: %w", err) + } + header.BaseFee, err = dummy.CalcBaseFee(w.chainConfig, parent, timestamp) if err != nil { return nil, fmt.Errorf("failed to calculate new base fee: %w", err) } From 0510079278e3de6445ed1aab86a5e9fa61a01f1a Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 18 Feb 2025 11:59:07 -0500 Subject: [PATCH 56/69] Support all upgrades in CalcBaseFee and CalcExtraPrefix (#804) --- consensus/dummy/consensus.go | 37 +++++++++++++-------------------- consensus/dummy/dynamic_fees.go | 28 ++++++++++++++++++++----- core/chain_makers.go | 20 +++++++++--------- core/state_processor_test.go | 6 ++---- miner/worker.go | 20 ++++++++---------- 5 files changed, 59 insertions(+), 52 deletions(-) diff --git a/consensus/dummy/consensus.go b/consensus/dummy/consensus.go index 02c89a8790..8ee94c3398 100644 --- a/consensus/dummy/consensus.go +++ b/consensus/dummy/consensus.go @@ -139,29 +139,22 @@ func (eng *DummyEngine) verifyHeaderGasFields(config *params.ChainConfig, header } } - if !config.IsApricotPhase3(header.Time) { - // Verify BaseFee is not present before AP3 - if header.BaseFee != nil { - return fmt.Errorf("invalid baseFee before fork: have %d, want ", header.BaseFee) - } - } else { - // Verify header.Extra matches the expected value. - expectedExtraPrefix, err := CalcExtraPrefix(config, parent, header.Time) - if err != nil { - return fmt.Errorf("failed to calculate extra prefix: %w", err) - } - if !bytes.HasPrefix(header.Extra, expectedExtraPrefix) { - return fmt.Errorf("expected header.Extra to have prefix: %x, found %x", expectedExtraPrefix, header.Extra) - } + // Verify header.Extra matches the expected value. + expectedExtraPrefix, err := CalcExtraPrefix(config, parent, header.Time) + if err != nil { + return fmt.Errorf("failed to calculate extra prefix: %w", err) + } + if !bytes.HasPrefix(header.Extra, expectedExtraPrefix) { + return fmt.Errorf("expected header.Extra to have prefix: %x, found %x", expectedExtraPrefix, header.Extra) + } - // Verify header.BaseFee matches the expected value. - expectedBaseFee, err := CalcBaseFee(config, parent, header.Time) - if err != nil { - return fmt.Errorf("failed to calculate base fee: %w", err) - } - if !utils.BigEqual(header.BaseFee, expectedBaseFee) { - return fmt.Errorf("expected base fee (%d), found (%d)", expectedBaseFee, header.BaseFee) - } + // Verify header.BaseFee matches the expected value. + expectedBaseFee, err := CalcBaseFee(config, parent, header.Time) + if err != nil { + return fmt.Errorf("failed to calculate base fee: %w", err) + } + if !utils.BigEqual(header.BaseFee, expectedBaseFee) { + return fmt.Errorf("expected base fee %d, found %d", expectedBaseFee, header.BaseFee) } // Verify BlockGasCost, ExtDataGasUsed not present before AP4 diff --git a/consensus/dummy/dynamic_fees.go b/consensus/dummy/dynamic_fees.go index 694b74d6e7..12c07de3f3 100644 --- a/consensus/dummy/dynamic_fees.go +++ b/consensus/dummy/dynamic_fees.go @@ -37,22 +37,40 @@ var ( // CalcExtraPrefix takes the previous header and the timestamp of its child // block and calculates the expected extra prefix for the child block. -// -// CalcExtraPrefix should only be called if timestamp >= config.ApricotPhase3Timestamp func CalcExtraPrefix( config *params.ChainConfig, parent *types.Header, timestamp uint64, ) ([]byte, error) { - window, err := calcFeeWindow(config, parent, timestamp) - return window.Bytes(), err + switch { + case config.IsApricotPhase3(timestamp): + window, err := calcFeeWindow(config, parent, timestamp) + if err != nil { + return nil, fmt.Errorf("failed to calculate fee window: %w", err) + } + return window.Bytes(), nil + default: + // Prior to AP3 there was no expected extra prefix. + return nil, nil + } } // CalcBaseFee takes the previous header and the timestamp of its child block // and calculates the expected base fee for the child block. // -// CalcBaseFee should only be called if timestamp >= config.ApricotPhase3Timestamp +// Prior to AP3, the returned base fee will be nil. func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uint64) (*big.Int, error) { + switch { + case config.IsApricotPhase3(timestamp): + return calcBaseFeeWithWindow(config, parent, timestamp) + default: + // Prior to AP3 the expected base fee is nil. + return nil, nil + } +} + +// calcBaseFeeWithWindow should only be called if `timestamp` >= `config.ApricotPhase3Timestamp` +func calcBaseFeeWithWindow(config *params.ChainConfig, parent *types.Header, timestamp uint64) (*big.Int, error) { // If the current block is the first EIP-1559 block, or it is the genesis block // return the initial slice and initial base fee. if !config.IsApricotPhase3(parent.Time) || parent.Number.Cmp(common.Big0) == 0 { diff --git a/core/chain_makers.go b/core/chain_makers.go index f40a3eaf7e..8211b1b20c 100644 --- a/core/chain_makers.go +++ b/core/chain_makers.go @@ -391,17 +391,17 @@ func (cm *chainMaker) makeHeader(parent *types.Block, gap uint64, state *state.S Number: new(big.Int).Add(parent.Number(), common.Big1), Time: time, } - if cm.config.IsApricotPhase3(time) { - var err error - header.Extra, err = dummy.CalcExtraPrefix(cm.config, parent.Header(), time) - if err != nil { - panic(err) - } - header.BaseFee, err = dummy.CalcBaseFee(cm.config, parent.Header(), time) - if err != nil { - panic(err) - } + + var err error + header.Extra, err = dummy.CalcExtraPrefix(cm.config, parent.Header(), time) + if err != nil { + panic(err) + } + header.BaseFee, err = dummy.CalcBaseFee(cm.config, parent.Header(), time) + if err != nil { + panic(err) } + if cm.config.IsCancun(header.Number, header.Time) { var ( parentExcessBlobGas uint64 diff --git a/core/state_processor_test.go b/core/state_processor_test.go index a837211205..65b098c32e 100644 --- a/core/state_processor_test.go +++ b/core/state_processor_test.go @@ -367,10 +367,8 @@ func GenerateBadBlock(parent *types.Block, engine consensus.Engine, txs types.Tr Time: parent.Time() + 10, UncleHash: types.EmptyUncleHash, } - if config.IsApricotPhase3(header.Time) { - header.Extra, _ = dummy.CalcExtraPrefix(config, parent.Header(), header.Time) - header.BaseFee, _ = dummy.CalcBaseFee(config, parent.Header(), header.Time) - } + header.Extra, _ = dummy.CalcExtraPrefix(config, parent.Header(), header.Time) + header.BaseFee, _ = dummy.CalcBaseFee(config, parent.Header(), header.Time) if config.IsApricotPhase4(header.Time) { header.BlockGasCost = big.NewInt(0) header.ExtDataGasUsed = big.NewInt(0) diff --git a/miner/worker.go b/miner/worker.go index 4febfb4dc9..52d256c571 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -164,18 +164,16 @@ func (w *worker) commitNewWork(predicateContext *precompileconfig.PredicateConte Time: timestamp, } - // Set BaseFee and Extra data field if we are post ApricotPhase3 - if w.chainConfig.IsApricotPhase3(timestamp) { - var err error - header.Extra, err = dummy.CalcExtraPrefix(w.chainConfig, parent, timestamp) - if err != nil { - return nil, fmt.Errorf("failed to calculate new extra prefix: %w", err) - } - header.BaseFee, err = dummy.CalcBaseFee(w.chainConfig, parent, timestamp) - if err != nil { - return nil, fmt.Errorf("failed to calculate new base fee: %w", err) - } + var err error + header.Extra, err = dummy.CalcExtraPrefix(w.chainConfig, parent, timestamp) + if err != nil { + return nil, fmt.Errorf("failed to calculate new extra prefix: %w", err) + } + header.BaseFee, err = dummy.CalcBaseFee(w.chainConfig, parent, timestamp) + if err != nil { + return nil, fmt.Errorf("failed to calculate new base fee: %w", err) } + // Apply EIP-4844, EIP-4788. if w.chainConfig.IsCancun(header.Number, header.Time) { var excessBlobGas uint64 From f23d63be6cdcd3f2630caedb81d99959f98402df Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 18 Feb 2025 13:45:23 -0500 Subject: [PATCH 57/69] Fix `params.ApricotPhase4BaseFeeChangeDenominator` name (#807) --- consensus/dummy/dynamic_fees.go | 4 ++-- consensus/dummy/dynamic_fees_test.go | 2 +- params/avalanche_params.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/consensus/dummy/dynamic_fees.go b/consensus/dummy/dynamic_fees.go index 12c07de3f3..96b56393fb 100644 --- a/consensus/dummy/dynamic_fees.go +++ b/consensus/dummy/dynamic_fees.go @@ -29,7 +29,7 @@ var ( ApricotPhase3InitialBaseFee = big.NewInt(params.ApricotPhase3InitialBaseFee) EtnaMinBaseFee = big.NewInt(params.EtnaMinBaseFee) - ApricotPhase4BaseFeeChangeDenominator = new(big.Int).SetUint64(params.ApricotPhase4BaseFeeChangeDenominator) + ApricotPhase3BaseFeeChangeDenominator = new(big.Int).SetUint64(params.ApricotPhase3BaseFeeChangeDenominator) ApricotPhase5BaseFeeChangeDenominator = new(big.Int).SetUint64(params.ApricotPhase5BaseFeeChangeDenominator) errEstimateBaseFeeWithoutActivation = errors.New("cannot estimate base fee for chain without apricot phase 3 scheduled") @@ -86,7 +86,7 @@ func calcBaseFeeWithWindow(config *params.ChainConfig, parent *types.Header, tim // block limit var ( isApricotPhase5 = config.IsApricotPhase5(parent.Time) - baseFeeChangeDenominator = ApricotPhase4BaseFeeChangeDenominator + baseFeeChangeDenominator = ApricotPhase3BaseFeeChangeDenominator parentGasTarget uint64 = params.ApricotPhase3TargetGas ) if isApricotPhase5 { diff --git a/consensus/dummy/dynamic_fees_test.go b/consensus/dummy/dynamic_fees_test.go index 543c1051a0..babd7557a4 100644 --- a/consensus/dummy/dynamic_fees_test.go +++ b/consensus/dummy/dynamic_fees_test.go @@ -397,7 +397,7 @@ func TestEstimateNextBaseFee(t *testing.T) { gasUsed = ApricotPhase3BlockGasFee amountUnderTarget = gasTarget - gasUsed parentBaseFee = params.ApricotPhase3MaxBaseFee - smoothingFactor = params.ApricotPhase4BaseFeeChangeDenominator + smoothingFactor = params.ApricotPhase3BaseFeeChangeDenominator baseFeeFractionUnderTarget = amountUnderTarget * parentBaseFee / gasTarget delta = baseFeeFractionUnderTarget / smoothingFactor baseFee = parentBaseFee - delta diff --git a/params/avalanche_params.go b/params/avalanche_params.go index ceb699b0ca..78e8f5ffc0 100644 --- a/params/avalanche_params.go +++ b/params/avalanche_params.go @@ -28,7 +28,7 @@ const ( ApricotPhase3TargetGas = 10_000_000 ApricotPhase4MinBaseFee int64 = 25 * GWei ApricotPhase4MaxBaseFee int64 = 1_000 * GWei - ApricotPhase4BaseFeeChangeDenominator = 12 + ApricotPhase3BaseFeeChangeDenominator = 12 ApricotPhase5TargetGas = 15_000_000 ApricotPhase5BaseFeeChangeDenominator uint64 = 36 EtnaMinBaseFee int64 = GWei From 11455745265bed1bd2809d114f9087b3394415d5 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Mon, 17 Feb 2025 11:28:34 -0800 Subject: [PATCH 58/69] ci: bump golang to 1.23.6 (#805) Co-authored-by: Martin HS Co-authored-by: Marius van der Wijden Co-authored-by: Quentin McGaw --- .github/workflows/ci.yml | 2 +- .golangci.yml | 16 +++++++++++----- accounts/abi/abi_test.go | 1 - accounts/abi/bind/bind.go | 2 +- accounts/abi/event_test.go | 1 - accounts/abi/pack_test.go | 1 - accounts/abi/reflect_test.go | 1 - accounts/abi/topics_test.go | 3 --- accounts/abi/unpack_test.go | 3 +-- core/blockchain_test.go | 1 - core/predicate_check_test.go | 1 - core/rawdb/accessors_chain_test.go | 6 +++--- eth/filters/api.go | 1 - plugin/evm/prestate_tracer_test.go | 1 - plugin/evm/vm_test.go | 1 - rpc/client_test.go | 1 - rpc/types_test.go | 1 - 17 files changed, 17 insertions(+), 26 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3adc2a853c..66dba3f52e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: - version: v1.56 + version: v1.63 working-directory: . args: --timeout 3m skip-pkg-cache: true diff --git a/.golangci.yml b/.golangci.yml index c6c8d5748a..ace8a22dad 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -3,11 +3,6 @@ run: timeout: 10m tests: true - # default is true. Enables skipping of directories: - # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ - skip-dirs-use-default: true - # Include non-test files tagged as test-only. - # Context: https://github.com/ava-labs/avalanchego/pull/3173 linters: disable-all: true @@ -18,8 +13,19 @@ linters: - ineffassign - misspell - unconvert + - typecheck - unused + # - staticcheck + - bidichk + - durationcheck + - copyloopvar - whitespace + # - revive # only certain checks enabled + - durationcheck + - gocheckcompilerdirectives + - reassign + - mirror + - tenv linters-settings: gofmt: diff --git a/accounts/abi/abi_test.go b/accounts/abi/abi_test.go index 1e30d27f19..ee46105203 100644 --- a/accounts/abi/abi_test.go +++ b/accounts/abi/abi_test.go @@ -1210,7 +1210,6 @@ func TestUnpackRevert(t *testing.T) { {"4e487b7100000000000000000000000000000000000000000000000000000000000000ff", "unknown panic code: 0xff", nil}, } for index, c := range cases { - index, c := index, c t.Run(fmt.Sprintf("case %d", index), func(t *testing.T) { t.Parallel() got, err := UnpackRevert(common.Hex2Bytes(c.input)) diff --git a/accounts/abi/bind/bind.go b/accounts/abi/bind/bind.go index e6a22121d4..4347ba8169 100644 --- a/accounts/abi/bind/bind.go +++ b/accounts/abi/bind/bind.go @@ -262,7 +262,7 @@ func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string] } // Parse library references. for pattern, name := range libs { - matched, err := regexp.Match("__\\$"+pattern+"\\$__", []byte(contracts[types[i]].InputBin)) + matched, err := regexp.MatchString("__\\$"+pattern+"\\$__", contracts[types[i]].InputBin) if err != nil { log.Error("Could not search for pattern", "pattern", pattern, "contract", contracts[types[i]], "err", err) } diff --git a/accounts/abi/event_test.go b/accounts/abi/event_test.go index 1da8c9dae1..63f9fb2ffe 100644 --- a/accounts/abi/event_test.go +++ b/accounts/abi/event_test.go @@ -341,7 +341,6 @@ func TestEventTupleUnpack(t *testing.T) { for _, tc := range testCases { assert := assert.New(t) - tc := tc t.Run(tc.name, func(t *testing.T) { err := unpackTestEventData(tc.dest, tc.data, tc.jsonLog, assert) if tc.error == "" { diff --git a/accounts/abi/pack_test.go b/accounts/abi/pack_test.go index 99bf47200e..c76866c369 100644 --- a/accounts/abi/pack_test.go +++ b/accounts/abi/pack_test.go @@ -44,7 +44,6 @@ import ( func TestPack(t *testing.T) { t.Parallel() for i, test := range packUnpackTests { - i, test := i, test t.Run(strconv.Itoa(i), func(t *testing.T) { t.Parallel() encb, err := hex.DecodeString(test.packed) diff --git a/accounts/abi/reflect_test.go b/accounts/abi/reflect_test.go index 5d90cdb763..624032968d 100644 --- a/accounts/abi/reflect_test.go +++ b/accounts/abi/reflect_test.go @@ -182,7 +182,6 @@ var reflectTests = []reflectTest{ func TestReflectNameToStruct(t *testing.T) { t.Parallel() for _, test := range reflectTests { - test := test t.Run(test.name, func(t *testing.T) { t.Parallel() m, err := mapArgNamesToStructFields(test.args, reflect.ValueOf(test.struc)) diff --git a/accounts/abi/topics_test.go b/accounts/abi/topics_test.go index 691c2c09dc..cf9ca32b4f 100644 --- a/accounts/abi/topics_test.go +++ b/accounts/abi/topics_test.go @@ -147,7 +147,6 @@ func TestMakeTopics(t *testing.T) { }, } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() got, err := MakeTopics(tt.args.query...) @@ -383,7 +382,6 @@ func TestParseTopics(t *testing.T) { tests := setupTopicsTests() for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() createObj := tt.args.createObj() @@ -403,7 +401,6 @@ func TestParseTopicsIntoMap(t *testing.T) { tests := setupTopicsTests() for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() outMap := make(map[string]interface{}) diff --git a/accounts/abi/unpack_test.go b/accounts/abi/unpack_test.go index 2454bde1fb..ae55cf3250 100644 --- a/accounts/abi/unpack_test.go +++ b/accounts/abi/unpack_test.go @@ -399,7 +399,6 @@ func TestMethodMultiReturn(t *testing.T) { "Can not unpack into a slice with wrong types", }} for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { require := require.New(t) err := abi.UnpackIntoInterface(tc.dest, "multi", data) @@ -957,7 +956,7 @@ func TestOOMMaliciousInput(t *testing.T) { } encb, err := hex.DecodeString(test.enc) if err != nil { - t.Fatalf("invalid hex: %s" + test.enc) + t.Fatalf("invalid hex: %s", test.enc) } _, err = abi.Methods["method"].Outputs.UnpackValues(encb) if err == nil { diff --git a/core/blockchain_test.go b/core/blockchain_test.go index 95e703c5ad..63fb388c4b 100644 --- a/core/blockchain_test.go +++ b/core/blockchain_test.go @@ -291,7 +291,6 @@ func TestBlockChainOfflinePruningUngracefulShutdown(t *testing.T) { return createBlockChain(db, pruningConfig, gspec, lastAcceptedHash) } for _, tt := range tests { - tt := tt t.Run(tt.Name, func(t *testing.T) { t.Parallel() tt.testFunc(t, create) diff --git a/core/predicate_check_test.go b/core/predicate_check_test.go index 949253ece4..de942c1a70 100644 --- a/core/predicate_check_test.go +++ b/core/predicate_check_test.go @@ -293,7 +293,6 @@ func TestCheckPredicate(t *testing.T) { expectedErr: ErrIntrinsicGas, }, } { - test := test t.Run(name, func(t *testing.T) { require := require.New(t) // Create the rules from TestChainConfig and update the predicates based on the test params diff --git a/core/rawdb/accessors_chain_test.go b/core/rawdb/accessors_chain_test.go index 0a99d5dfda..3ec409066e 100644 --- a/core/rawdb/accessors_chain_test.go +++ b/core/rawdb/accessors_chain_test.go @@ -291,10 +291,10 @@ func TestBlockReceiptStorage(t *testing.T) { // Insert the receipt slice into the database and check presence WriteReceipts(db, hash, 0, receipts) if rs := ReadReceipts(db, hash, 0, 0, params.TestChainConfig); len(rs) == 0 { - t.Fatalf("no receipts returned") + t.Fatal("no receipts returned") } else { if err := checkReceiptsRLP(rs, receipts); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } } // Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed) @@ -308,7 +308,7 @@ func TestBlockReceiptStorage(t *testing.T) { } // Ensure that receipts without metadata can be returned without the block body too if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } // Sanity check that body and header alone without the receipt is a full purge WriteHeader(db, header) diff --git a/eth/filters/api.go b/eth/filters/api.go index 6e79f0ddca..1ed17ec6db 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -350,7 +350,6 @@ func (api *FilterAPI) Logs(ctx context.Context, crit FilterCriteria) (*rpc.Subsc select { case logs := <-matchedLogs: for _, log := range logs { - log := log notifier.Notify(rpcSub.ID, &log) } case <-rpcSub.Err(): // client send an unsubscribe request diff --git a/plugin/evm/prestate_tracer_test.go b/plugin/evm/prestate_tracer_test.go index 029abac932..8de9762efa 100644 --- a/plugin/evm/prestate_tracer_test.go +++ b/plugin/evm/prestate_tracer_test.go @@ -38,7 +38,6 @@ func testPrestateDiffTracer(tracerName string, dirPath string, t *testing.T) { if !strings.HasSuffix(file.Name(), ".json") { continue } - file := file // capture range variable t.Run(camel(strings.TrimSuffix(file.Name(), ".json")), func(t *testing.T) { t.Parallel() diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index b1acd489b6..5f56e69c87 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -1137,7 +1137,6 @@ func TestConflictingImportTxsAcrossBlocks(t *testing.T) { "apricotPhase4": genesisJSONApricotPhase4, "apricotPhase5": genesisJSONApricotPhase5, } { - genesis := genesis t.Run(name, func(t *testing.T) { testConflictingImportTxs(t, genesis) }) diff --git a/rpc/client_test.go b/rpc/client_test.go index 6a13e487da..826d1eed48 100644 --- a/rpc/client_test.go +++ b/rpc/client_test.go @@ -723,7 +723,6 @@ func TestClientHTTP(t *testing.T) { ) defer client.Close() for i := range results { - i := i go func() { errc <- client.Call(&results[i], "test_echo", wantResult.String, wantResult.Int, wantResult.Args) }() diff --git a/rpc/types_test.go b/rpc/types_test.go index 824c1c8155..d37632d62e 100644 --- a/rpc/types_test.go +++ b/rpc/types_test.go @@ -145,7 +145,6 @@ func TestBlockNumberOrHash_WithNumber_MarshalAndUnmarshal(t *testing.T) { {"earliest", int64(EarliestBlockNumber)}, } for _, test := range tests { - test := test t.Run(test.name, func(t *testing.T) { bnh := BlockNumberOrHashWithNumber(BlockNumber(test.number)) marshalled, err := json.Marshal(bnh) From 2e4e6bd85132e7c655775e1b62a6397e0270cdb5 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 18 Feb 2025 18:41:22 -0500 Subject: [PATCH 59/69] Move AP4 params (#809) --- consensus/dummy/dynamic_fees.go | 4 ++-- consensus/dummy/dynamic_fees_test.go | 3 ++- params/avalanche_params.go | 2 -- plugin/evm/ap4/cost.go | 28 +++++++++++++++++++++++++--- 4 files changed, 29 insertions(+), 8 deletions(-) diff --git a/consensus/dummy/dynamic_fees.go b/consensus/dummy/dynamic_fees.go index 96b56393fb..772b0f11e5 100644 --- a/consensus/dummy/dynamic_fees.go +++ b/consensus/dummy/dynamic_fees.go @@ -24,8 +24,8 @@ var ( ApricotPhase3MinBaseFee = big.NewInt(params.ApricotPhase3MinBaseFee) ApricotPhase3MaxBaseFee = big.NewInt(params.ApricotPhase3MaxBaseFee) - ApricotPhase4MinBaseFee = big.NewInt(params.ApricotPhase4MinBaseFee) - ApricotPhase4MaxBaseFee = big.NewInt(params.ApricotPhase4MaxBaseFee) + ApricotPhase4MinBaseFee = big.NewInt(ap4.MinBaseFee) + ApricotPhase4MaxBaseFee = big.NewInt(ap4.MaxBaseFee) ApricotPhase3InitialBaseFee = big.NewInt(params.ApricotPhase3InitialBaseFee) EtnaMinBaseFee = big.NewInt(params.EtnaMinBaseFee) diff --git a/consensus/dummy/dynamic_fees_test.go b/consensus/dummy/dynamic_fees_test.go index babd7557a4..b8b239c708 100644 --- a/consensus/dummy/dynamic_fees_test.go +++ b/consensus/dummy/dynamic_fees_test.go @@ -9,6 +9,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/plugin/evm/ap4" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/log" @@ -346,7 +347,7 @@ func TestDynamicFeesEtna(t *testing.T) { require.NoError(err) // After some time has passed in the Etna phase, the base fee should drop // lower than the prior base fee minimum. - require.Less(nextBaseFee.Int64(), params.ApricotPhase4MinBaseFee) + require.Less(nextBaseFee.Int64(), int64(ap4.MinBaseFee)) } func TestCalcBaseFeeRegression(t *testing.T) { diff --git a/params/avalanche_params.go b/params/avalanche_params.go index 78e8f5ffc0..20bf49b215 100644 --- a/params/avalanche_params.go +++ b/params/avalanche_params.go @@ -26,8 +26,6 @@ const ( ApricotPhase3MaxBaseFee = 225 * GWei ApricotPhase3InitialBaseFee int64 = 225 * GWei ApricotPhase3TargetGas = 10_000_000 - ApricotPhase4MinBaseFee int64 = 25 * GWei - ApricotPhase4MaxBaseFee int64 = 1_000 * GWei ApricotPhase3BaseFeeChangeDenominator = 12 ApricotPhase5TargetGas = 15_000_000 ApricotPhase5BaseFeeChangeDenominator uint64 = 36 diff --git a/plugin/evm/ap4/cost.go b/plugin/evm/ap4/cost.go index 396aaa06b4..46296196fc 100644 --- a/plugin/evm/ap4/cost.go +++ b/plugin/evm/ap4/cost.go @@ -9,25 +9,47 @@ import ( "math" safemath "github.com/ava-labs/avalanchego/utils/math" + "github.com/ava-labs/coreth/params" ) const ( + // MinBlockGasCost is the minimum block gas cost. MinBlockGasCost = 0 + // MaxBlockGasCost is the maximum block gas cost. If the block gas cost + // would exceed this value, the block gas cost is set to this value. MaxBlockGasCost = 1_000_000 - TargetBlockRate = 2 // in seconds + // TargetBlockRate is the target amount of time in seconds between blocks. + // If blocks are produced faster than this rate, the block gas cost is + // increased. If blocks are produced slower than this rate, the block gas + // cost is decreased. + TargetBlockRate = 2 // BlockGasCostStep is the rate at which the block gas cost changes per // second. // // This value was modified by the Apricot Phase 5 upgrade. BlockGasCostStep = 50_000 + + // MinBaseFee is the minimum base fee that is allowed after Apricot Phase 3 + // upgrade. + // + // This value modifies the previously used `ap3.MinBaseFee`. + // + // This value was modified in Etna. + MinBaseFee = 25 * params.GWei + + // MaxBaseFee is the maximum base fee that is allowed after Apricot Phase 3 + // upgrade. + // + // This value modifies the previously used `ap3.MaxBaseFee`. + MaxBaseFee = 1_000 * params.GWei ) // BlockGasCost calculates the required block gas cost. // -// cost = parentCost + step * (TargetBlockRate - timeElapsed) +// cost = parentCost + step * ([TargetBlockRate] - timeElapsed) // -// The returned cost is clamped to [MinBlockGasCost, MaxBlockGasCost]. +// The returned cost is clamped to [[MinBlockGasCost], [MaxBlockGasCost]]. func BlockGasCost( parentCost uint64, step uint64, From e3470ce5f7a968c4c18818b72d2e4e58fdcf8f0d Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 18 Feb 2025 15:43:53 -0800 Subject: [PATCH 60/69] format: as upstream --- accounts/abi/abi.go | 4 +- accounts/abi/abi_extra_test.go | 2 +- accounts/abi/abi_test.go | 6 +- accounts/abi/bind/auth.go | 12 +-- accounts/abi/bind/backend.go | 2 +- accounts/abi/bind/backends/simulated.go | 2 +- accounts/abi/bind/base.go | 6 +- accounts/abi/bind/base_test.go | 8 +- accounts/abi/bind/bind.go | 2 +- accounts/abi/bind/bind_extra_test.go | 4 +- accounts/abi/bind/bind_test.go | 74 +++++++++--------- accounts/abi/bind/template.go | 4 +- accounts/abi/bind/util.go | 4 +- accounts/abi/bind/util_test.go | 4 +- accounts/abi/error.go | 4 +- accounts/abi/event.go | 4 +- accounts/abi/event_test.go | 4 +- accounts/abi/method.go | 2 +- accounts/abi/pack.go | 4 +- accounts/abi/pack_test.go | 2 +- accounts/abi/packing_test.go | 2 +- accounts/abi/topics.go | 6 +- accounts/abi/topics_test.go | 4 +- accounts/abi/type.go | 2 +- accounts/abi/type_test.go | 2 +- accounts/abi/unpack.go | 2 +- accounts/abi/unpack_test.go | 2 +- cmd/abigen/main.go | 6 +- consensus/consensus.go | 2 +- consensus/dummy/consensus.go | 4 +- consensus/dummy/consensus_test.go | 2 +- consensus/dummy/dynamic_fees.go | 4 +- consensus/dummy/dynamic_fees_test.go | 6 +- constants/constants.go | 2 +- core/bench_test.go | 10 +-- core/block_validator.go | 2 +- core/blockchain.go | 16 ++-- core/blockchain_log_test.go | 6 +- core/blockchain_reader.go | 8 +- core/blockchain_repair_test.go | 8 +- core/blockchain_snapshot_test.go | 6 +- core/blockchain_test.go | 10 +-- core/bloom_indexer.go | 6 +- core/bloombits/matcher.go | 4 +- core/bloombits/matcher_test.go | 2 +- core/chain_indexer.go | 8 +- core/chain_indexer_test.go | 2 +- core/chain_makers.go | 8 +- core/chain_makers_test.go | 8 +- core/events.go | 2 +- core/evm.go | 8 +- core/extstate/statedb.go | 4 +- core/extstate/test_statedb.go | 2 +- core/gen_genesis.go | 8 +- core/genesis.go | 14 ++-- core/genesis_extra_test.go | 4 +- core/genesis_test.go | 10 +-- core/headerchain.go | 6 +- core/headerchain_test.go | 4 +- core/mkalloc.go | 4 +- core/predicate_check.go | 4 +- core/predicate_check_test.go | 2 +- core/rawdb/accessors_chain.go | 8 +- core/rawdb/accessors_chain_test.go | 4 +- core/rawdb/accessors_indexes.go | 8 +- core/rawdb/accessors_indexes_test.go | 6 +- core/rawdb/accessors_metadata.go | 8 +- core/rawdb/accessors_snapshot.go | 6 +- core/rawdb/accessors_state.go | 6 +- core/rawdb/accessors_state_sync.go | 6 +- core/rawdb/accessors_state_sync_test.go | 2 +- core/rawdb/accessors_trie.go | 8 +- core/rawdb/chain_iterator.go | 10 +-- core/rawdb/chain_iterator_test.go | 2 +- core/rawdb/database.go | 12 +-- core/rawdb/key_length_iterator.go | 2 +- core/rawdb/schema.go | 4 +- core/rawdb/table.go | 2 +- core/rawdb/table_test.go | 2 +- core/rlp_test.go | 6 +- core/state/database.go | 16 ++-- core/state/dump.go | 2 +- core/state/pruner/bloom.go | 4 +- core/state/pruner/pruner.go | 12 +-- core/state/snapshot/context.go | 4 +- core/state/snapshot/conversion.go | 10 +-- core/state/snapshot/difflayer.go | 4 +- core/state/snapshot/difflayer_test.go | 6 +- core/state/snapshot/disklayer.go | 8 +- core/state/snapshot/disklayer_test.go | 6 +- core/state/snapshot/generate.go | 12 +-- core/state/snapshot/generate_test.go | 14 ++-- core/state/snapshot/iterator.go | 6 +- core/state/snapshot/iterator_binary.go | 2 +- core/state/snapshot/iterator_fast.go | 2 +- core/state/snapshot/iterator_test.go | 2 +- core/state/snapshot/journal.go | 10 +-- core/state/snapshot/snapshot.go | 12 +-- core/state/snapshot/snapshot_ext.go | 4 +- core/state/snapshot/snapshot_test.go | 4 +- core/state/snapshot/utils.go | 6 +- core/state/snapshot/wipe.go | 6 +- core/state/snapshot/wipe_test.go | 4 +- core/state/state_object_test.go | 2 +- core/state/state_test.go | 4 +- core/state/statedb_multicoin_test.go | 4 +- core/state_manager.go | 4 +- core/state_manager_test.go | 2 +- core/state_processor.go | 8 +- core/state_processor_ext.go | 2 +- core/state_processor_test.go | 8 +- core/state_transition.go | 8 +- core/state_transition_test.go | 8 +- core/test_blockchain.go | 6 +- core/txindexer.go | 4 +- core/txindexer_test.go | 6 +- core/txpool/blobpool/blobpool.go | 8 +- core/txpool/blobpool/blobpool_test.go | 12 +-- core/txpool/blobpool/config.go | 2 +- core/txpool/blobpool/evictheap.go | 2 +- core/txpool/blobpool/evictheap_test.go | 2 +- core/txpool/blobpool/interface.go | 2 +- core/txpool/blobpool/limbo.go | 6 +- core/txpool/legacypool/journal.go | 6 +- core/txpool/legacypool/legacypool.go | 8 +- core/txpool/legacypool/legacypool2_test.go | 6 +- core/txpool/legacypool/legacypool_test.go | 8 +- core/txpool/legacypool/list.go | 2 +- core/txpool/legacypool/list_test.go | 4 +- core/txpool/legacypool/noncer.go | 2 +- core/txpool/subpool.go | 4 +- core/txpool/txpool.go | 6 +- core/txpool/validation.go | 6 +- core/types.go | 2 +- core/types/account.go | 6 +- core/types/block.go | 6 +- core/types/block_ext.go | 2 +- core/types/block_test.go | 10 +-- core/types/gen_account.go | 6 +- core/types/gen_header_json.go | 4 +- core/types/gen_header_rlp.go | 2 +- core/types/hashes.go | 6 +- core/types/hashing.go | 6 +- core/types/hashing_test.go | 12 +-- core/types/header_ext.go | 4 +- core/types/imports.go | 2 +- core/types/log.go | 2 +- core/types/rlp_fuzzer_test.go | 2 +- core/types/state_account.go | 2 +- core/types/types_test.go | 6 +- core/vm/runtime/env.go | 2 +- core/vm/runtime/runtime.go | 6 +- core/vm/runtime/runtime_example_test.go | 2 +- core/vm/runtime/runtime_test.go | 10 +-- eth/api.go | 2 +- eth/api_admin.go | 2 +- eth/api_backend.go | 10 +-- eth/api_backend_test.go | 4 +- eth/api_debug.go | 12 +-- eth/api_debug_test.go | 6 +- eth/backend.go | 12 +-- eth/bloombits.go | 2 +- eth/ethconfig/config.go | 2 +- eth/filters/api.go | 6 +- eth/filters/api_test.go | 2 +- eth/filters/bench_test.go | 6 +- eth/filters/filter.go | 2 +- eth/filters/filter_system.go | 8 +- eth/filters/filter_system_test.go | 6 +- eth/filters/filter_test.go | 8 +- eth/gasestimator/gasestimator.go | 6 +- eth/gasprice/fee_info_provider_test.go | 2 +- eth/gasprice/feehistory.go | 4 +- eth/gasprice/feehistory_test.go | 2 +- eth/gasprice/gasprice.go | 10 +-- eth/gasprice/gasprice_test.go | 8 +- eth/state_accessor.go | 10 +-- eth/tracers/api.go | 14 ++-- eth/tracers/api_test.go | 12 +-- eth/tracers/tracers.go | 4 +- eth/tracers/tracers_test.go | 8 +- ethclient/corethclient/corethclient.go | 4 +- ethclient/ethclient.go | 4 +- ethclient/signer.go | 2 +- ethclient/simulated/backend.go | 2 +- ethclient/simulated/backend_test.go | 4 +- interfaces/interfaces.go | 4 +- internal/blocktest/test_hash.go | 2 +- internal/debug/api.go | 2 +- internal/debug/flags.go | 2 +- internal/debug/trace.go | 2 +- internal/ethapi/addrlock.go | 2 +- internal/ethapi/api.go | 24 +++--- internal/ethapi/api_extra.go | 6 +- internal/ethapi/api_test.go | 18 ++--- internal/ethapi/backend.go | 10 +-- internal/ethapi/errors.go | 2 +- internal/ethapi/transaction_args.go | 10 +-- internal/ethapi/transaction_args_test.go | 4 +- internal/shutdowncheck/shutdown_tracker.go | 6 +- metrics/cpu_enabled.go | 2 +- metrics/cputime_unix.go | 2 +- miner/miner.go | 4 +- miner/ordering.go | 2 +- miner/ordering_ext.go | 2 +- miner/ordering_test.go | 4 +- miner/worker.go | 8 +- nativeasset/contract.go | 6 +- nativeasset/contract_test.go | 6 +- node/api.go | 4 +- node/config.go | 8 +- node/node.go | 2 +- params/config.go | 2 +- params/config_libevm.go | 4 +- params/extras/config.go | 4 +- params/extras/precompile_upgrade.go | 2 +- params/extras/rules.go | 2 +- params/hooks_libevm.go | 8 +- params/protocol_params.go | 2 +- peer/network.go | 2 +- peer/peer_tracker.go | 2 +- plugin/evm/admin.go | 2 +- plugin/evm/api.go | 6 +- plugin/evm/atomic/export_tx.go | 4 +- plugin/evm/atomic/import_tx.go | 4 +- plugin/evm/atomic/mempool.go | 2 +- plugin/evm/atomic/tx.go | 2 +- plugin/evm/atomic_backend.go | 4 +- plugin/evm/atomic_state.go | 4 +- plugin/evm/atomic_syncer.go | 4 +- plugin/evm/atomic_syncer_test.go | 6 +- plugin/evm/atomic_trie.go | 12 +-- plugin/evm/atomic_trie_iterator.go | 4 +- plugin/evm/atomic_trie_iterator_test.go | 2 +- plugin/evm/atomic_trie_test.go | 2 +- plugin/evm/atomic_tx_repository.go | 4 +- plugin/evm/atomic_tx_repository_test.go | 2 +- plugin/evm/block.go | 6 +- plugin/evm/block_builder.go | 2 +- plugin/evm/block_verification.go | 4 +- plugin/evm/client/client.go | 4 +- plugin/evm/client/utils.go | 2 +- plugin/evm/config/config.go | 4 +- plugin/evm/config/config_test.go | 2 +- plugin/evm/database/wrapped_database.go | 2 +- plugin/evm/export_tx_test.go | 2 +- plugin/evm/ext_data_hashes.go | 2 +- plugin/evm/gossip.go | 4 +- plugin/evm/gossip_test.go | 6 +- plugin/evm/gossiper_eth_gossiping_test.go | 4 +- plugin/evm/import_tx_test.go | 2 +- plugin/evm/log.go | 2 +- plugin/evm/log_test.go | 2 +- plugin/evm/message/block_request.go | 2 +- plugin/evm/message/block_request_test.go | 2 +- plugin/evm/message/code_request.go | 2 +- plugin/evm/message/code_request_test.go | 2 +- plugin/evm/message/leafs_request.go | 4 +- plugin/evm/message/leafs_request_test.go | 2 +- plugin/evm/message/syncable.go | 4 +- plugin/evm/network_handler.go | 4 +- plugin/evm/prestate_tracer_test.go | 8 +- plugin/evm/syncervm_client.go | 6 +- plugin/evm/syncervm_server.go | 4 +- plugin/evm/syncervm_test.go | 12 +-- plugin/evm/tx_test.go | 2 +- plugin/evm/user.go | 2 +- plugin/evm/vm.go | 14 ++-- plugin/evm/vm_database.go | 4 +- plugin/evm/vm_test.go | 8 +- plugin/evm/vm_warp_test.go | 4 +- precompile/contract/contract.go | 2 +- precompile/contract/interfaces.go | 6 +- precompile/contract/mocks.go | 4 +- precompile/contract/utils.go | 2 +- precompile/contracts/warp/config.go | 6 +- precompile/contracts/warp/contract.go | 4 +- precompile/contracts/warp/contract_test.go | 2 +- .../contracts/warp/contract_warp_handler.go | 4 +- precompile/contracts/warp/module.go | 2 +- precompile/modules/module.go | 2 +- precompile/modules/registerer.go | 2 +- precompile/modules/registerer_test.go | 2 +- precompile/precompileconfig/config.go | 2 +- precompile/precompileconfig/mocks.go | 2 +- precompile/testutils/test_precompile.go | 2 +- predicate/predicate_bytes.go | 2 +- predicate/predicate_results.go | 2 +- predicate/predicate_results_test.go | 2 +- predicate/predicate_slots.go | 2 +- predicate/predicate_tx.go | 2 +- rpc/client.go | 2 +- rpc/client_test.go | 2 +- rpc/handler.go | 2 +- rpc/server.go | 2 +- rpc/service.go | 2 +- rpc/subscription_test.go | 2 +- rpc/types.go | 4 +- rpc/types_test.go | 4 +- rpc/websocket.go | 2 +- scripts/eth-allowed-packages.txt | 78 +++++++++---------- scripts/lint_allowed_eth_imports.sh | 2 +- signer/core/apitypes/types.go | 4 +- sync/client/client.go | 10 +-- sync/client/client_test.go | 6 +- sync/client/leaf_syncer.go | 4 +- sync/client/mock_client.go | 4 +- sync/handlers/block_request.go | 4 +- sync/handlers/block_request_test.go | 8 +- sync/handlers/code_request.go | 6 +- sync/handlers/code_request_test.go | 6 +- sync/handlers/handler.go | 2 +- sync/handlers/leafs_request.go | 12 +-- sync/handlers/leafs_request_test.go | 10 +-- sync/handlers/test_providers.go | 2 +- sync/statesync/code_syncer.go | 4 +- sync/statesync/code_syncer_test.go | 6 +- sync/statesync/state_syncer.go | 6 +- sync/statesync/sync_helpers.go | 6 +- sync/statesync/sync_test.go | 12 +-- sync/statesync/test_sync.go | 10 +-- sync/statesync/trie_queue.go | 4 +- sync/statesync/trie_segments.go | 8 +- sync/statesync/trie_sync_stats.go | 4 +- sync/statesync/trie_sync_tasks.go | 10 +-- sync/syncutils/iterators.go | 2 +- sync/syncutils/test_trie.go | 12 +-- tests/rlp_test_util.go | 2 +- triedb/hashdb/database.go | 18 ++--- triedb/pathdb/database.go | 14 ++-- triedb/pathdb/database_test.go | 12 +-- triedb/pathdb/difflayer.go | 8 +- triedb/pathdb/difflayer_test.go | 6 +- triedb/pathdb/disklayer.go | 10 +-- triedb/pathdb/errors.go | 4 +- triedb/pathdb/history.go | 4 +- triedb/pathdb/history_test.go | 8 +- triedb/pathdb/journal.go | 12 +-- triedb/pathdb/layertree.go | 6 +- triedb/pathdb/nodebuffer.go | 10 +-- triedb/pathdb/testutils.go | 8 +- utils/address_range.go | 2 +- utils/bytes.go | 2 +- utils/bytes_test.go | 2 +- utils/key.go | 4 +- vmerrs/vmerrs.go | 2 +- warp/aggregator/aggregator.go | 2 +- warp/backend.go | 2 +- warp/client.go | 2 +- warp/handlers/signature_request.go | 2 +- warp/service.go | 4 +- 351 files changed, 954 insertions(+), 954 deletions(-) diff --git a/accounts/abi/abi.go b/accounts/abi/abi.go index cb924a0189..1a6e224090 100644 --- a/accounts/abi/abi.go +++ b/accounts/abi/abi.go @@ -34,8 +34,8 @@ import ( "io" "math/big" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" ) // The ABI holds information about a contract's context and available diff --git a/accounts/abi/abi_extra_test.go b/accounts/abi/abi_extra_test.go index 32d3c2d0b5..52bce1b0a4 100644 --- a/accounts/abi/abi_extra_test.go +++ b/accounts/abi/abi_extra_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" ) diff --git a/accounts/abi/abi_test.go b/accounts/abi/abi_test.go index ee46105203..023ff5cc4e 100644 --- a/accounts/abi/abi_test.go +++ b/accounts/abi/abi_test.go @@ -36,9 +36,9 @@ import ( "strings" "testing" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/math" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/assert" ) diff --git a/accounts/abi/bind/auth.go b/accounts/abi/bind/auth.go index 5de9741d05..ec313dffbb 100644 --- a/accounts/abi/bind/auth.go +++ b/accounts/abi/bind/auth.go @@ -34,12 +34,12 @@ import ( "math/big" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/accounts" - "github.com/ava-labs/libevm/accounts/external" - "github.com/ava-labs/libevm/accounts/keystore" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/accounts/external" + "github.com/ethereum/go-ethereum/accounts/keystore" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/log" ) // ErrNoChainID is returned whenever the user failed to specify a chain id. diff --git a/accounts/abi/bind/backend.go b/accounts/abi/bind/backend.go index 1aaf78161b..4cd21c399b 100644 --- a/accounts/abi/bind/backend.go +++ b/accounts/abi/bind/backend.go @@ -33,7 +33,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/interfaces" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) var ( diff --git a/accounts/abi/bind/backends/simulated.go b/accounts/abi/bind/backends/simulated.go index 9dadf11482..f1594e525b 100644 --- a/accounts/abi/bind/backends/simulated.go +++ b/accounts/abi/bind/backends/simulated.go @@ -33,7 +33,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/ethclient/simulated" "github.com/ava-labs/coreth/interfaces" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // Verify that SimulatedBackend implements required interfaces diff --git a/accounts/abi/bind/base.go b/accounts/abi/bind/base.go index 92da2b79ac..f3132a6614 100644 --- a/accounts/abi/bind/base.go +++ b/accounts/abi/bind/base.go @@ -39,9 +39,9 @@ import ( "github.com/ava-labs/coreth/interfaces" "github.com/ava-labs/coreth/nativeasset" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/event" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/event" ) const basefeeWiggleMultiplier = 2 diff --git a/accounts/abi/bind/base_test.go b/accounts/abi/bind/base_test.go index d6c0a50e6e..0605dc2653 100644 --- a/accounts/abi/bind/base_test.go +++ b/accounts/abi/bind/base_test.go @@ -40,10 +40,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/interfaces" "github.com/ava-labs/coreth/nativeasset" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/rlp" "github.com/stretchr/testify/assert" ) diff --git a/accounts/abi/bind/bind.go b/accounts/abi/bind/bind.go index 4347ba8169..3dfbb6d243 100644 --- a/accounts/abi/bind/bind.go +++ b/accounts/abi/bind/bind.go @@ -40,7 +40,7 @@ import ( "unicode" "github.com/ava-labs/coreth/accounts/abi" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) // Lang is a target programming language selector to generate bindings for. diff --git a/accounts/abi/bind/bind_extra_test.go b/accounts/abi/bind/bind_extra_test.go index 80e5932648..661eca3296 100644 --- a/accounts/abi/bind/bind_extra_test.go +++ b/accounts/abi/bind/bind_extra_test.go @@ -16,8 +16,8 @@ import ( "github.com/ava-labs/coreth/ethclient/simulated" "github.com/ava-labs/coreth/node" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" ) // TestGetSenderNativeAssetCall checks that the NativeAssetCall proxies the diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index c1035f6b8a..a54919722c 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -35,7 +35,7 @@ import ( "strings" "testing" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) var bindTests = []struct { @@ -56,7 +56,7 @@ var bindTests = []struct { `contract NilContract {}`, []string{`606060405260068060106000396000f3606060405200`}, []string{`[]`}, - `"github.com/ava-labs/libevm/common"`, + `"github.com/ethereum/go-ethereum/common"`, ` if b, err := NewEmpty(common.Address{}, nil); b == nil || err != nil { t.Fatalf("combined binding (%v) nil or error (%v) not nil", b, nil) @@ -79,7 +79,7 @@ var bindTests = []struct { `https://ethereum.org/token`, []string{`60606040526040516107fd3803806107fd83398101604052805160805160a05160c051929391820192909101600160a060020a0333166000908152600360209081526040822086905581548551838052601f6002600019610100600186161502019093169290920482018390047f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56390810193919290918801908390106100e857805160ff19168380011785555b506101189291505b8082111561017157600081556001016100b4565b50506002805460ff19168317905550505050610658806101a56000396000f35b828001600101855582156100ac579182015b828111156100ac5782518260005055916020019190600101906100fa565b50508060016000509080519060200190828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061017557805160ff19168380011785555b506100c89291506100b4565b5090565b82800160010185558215610165579182015b8281111561016557825182600050559160200191906001019061018756606060405236156100775760e060020a600035046306fdde03811461007f57806323b872dd146100dc578063313ce5671461010e57806370a082311461011a57806395d89b4114610132578063a9059cbb1461018e578063cae9ca51146101bd578063dc3080f21461031c578063dd62ed3e14610341575b610365610002565b61036760008054602060026001831615610100026000190190921691909104601f810182900490910260809081016040526060828152929190828280156104eb5780601f106104c0576101008083540402835291602001916104eb565b6103d5600435602435604435600160a060020a038316600090815260036020526040812054829010156104f357610002565b6103e760025460ff1681565b6103d560043560036020526000908152604090205481565b610367600180546020600282841615610100026000190190921691909104601f810182900490910260809081016040526060828152929190828280156104eb5780601f106104c0576101008083540402835291602001916104eb565b610365600435602435600160a060020a033316600090815260036020526040902054819010156103f157610002565b60806020604435600481810135601f8101849004909302840160405260608381526103d5948235946024803595606494939101919081908382808284375094965050505050505060006000836004600050600033600160a060020a03168152602001908152602001600020600050600087600160a060020a031681526020019081526020016000206000508190555084905080600160a060020a0316638f4ffcb1338630876040518560e060020a0281526004018085600160a060020a0316815260200184815260200183600160a060020a03168152602001806020018281038252838181518152602001915080519060200190808383829060006004602084601f0104600f02600301f150905090810190601f1680156102f25780820380516001836020036101000a031916815260200191505b50955050505050506000604051808303816000876161da5a03f11561000257505050509392505050565b6005602090815260043560009081526040808220909252602435815220546103d59081565b60046020818152903560009081526040808220909252602435815220546103d59081565b005b60405180806020018281038252838181518152602001915080519060200190808383829060006004602084601f0104600f02600301f150905090810190601f1680156103c75780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60408051918252519081900360200190f35b6060908152602090f35b600160a060020a03821660009081526040902054808201101561041357610002565b806003600050600033600160a060020a03168152602001908152602001600020600082828250540392505081905550806003600050600084600160a060020a0316815260200190815260200160002060008282825054019250508190555081600160a060020a031633600160a060020a03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b820191906000526020600020905b8154815290600101906020018083116104ce57829003601f168201915b505050505081565b600160a060020a03831681526040812054808301101561051257610002565b600160a060020a0380851680835260046020908152604080852033949094168086529382528085205492855260058252808520938552929052908220548301111561055c57610002565b816003600050600086600160a060020a03168152602001908152602001600020600082828250540392505081905550816003600050600085600160a060020a03168152602001908152602001600020600082828250540192505081905550816005600050600086600160a060020a03168152602001908152602001600020600050600033600160a060020a0316815260200190815260200160002060008282825054019250508190555082600160a060020a031633600160a060020a03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3939250505056`}, []string{`[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"},{"name":"_extraData","type":"bytes"}],"name":"approveAndCall","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"spentAllowance","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"inputs":[{"name":"initialSupply","type":"uint256"},{"name":"tokenName","type":"string"},{"name":"decimalUnits","type":"uint8"},{"name":"tokenSymbol","type":"string"}],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]`}, - `"github.com/ava-labs/libevm/common"`, + `"github.com/ethereum/go-ethereum/common"`, ` if b, err := NewToken(common.Address{}, nil); b == nil || err != nil { t.Fatalf("binding (%v) nil or error (%v) not nil", b, nil) @@ -95,7 +95,7 @@ var bindTests = []struct { `https://ethereum.org/crowdsale`, []string{`606060408190526007805460ff1916905560a0806105a883396101006040529051608051915160c05160e05160008054600160a060020a03199081169095178155670de0b6b3a7640000958602600155603c9093024201600355930260045560058054909216909217905561052f90819061007990396000f36060604052361561006c5760e060020a600035046301cb3b20811461008257806329dcb0cf1461014457806338af3eed1461014d5780636e66f6e91461015f5780637a3a0e84146101715780637b3e5e7b1461017a578063a035b1fe14610183578063dc0d3dff1461018c575b61020060075460009060ff161561032357610002565b61020060035460009042106103205760025460015490106103cb576002548154600160a060020a0316908290606082818181858883f150915460025460408051600160a060020a039390931683526020830191909152818101869052517fe842aea7a5f1b01049d752008c53c52890b1a6daf660cf39e8eec506112bbdf6945090819003909201919050a15b60405160008054600160a060020a039081169230909116319082818181858883f150506007805460ff1916600117905550505050565b6103a160035481565b6103ab600054600160a060020a031681565b6103ab600554600160a060020a031681565b6103a160015481565b6103a160025481565b6103a160045481565b6103be60043560068054829081101561000257506000526002027ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f8101547ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d409190910154600160a060020a03919091169082565b005b505050815481101561000257906000526020600020906002020160005060008201518160000160006101000a815481600160a060020a030219169083021790555060208201518160010160005055905050806002600082828250540192505081905550600560009054906101000a9004600160a060020a0316600160a060020a031663a9059cbb3360046000505484046040518360e060020a0281526004018083600160a060020a03168152602001828152602001925050506000604051808303816000876161da5a03f11561000257505060408051600160a060020a03331681526020810184905260018183015290517fe842aea7a5f1b01049d752008c53c52890b1a6daf660cf39e8eec506112bbdf692509081900360600190a15b50565b5060a0604052336060908152346080819052600680546001810180835592939282908280158290116102025760020281600202836000526020600020918201910161020291905b8082111561039d57805473ffffffffffffffffffffffffffffffffffffffff19168155600060019190910190815561036a565b5090565b6060908152602090f35b600160a060020a03166060908152602090f35b6060918252608052604090f35b5b60065481101561010e576006805482908110156100025760009182526002027ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f0190600680549254600160a060020a0316928490811015610002576002027ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d40015460405190915082818181858883f19350505050507fe842aea7a5f1b01049d752008c53c52890b1a6daf660cf39e8eec506112bbdf660066000508281548110156100025760008290526002027ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f01548154600160a060020a039190911691908490811015610002576002027ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d40015460408051600160a060020a0394909416845260208401919091526000838201525191829003606001919050a16001016103cc56`}, []string{`[{"constant":false,"inputs":[],"name":"checkGoalReached","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"deadline","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"beneficiary","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":true,"inputs":[],"name":"tokenReward","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":true,"inputs":[],"name":"fundingGoal","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"amountRaised","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"price","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"funders","outputs":[{"name":"addr","type":"address"},{"name":"amount","type":"uint256"}],"type":"function"},{"inputs":[{"name":"ifSuccessfulSendTo","type":"address"},{"name":"fundingGoalInEthers","type":"uint256"},{"name":"durationInMinutes","type":"uint256"},{"name":"etherCostOfEachToken","type":"uint256"},{"name":"addressOfTokenUsedAsReward","type":"address"}],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"backer","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"isContribution","type":"bool"}],"name":"FundTransfer","type":"event"}]`}, - `"github.com/ava-labs/libevm/common"`, + `"github.com/ethereum/go-ethereum/common"`, ` if b, err := NewCrowdsale(common.Address{}, nil); b == nil || err != nil { t.Fatalf("binding (%v) nil or error (%v) not nil", b, nil) @@ -111,7 +111,7 @@ var bindTests = []struct { `https://ethereum.org/dao`, []string{`606060405260405160808061145f833960e06040529051905160a05160c05160008054600160a060020a03191633179055600184815560028490556003839055600780549182018082558280158290116100b8576003028160030283600052602060002091820191016100b891906101c8565b50506060919091015160029190910155600160a060020a0381166000146100a65760008054600160a060020a031916821790555b505050506111f18061026e6000396000f35b505060408051608081018252600080825260208281018290528351908101845281815292820192909252426060820152600780549194509250811015610002579081527fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c6889050815181546020848101517401000000000000000000000000000000000000000002600160a060020a03199290921690921760a060020a60ff021916178255604083015180516001848101805460008281528690209195600293821615610100026000190190911692909204601f9081018390048201949192919091019083901061023e57805160ff19168380011785555b50610072929150610226565b5050600060028201556001015b8082111561023a578054600160a860020a031916815560018181018054600080835592600290821615610100026000190190911604601f81901061020c57506101bb565b601f0160209004906000526020600020908101906101bb91905b8082111561023a5760008155600101610226565b5090565b828001600101855582156101af579182015b828111156101af57825182600050559160200191906001019061025056606060405236156100b95760e060020a6000350463013cf08b81146100bb578063237e9492146101285780633910682114610281578063400e3949146102995780635daf08ca146102a257806369bd34361461032f5780638160f0b5146103385780638da5cb5b146103415780639644fcbd14610353578063aa02a90f146103be578063b1050da5146103c7578063bcca1fd3146104b5578063d3c0715b146104dc578063eceb29451461058d578063f2fde38b1461067b575b005b61069c6004356004805482908110156100025790600052602060002090600a02016000506005810154815460018301546003840154600485015460068601546007870154600160a060020a03959095169750929560020194919360ff828116946101009093041692919089565b60408051602060248035600481810135601f81018590048502860185019096528585526107759581359591946044949293909201918190840183828082843750949650505050505050600060006004600050848154811015610002575090527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19e600a8402908101547f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b909101904210806101e65750600481015460ff165b8061026757508060000160009054906101000a9004600160a060020a03168160010160005054846040518084600160a060020a0316606060020a0281526014018381526020018280519060200190808383829060006004602084601f0104600f02600301f15090500193505050506040518091039020816007016000505414155b8061027757506001546005820154105b1561109257610002565b61077560043560066020526000908152604090205481565b61077560055481565b61078760043560078054829081101561000257506000526003026000805160206111d18339815191528101547fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c68a820154600160a060020a0382169260a060020a90920460ff16917fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c689019084565b61077560025481565b61077560015481565b610830600054600160a060020a031681565b604080516020604435600481810135601f81018490048402850184019095528484526100b9948135946024803595939460649492939101918190840183828082843750949650505050505050600080548190600160a060020a03908116339091161461084d57610002565b61077560035481565b604080516020604435600481810135601f8101849004840285018401909552848452610775948135946024803595939460649492939101918190840183828082843750506040805160209735808a0135601f81018a90048a0283018a019093528282529698976084979196506024909101945090925082915084018382808284375094965050505050505033600160a060020a031660009081526006602052604081205481908114806104ab5750604081205460078054909190811015610002579082526003026000805160206111d1833981519152015460a060020a900460ff16155b15610ce557610002565b6100b960043560243560443560005433600160a060020a03908116911614610b1857610002565b604080516020604435600481810135601f810184900484028501840190955284845261077594813594602480359593946064949293910191819084018382808284375094965050505050505033600160a060020a031660009081526006602052604081205481908114806105835750604081205460078054909190811015610002579082526003026000805160206111d18339815191520181505460a060020a900460ff16155b15610f1d57610002565b604080516020606435600481810135601f81018490048402850184019095528484526107759481359460248035956044359560849492019190819084018382808284375094965050505050505060006000600460005086815481101561000257908252600a027f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b01815090508484846040518084600160a060020a0316606060020a0281526014018381526020018280519060200190808383829060006004602084601f0104600f02600301f150905001935050505060405180910390208160070160005054149150610cdc565b6100b960043560005433600160a060020a03908116911614610f0857610002565b604051808a600160a060020a031681526020018981526020018060200188815260200187815260200186815260200185815260200184815260200183815260200182810382528981815460018160011615610100020316600290048152602001915080546001816001161561010002031660029004801561075e5780601f106107335761010080835404028352916020019161075e565b820191906000526020600020905b81548152906001019060200180831161074157829003601f168201915b50509a505050505050505050505060405180910390f35b60408051918252519081900360200190f35b60408051600160a060020a038616815260208101859052606081018390526080918101828152845460026001821615610100026000190190911604928201839052909160a08301908590801561081e5780601f106107f35761010080835404028352916020019161081e565b820191906000526020600020905b81548152906001019060200180831161080157829003601f168201915b50509550505050505060405180910390f35b60408051600160a060020a03929092168252519081900360200190f35b600160a060020a03851660009081526006602052604081205414156108a957604060002060078054918290556001820180825582801582901161095c5760030281600302836000526020600020918201910161095c9190610a4f565b600160a060020a03851660009081526006602052604090205460078054919350908390811015610002575060005250600381026000805160206111d183398151915201805474ff0000000000000000000000000000000000000000191660a060020a85021781555b60408051600160a060020a03871681526020810186905281517f27b022af4a8347100c7a041ce5ccf8e14d644ff05de696315196faae8cd50c9b929181900390910190a15050505050565b505050915081506080604051908101604052808681526020018581526020018481526020014281526020015060076000508381548110156100025790600052602060002090600302016000508151815460208481015160a060020a02600160a060020a03199290921690921774ff00000000000000000000000000000000000000001916178255604083015180516001848101805460008281528690209195600293821615610100026000190190911692909204601f90810183900482019491929190910190839010610ad357805160ff19168380011785555b50610b03929150610abb565b5050600060028201556001015b80821115610acf57805474ffffffffffffffffffffffffffffffffffffffffff1916815560018181018054600080835592600290821615610100026000190190911604601f819010610aa15750610a42565b601f016020900490600052602060002090810190610a4291905b80821115610acf5760008155600101610abb565b5090565b82800160010185558215610a36579182015b82811115610a36578251826000505591602001919060010190610ae5565b50506060919091015160029190910155610911565b600183905560028290556003819055604080518481526020810184905280820183905290517fa439d3fa452be5e0e1e24a8145e715f4fd8b9c08c96a42fd82a855a85e5d57de9181900360600190a1505050565b50508585846040518084600160a060020a0316606060020a0281526014018381526020018280519060200190808383829060006004602084601f0104600f02600301f150905001935050505060405180910390208160070160005081905550600260005054603c024201816003016000508190555060008160040160006101000a81548160ff0219169083021790555060008160040160016101000a81548160ff02191690830217905550600081600501600050819055507f646fec02522b41e7125cfc859a64fd4f4cefd5dc3b6237ca0abe251ded1fa881828787876040518085815260200184600160a060020a03168152602001838152602001806020018281038252838181518152602001915080519060200190808383829060006004602084601f0104600f02600301f150905090810190601f168015610cc45780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a1600182016005555b50949350505050565b6004805460018101808355909190828015829011610d1c57600a0281600a028360005260206000209182019101610d1c9190610db8565b505060048054929450918491508110156100025790600052602060002090600a02016000508054600160a060020a031916871781556001818101879055855160028381018054600082815260209081902096975091959481161561010002600019011691909104601f90810182900484019391890190839010610ed857805160ff19168380011785555b50610b6c929150610abb565b50506001015b80821115610acf578054600160a060020a03191681556000600182810182905560028381018054848255909281161561010002600019011604601f819010610e9c57505b5060006003830181905560048301805461ffff191690556005830181905560068301819055600783018190556008830180548282559082526020909120610db2916002028101905b80821115610acf57805474ffffffffffffffffffffffffffffffffffffffffff1916815560018181018054600080835592600290821615610100026000190190911604601f819010610eba57505b5050600101610e44565b601f016020900490600052602060002090810190610dfc9190610abb565b601f016020900490600052602060002090810190610e929190610abb565b82800160010185558215610da6579182015b82811115610da6578251826000505591602001919060010190610eea565b60008054600160a060020a0319168217905550565b600480548690811015610002576000918252600a027f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b01905033600160a060020a0316600090815260098201602052604090205490915060ff1660011415610f8457610002565b33600160a060020a031660009081526009820160205260409020805460ff1916600190811790915560058201805490910190558315610fcd576006810180546001019055610fda565b6006810180546000190190555b7fc34f869b7ff431b034b7b9aea9822dac189a685e0b015c7d1be3add3f89128e8858533866040518085815260200184815260200183600160a060020a03168152602001806020018281038252838181518152602001915080519060200190808383829060006004602084601f0104600f02600301f150905090810190601f16801561107a5780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a1509392505050565b6006810154600354901315611158578060000160009054906101000a9004600160a060020a0316600160a060020a03168160010160005054670de0b6b3a76400000284604051808280519060200190808383829060006004602084601f0104600f02600301f150905090810190601f1680156111225780820380516001836020036101000a031916815260200191505b5091505060006040518083038185876185025a03f15050505060048101805460ff191660011761ff00191661010017905561116d565b60048101805460ff191660011761ff00191690555b60068101546005820154600483015460408051888152602081019490945283810192909252610100900460ff166060830152517fd220b7272a8b6d0d7d6bcdace67b936a8f175e6d5c1b3ee438b72256b32ab3af9181900360800190a1509291505056a66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c688`}, []string{`[{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"proposals","outputs":[{"name":"recipient","type":"address"},{"name":"amount","type":"uint256"},{"name":"description","type":"string"},{"name":"votingDeadline","type":"uint256"},{"name":"executed","type":"bool"},{"name":"proposalPassed","type":"bool"},{"name":"numberOfVotes","type":"uint256"},{"name":"currentResult","type":"int256"},{"name":"proposalHash","type":"bytes32"}],"type":"function"},{"constant":false,"inputs":[{"name":"proposalNumber","type":"uint256"},{"name":"transactionBytecode","type":"bytes"}],"name":"executeProposal","outputs":[{"name":"result","type":"int256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"memberId","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numProposals","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"members","outputs":[{"name":"member","type":"address"},{"name":"canVote","type":"bool"},{"name":"name","type":"string"},{"name":"memberSince","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"debatingPeriodInMinutes","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"minimumQuorum","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":false,"inputs":[{"name":"targetMember","type":"address"},{"name":"canVote","type":"bool"},{"name":"memberName","type":"string"}],"name":"changeMembership","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"majorityMargin","outputs":[{"name":"","type":"int256"}],"type":"function"},{"constant":false,"inputs":[{"name":"beneficiary","type":"address"},{"name":"etherAmount","type":"uint256"},{"name":"JobDescription","type":"string"},{"name":"transactionBytecode","type":"bytes"}],"name":"newProposal","outputs":[{"name":"proposalID","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"minimumQuorumForProposals","type":"uint256"},{"name":"minutesForDebate","type":"uint256"},{"name":"marginOfVotesForMajority","type":"int256"}],"name":"changeVotingRules","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"proposalNumber","type":"uint256"},{"name":"supportsProposal","type":"bool"},{"name":"justificationText","type":"string"}],"name":"vote","outputs":[{"name":"voteID","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"proposalNumber","type":"uint256"},{"name":"beneficiary","type":"address"},{"name":"etherAmount","type":"uint256"},{"name":"transactionBytecode","type":"bytes"}],"name":"checkProposalCode","outputs":[{"name":"codeChecksOut","type":"bool"}],"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"type":"function"},{"inputs":[{"name":"minimumQuorumForProposals","type":"uint256"},{"name":"minutesForDebate","type":"uint256"},{"name":"marginOfVotesForMajority","type":"int256"},{"name":"congressLeader","type":"address"}],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"proposalID","type":"uint256"},{"indexed":false,"name":"recipient","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"description","type":"string"}],"name":"ProposalAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"proposalID","type":"uint256"},{"indexed":false,"name":"position","type":"bool"},{"indexed":false,"name":"voter","type":"address"},{"indexed":false,"name":"justification","type":"string"}],"name":"Voted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"proposalID","type":"uint256"},{"indexed":false,"name":"result","type":"int256"},{"indexed":false,"name":"quorum","type":"uint256"},{"indexed":false,"name":"active","type":"bool"}],"name":"ProposalTallied","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"member","type":"address"},{"indexed":false,"name":"isMember","type":"bool"}],"name":"MembershipChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"minimumQuorum","type":"uint256"},{"indexed":false,"name":"debatingPeriodInMinutes","type":"uint256"},{"indexed":false,"name":"majorityMargin","type":"int256"}],"name":"ChangeOfRules","type":"event"}]`}, - `"github.com/ava-labs/libevm/common"`, + `"github.com/ethereum/go-ethereum/common"`, ` if b, err := NewDAO(common.Address{}, nil); b == nil || err != nil { t.Fatalf("binding (%v) nil or error (%v) not nil", b, nil) @@ -138,7 +138,7 @@ var bindTests = []struct { ` "fmt" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" `, `if b, err := NewInputChecker(common.Address{}, nil); b == nil || err != nil { t.Fatalf("binding (%v) nil or error (%v) not nil", b, nil) @@ -176,7 +176,7 @@ var bindTests = []struct { ` "fmt" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" `, `if b, err := NewOutputChecker(common.Address{}, nil); b == nil || err != nil { t.Fatalf("binding (%v) nil or error (%v) not nil", b, nil) @@ -217,7 +217,7 @@ var bindTests = []struct { "math/big" "reflect" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" `, `if e, err := NewEventChecker(common.Address{}, nil); e == nil || err != nil { t.Fatalf("binding (%v) nil or error (%v) not nil", e, nil) @@ -300,7 +300,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -356,7 +356,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -402,7 +402,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -458,9 +458,9 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -508,7 +508,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -575,7 +575,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -619,7 +619,7 @@ var bindTests = []struct { ` "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/ava-labs/coreth/core/types" `, ` @@ -658,7 +658,7 @@ var bindTests = []struct { ` "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/ava-labs/coreth/core/types" `, ` @@ -707,7 +707,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -755,9 +755,9 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -832,7 +832,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -924,9 +924,9 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -1116,7 +1116,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -1251,7 +1251,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` @@ -1393,7 +1393,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -1459,7 +1459,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Initialize test accounts @@ -1567,7 +1567,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" "github.com/ava-labs/coreth/core/types" `, ` @@ -1630,7 +1630,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" "github.com/ava-labs/coreth/core/types" `, ` @@ -1693,7 +1693,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` // Generate a new random account and a funded simulator @@ -1754,7 +1754,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` key, _ := crypto.GenerateKey() @@ -1842,7 +1842,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` var ( @@ -1912,7 +1912,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, ` var ( @@ -1964,7 +1964,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, tester: ` var ( @@ -2012,7 +2012,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, tester: ` var ( @@ -2053,7 +2053,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" `, tester: ` var ( @@ -2088,7 +2088,7 @@ var bindTests = []struct { bytecode: []string{"0x6080604052348015600f57600080fd5b5060958061001e6000396000f3fe6080604052348015600f57600080fd5b5060043610603c5760003560e01c80639d993132146041578063d02767c7146049578063ffa02795146051575b600080fd5b60476059565b005b604f605b565b005b6057605d565b005b565b565b56fea26469706673582212200382ca602dff96a7e2ba54657985e2b4ac423a56abe4a1f0667bc635c4d4371f64736f6c63430008110033"}, abi: []string{`[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_param","type":"address"}],"name":"_1TestEvent","type":"event"},{"inputs":[],"name":"_1test","outputs":[],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"__1test","outputs":[],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"__2test","outputs":[],"stateMutability":"pure","type":"function"}]`}, imports: ` - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" `, tester: ` if b, err := NewNumericMethodName(common.Address{}, nil); b == nil || err != nil { diff --git a/accounts/abi/bind/template.go b/accounts/abi/bind/template.go index aa1de7f913..22dca1e71d 100644 --- a/accounts/abi/bind/template.go +++ b/accounts/abi/bind/template.go @@ -105,8 +105,8 @@ import ( "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/interfaces" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/event" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/event" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/accounts/abi/bind/util.go b/accounts/abi/bind/util.go index 508caf7cf2..378f7ef877 100644 --- a/accounts/abi/bind/util.go +++ b/accounts/abi/bind/util.go @@ -33,8 +33,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/interfaces" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) // WaitMined waits for tx to be mined on the blockchain. diff --git a/accounts/abi/bind/util_test.go b/accounts/abi/bind/util_test.go index e1311c47d9..ec30d8c832 100644 --- a/accounts/abi/bind/util_test.go +++ b/accounts/abi/bind/util_test.go @@ -37,8 +37,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/ethclient/simulated" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" ) var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") diff --git a/accounts/abi/error.go b/accounts/abi/error.go index 46b056c052..a968fd20c0 100644 --- a/accounts/abi/error.go +++ b/accounts/abi/error.go @@ -31,8 +31,8 @@ import ( "fmt" "strings" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" ) type Error struct { diff --git a/accounts/abi/event.go b/accounts/abi/event.go index 39b55bb62c..f4f0f5d92d 100644 --- a/accounts/abi/event.go +++ b/accounts/abi/event.go @@ -30,8 +30,8 @@ import ( "fmt" "strings" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" ) // Event is an event potentially triggered by the EVM's LOG mechanism. The Event diff --git a/accounts/abi/event_test.go b/accounts/abi/event_test.go index 63f9fb2ffe..4a254e9950 100644 --- a/accounts/abi/event_test.go +++ b/accounts/abi/event_test.go @@ -35,8 +35,8 @@ import ( "strings" "testing" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/accounts/abi/method.go b/accounts/abi/method.go index e437d8d2a9..1da260da2c 100644 --- a/accounts/abi/method.go +++ b/accounts/abi/method.go @@ -30,7 +30,7 @@ import ( "fmt" "strings" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" ) // FunctionType represents different types of functions a contract might have. diff --git a/accounts/abi/pack.go b/accounts/abi/pack.go index 830df0b390..9f9f2b23d5 100644 --- a/accounts/abi/pack.go +++ b/accounts/abi/pack.go @@ -32,8 +32,8 @@ import ( "math/big" "reflect" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/math" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" ) // packBytesSlice packs the given bytes as [L, V] as the canonical representation diff --git a/accounts/abi/pack_test.go b/accounts/abi/pack_test.go index c76866c369..b13de922a5 100644 --- a/accounts/abi/pack_test.go +++ b/accounts/abi/pack_test.go @@ -37,7 +37,7 @@ import ( "strings" "testing" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // TestPack tests the general pack/unpack tests in packing_test.go diff --git a/accounts/abi/packing_test.go b/accounts/abi/packing_test.go index 0c2ee00745..8e876dcaef 100644 --- a/accounts/abi/packing_test.go +++ b/accounts/abi/packing_test.go @@ -29,7 +29,7 @@ package abi import ( "math/big" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) type packUnpackTest struct { diff --git a/accounts/abi/topics.go b/accounts/abi/topics.go index 0e3cb383ee..03082f221e 100644 --- a/accounts/abi/topics.go +++ b/accounts/abi/topics.go @@ -33,9 +33,9 @@ import ( "math/big" "reflect" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/math" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/crypto" ) // packTopic packs rule into the corresponding hash value for a log's topic diff --git a/accounts/abi/topics_test.go b/accounts/abi/topics_test.go index cf9ca32b4f..53e4327bf6 100644 --- a/accounts/abi/topics_test.go +++ b/accounts/abi/topics_test.go @@ -32,8 +32,8 @@ import ( "reflect" "testing" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" ) func TestMakeTopics(t *testing.T) { diff --git a/accounts/abi/type.go b/accounts/abi/type.go index 93678f5578..75a6c15fd7 100644 --- a/accounts/abi/type.go +++ b/accounts/abi/type.go @@ -36,7 +36,7 @@ import ( "unicode" "unicode/utf8" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // Type enumerator diff --git a/accounts/abi/type_test.go b/accounts/abi/type_test.go index c55559167f..ad0daffe06 100644 --- a/accounts/abi/type_test.go +++ b/accounts/abi/type_test.go @@ -31,8 +31,8 @@ import ( "reflect" "testing" - "github.com/ava-labs/libevm/common" "github.com/davecgh/go-spew/spew" + "github.com/ethereum/go-ethereum/common" ) // typeWithoutStringer is a alias for the Type type which simply doesn't implement diff --git a/accounts/abi/unpack.go b/accounts/abi/unpack.go index c161c81767..b975cb8802 100644 --- a/accounts/abi/unpack.go +++ b/accounts/abi/unpack.go @@ -34,7 +34,7 @@ import ( "math/big" "reflect" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) var ( diff --git a/accounts/abi/unpack_test.go b/accounts/abi/unpack_test.go index ae55cf3250..d7f383a731 100644 --- a/accounts/abi/unpack_test.go +++ b/accounts/abi/unpack_test.go @@ -37,7 +37,7 @@ import ( "strings" "testing" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" ) diff --git a/cmd/abigen/main.go b/cmd/abigen/main.go index 2dd4a35682..a6f670ea4d 100644 --- a/cmd/abigen/main.go +++ b/cmd/abigen/main.go @@ -37,9 +37,9 @@ import ( "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/cmd/utils" "github.com/ava-labs/coreth/internal/flags" - "github.com/ava-labs/libevm/common/compiler" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common/compiler" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/log" "github.com/urfave/cli/v2" ) diff --git a/consensus/consensus.go b/consensus/consensus.go index 19252097c7..d4e247ceaf 100644 --- a/consensus/consensus.go +++ b/consensus/consensus.go @@ -33,7 +33,7 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // ChainHeaderReader defines a small collection of methods needed to access the local diff --git a/consensus/dummy/consensus.go b/consensus/dummy/consensus.go index 822ea8fe22..95a99628d1 100644 --- a/consensus/dummy/consensus.go +++ b/consensus/dummy/consensus.go @@ -16,8 +16,8 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/trie" ) var ( diff --git a/consensus/dummy/consensus_test.go b/consensus/dummy/consensus_test.go index 5c7c69cc3a..64a8439817 100644 --- a/consensus/dummy/consensus_test.go +++ b/consensus/dummy/consensus_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) func TestVerifyBlockFee(t *testing.T) { diff --git a/consensus/dummy/dynamic_fees.go b/consensus/dummy/dynamic_fees.go index 0d3355a97f..ad14f2b16d 100644 --- a/consensus/dummy/dynamic_fees.go +++ b/consensus/dummy/dynamic_fees.go @@ -11,8 +11,8 @@ import ( "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/math" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" ) var ( diff --git a/consensus/dummy/dynamic_fees_test.go b/consensus/dummy/dynamic_fees_test.go index 69f148eea4..c86daf0ffb 100644 --- a/consensus/dummy/dynamic_fees_test.go +++ b/consensus/dummy/dynamic_fees_test.go @@ -10,9 +10,9 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/math" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/constants/constants.go b/constants/constants.go index d1523eaa5b..2514f58119 100644 --- a/constants/constants.go +++ b/constants/constants.go @@ -3,7 +3,7 @@ package constants -import "github.com/ava-labs/libevm/common" +import "github.com/ethereum/go-ethereum/common" var ( BlackholeAddr = common.Address{ diff --git a/core/bench_test.go b/core/bench_test.go index 4e98a6a600..1150d1491d 100644 --- a/core/bench_test.go +++ b/core/bench_test.go @@ -35,11 +35,11 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/math" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethdb" ) func BenchmarkInsertChain_empty_memdb(b *testing.B) { diff --git a/core/block_validator.go b/core/block_validator.go index 2c0fdceaf3..3038ed8b5d 100644 --- a/core/block_validator.go +++ b/core/block_validator.go @@ -34,7 +34,7 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/trie" ) // BlockValidator is responsible for validating block headers, uncles and diff --git a/core/blockchain.go b/core/blockchain.go index 6998fbb57a..f2af24bce7 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -50,14 +50,14 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/triedb/hashdb" "github.com/ava-labs/coreth/triedb/pathdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/lru" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/event" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/lru" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/event" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/triedb" ) var ( diff --git a/core/blockchain_log_test.go b/core/blockchain_log_test.go index 1dc6b3a3dc..1d430f4089 100644 --- a/core/blockchain_log_test.go +++ b/core/blockchain_log_test.go @@ -13,9 +13,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" ) diff --git a/core/blockchain_reader.go b/core/blockchain_reader.go index 96199417ee..b023aea345 100644 --- a/core/blockchain_reader.go +++ b/core/blockchain_reader.go @@ -33,10 +33,10 @@ import ( "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/event" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/event" + "github.com/ethereum/go-ethereum/triedb" ) // CurrentHeader retrieves the current head header of the canonical chain. The diff --git a/core/blockchain_repair_test.go b/core/blockchain_repair_test.go index 4f29d198ce..6d9af7c2f4 100644 --- a/core/blockchain_repair_test.go +++ b/core/blockchain_repair_test.go @@ -38,10 +38,10 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/triedb" "github.com/stretchr/testify/require" ) diff --git a/core/blockchain_snapshot_test.go b/core/blockchain_snapshot_test.go index 510065b1b0..6a9e18c446 100644 --- a/core/blockchain_snapshot_test.go +++ b/core/blockchain_snapshot_test.go @@ -43,9 +43,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/ethdb" ) // snapshotTestBasic wraps the common testing fields in the snapshot tests. diff --git a/core/blockchain_test.go b/core/blockchain_test.go index 63fb388c4b..2bf4aef6ad 100644 --- a/core/blockchain_test.go +++ b/core/blockchain_test.go @@ -17,11 +17,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/params/extras" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/eth/tracers/logger" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/eth/tracers/logger" + "github.com/ethereum/go-ethereum/ethdb" "github.com/holiman/uint256" ) diff --git a/core/bloom_indexer.go b/core/bloom_indexer.go index 01152ec8f9..ab8bc706f1 100644 --- a/core/bloom_indexer.go +++ b/core/bloom_indexer.go @@ -23,9 +23,9 @@ import ( "github.com/ava-labs/coreth/core/bloombits" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/bitutil" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/bitutil" + "github.com/ethereum/go-ethereum/ethdb" ) const ( diff --git a/core/bloombits/matcher.go b/core/bloombits/matcher.go index 94bbb59c6b..532bc7af93 100644 --- a/core/bloombits/matcher.go +++ b/core/bloombits/matcher.go @@ -36,8 +36,8 @@ import ( "sync/atomic" "time" - "github.com/ava-labs/libevm/common/bitutil" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common/bitutil" + "github.com/ethereum/go-ethereum/crypto" ) // bloomIndexes represents the bit indexes inside the bloom filter that belong diff --git a/core/bloombits/matcher_test.go b/core/bloombits/matcher_test.go index 04318f3489..c095ec31e4 100644 --- a/core/bloombits/matcher_test.go +++ b/core/bloombits/matcher_test.go @@ -33,7 +33,7 @@ import ( "testing" "time" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) const testSectionSize = 4096 diff --git a/core/chain_indexer.go b/core/chain_indexer.go index e5b098fae0..05cbc54c76 100644 --- a/core/chain_indexer.go +++ b/core/chain_indexer.go @@ -37,10 +37,10 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/event" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/event" + "github.com/ethereum/go-ethereum/log" ) // ChainIndexerBackend defines the methods needed to process chain segments in diff --git a/core/chain_indexer_test.go b/core/chain_indexer_test.go index f284c33f45..3edf175d3d 100644 --- a/core/chain_indexer_test.go +++ b/core/chain_indexer_test.go @@ -37,7 +37,7 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // Runs multiple tests with randomized parameters. diff --git a/core/chain_makers.go b/core/chain_makers.go index 9a2d833cd7..fe529a3f3d 100644 --- a/core/chain_makers.go +++ b/core/chain_makers.go @@ -37,10 +37,10 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/triedb" "github.com/holiman/uint256" ) diff --git a/core/chain_makers_test.go b/core/chain_makers_test.go index 06b482388d..e2824ff81e 100644 --- a/core/chain_makers_test.go +++ b/core/chain_makers_test.go @@ -34,10 +34,10 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/triedb" ) func ExampleGenerateChain() { diff --git a/core/events.go b/core/events.go index 5a04f9b0ad..462d26d9ee 100644 --- a/core/events.go +++ b/core/events.go @@ -28,7 +28,7 @@ package core import ( "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // NewTxsEvent is posted when a batch of transactions enter the transaction pool. diff --git a/core/evm.go b/core/evm.go index 8f9559b44c..7b7825e27e 100644 --- a/core/evm.go +++ b/core/evm.go @@ -37,10 +37,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/predicate" - "github.com/ava-labs/libevm/common" - ethtypes "github.com/ava-labs/libevm/core/types" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/log" "github.com/holiman/uint256" ) diff --git a/core/extstate/statedb.go b/core/extstate/statedb.go index 1c81601064..46e225c734 100644 --- a/core/extstate/statedb.go +++ b/core/extstate/statedb.go @@ -9,8 +9,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/predicate" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" ) type VmStateDB interface { diff --git a/core/extstate/test_statedb.go b/core/extstate/test_statedb.go index f6ed3ed77c..aa967aac2b 100644 --- a/core/extstate/test_statedb.go +++ b/core/extstate/test_statedb.go @@ -8,7 +8,7 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/precompile/contract" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" ) diff --git a/core/gen_genesis.go b/core/gen_genesis.go index c3ffd954b3..b1b46a91ba 100644 --- a/core/gen_genesis.go +++ b/core/gen_genesis.go @@ -8,10 +8,10 @@ import ( "math/big" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/common/math" - "github.com/ava-labs/libevm/params" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/params" ) var _ = (*genesisSpecMarshaling)(nil) diff --git a/core/genesis.go b/core/genesis.go index 39b3a01397..d86f118d1f 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -38,13 +38,13 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/triedb/pathdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/common/math" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/triedb" "github.com/holiman/uint256" ) diff --git a/core/genesis_extra_test.go b/core/genesis_extra_test.go index 6701fefe0e..49121ad448 100644 --- a/core/genesis_extra_test.go +++ b/core/genesis_extra_test.go @@ -36,8 +36,8 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/triedb" "github.com/stretchr/testify/require" ) diff --git a/core/genesis_test.go b/core/genesis_test.go index 9fba3f209e..5ebeec3e77 100644 --- a/core/genesis_test.go +++ b/core/genesis_test.go @@ -41,12 +41,12 @@ import ( "github.com/ava-labs/coreth/precompile/contracts/warp" "github.com/ava-labs/coreth/triedb/pathdb" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/triedb" "github.com/davecgh/go-spew/spew" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/triedb" "github.com/stretchr/testify/require" ) diff --git a/core/headerchain.go b/core/headerchain.go index e7cf80ac4b..fe8f752d41 100644 --- a/core/headerchain.go +++ b/core/headerchain.go @@ -37,9 +37,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/lru" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/lru" + "github.com/ethereum/go-ethereum/ethdb" ) const ( diff --git a/core/headerchain_test.go b/core/headerchain_test.go index 5117e2871e..c9c088f03a 100644 --- a/core/headerchain_test.go +++ b/core/headerchain_test.go @@ -37,8 +37,8 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" ) func verifyUnbrokenCanonchain(bc *BlockChain) error { diff --git a/core/mkalloc.go b/core/mkalloc.go index 4fd247323e..f481249c60 100644 --- a/core/mkalloc.go +++ b/core/mkalloc.go @@ -43,8 +43,8 @@ import ( "strconv" "github.com/ava-labs/coreth/core" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/rlp" "golang.org/x/exp/slices" ) diff --git a/core/predicate_check.go b/core/predicate_check.go index 00671bcda6..7e19253686 100644 --- a/core/predicate_check.go +++ b/core/predicate_check.go @@ -12,8 +12,8 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/predicate" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) var ErrMissingPredicateContext = errors.New("missing predicate context") diff --git a/core/predicate_check_test.go b/core/predicate_check_test.go index de942c1a70..66808d977a 100644 --- a/core/predicate_check_test.go +++ b/core/predicate_check_test.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/precompile/precompileconfig" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" ) diff --git a/core/rawdb/accessors_chain.go b/core/rawdb/accessors_chain.go index dba05750a7..d63da4782a 100644 --- a/core/rawdb/accessors_chain.go +++ b/core/rawdb/accessors_chain.go @@ -35,10 +35,10 @@ import ( "github.com/ava-labs/coreth/consensus/misc/eip4844" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" ) // ReadCanonicalHash retrieves the hash assigned to a canonical block number. diff --git a/core/rawdb/accessors_chain_test.go b/core/rawdb/accessors_chain_test.go index 3ec409066e..1157eee792 100644 --- a/core/rawdb/accessors_chain_test.go +++ b/core/rawdb/accessors_chain_test.go @@ -27,8 +27,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/rlp" "golang.org/x/crypto/sha3" ) diff --git a/core/rawdb/accessors_indexes.go b/core/rawdb/accessors_indexes.go index afb50354c9..511fa39d8f 100644 --- a/core/rawdb/accessors_indexes.go +++ b/core/rawdb/accessors_indexes.go @@ -32,10 +32,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" ) // ReadTxLookupEntry retrieves the positional metadata associated with a transaction diff --git a/core/rawdb/accessors_indexes_test.go b/core/rawdb/accessors_indexes_test.go index e4fac23e75..1930d81e91 100644 --- a/core/rawdb/accessors_indexes_test.go +++ b/core/rawdb/accessors_indexes_test.go @@ -23,9 +23,9 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/internal/blocktest" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/rlp" ) var newTestHasher = blocktest.NewHasher diff --git a/core/rawdb/accessors_metadata.go b/core/rawdb/accessors_metadata.go index 3bfe634a12..c6ad7645a3 100644 --- a/core/rawdb/accessors_metadata.go +++ b/core/rawdb/accessors_metadata.go @@ -31,10 +31,10 @@ import ( "time" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" ) // ReadDatabaseVersion retrieves the version number of the database. diff --git a/core/rawdb/accessors_snapshot.go b/core/rawdb/accessors_snapshot.go index f091b63831..06a136ba89 100644 --- a/core/rawdb/accessors_snapshot.go +++ b/core/rawdb/accessors_snapshot.go @@ -27,9 +27,9 @@ package rawdb import ( - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" ) // ReadSnapshotRoot retrieves the root of the block whose state is contained in diff --git a/core/rawdb/accessors_state.go b/core/rawdb/accessors_state.go index 509dfba818..03cbf44b6c 100644 --- a/core/rawdb/accessors_state.go +++ b/core/rawdb/accessors_state.go @@ -29,9 +29,9 @@ package rawdb import ( "encoding/binary" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" ) // ReadPreimage retrieves a single preimage of the provided hash. diff --git a/core/rawdb/accessors_state_sync.go b/core/rawdb/accessors_state_sync.go index 0781a8c142..36ba9ef1bd 100644 --- a/core/rawdb/accessors_state_sync.go +++ b/core/rawdb/accessors_state_sync.go @@ -7,9 +7,9 @@ import ( "encoding/binary" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" ) // ReadSyncRoot reads the root corresponding to the main trie of an in-progress diff --git a/core/rawdb/accessors_state_sync_test.go b/core/rawdb/accessors_state_sync_test.go index 506e843c8b..5c51eb7bf3 100644 --- a/core/rawdb/accessors_state_sync_test.go +++ b/core/rawdb/accessors_state_sync_test.go @@ -6,7 +6,7 @@ package rawdb import ( "testing" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" ) diff --git a/core/rawdb/accessors_trie.go b/core/rawdb/accessors_trie.go index 742a462c7c..e148a4280b 100644 --- a/core/rawdb/accessors_trie.go +++ b/core/rawdb/accessors_trie.go @@ -30,10 +30,10 @@ import ( "fmt" "sync" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" "golang.org/x/crypto/sha3" ) diff --git a/core/rawdb/chain_iterator.go b/core/rawdb/chain_iterator.go index f4c79fd0b4..5f449e4b6c 100644 --- a/core/rawdb/chain_iterator.go +++ b/core/rawdb/chain_iterator.go @@ -32,11 +32,11 @@ import ( "time" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/prque" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/prque" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" ) type blockTxHashes struct { diff --git a/core/rawdb/chain_iterator_test.go b/core/rawdb/chain_iterator_test.go index 2086fa72b5..0e4e762789 100644 --- a/core/rawdb/chain_iterator_test.go +++ b/core/rawdb/chain_iterator_test.go @@ -34,7 +34,7 @@ import ( "testing" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) func TestChainIterator(t *testing.T) { diff --git a/core/rawdb/database.go b/core/rawdb/database.go index 1bf30508c5..75922eba5d 100644 --- a/core/rawdb/database.go +++ b/core/rawdb/database.go @@ -33,12 +33,12 @@ import ( "path/filepath" "time" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/ethdb/leveldb" - "github.com/ava-labs/libevm/ethdb/memorydb" - "github.com/ava-labs/libevm/ethdb/pebble" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/ethdb/leveldb" + "github.com/ethereum/go-ethereum/ethdb/memorydb" + "github.com/ethereum/go-ethereum/ethdb/pebble" + "github.com/ethereum/go-ethereum/log" "github.com/olekukonko/tablewriter" ) diff --git a/core/rawdb/key_length_iterator.go b/core/rawdb/key_length_iterator.go index 8d1a7d2f54..fe95d719f0 100644 --- a/core/rawdb/key_length_iterator.go +++ b/core/rawdb/key_length_iterator.go @@ -26,7 +26,7 @@ package rawdb -import "github.com/ava-labs/libevm/ethdb" +import "github.com/ethereum/go-ethereum/ethdb" // KeyLengthIterator is a wrapper for a database iterator that ensures only key-value pairs // with a specific key length will be returned. diff --git a/core/rawdb/schema.go b/core/rawdb/schema.go index 290a565b19..71dff23127 100644 --- a/core/rawdb/schema.go +++ b/core/rawdb/schema.go @@ -33,8 +33,8 @@ import ( "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/coreth/metrics" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" ) // The fields below define the low level database schema prefixing. diff --git a/core/rawdb/table.go b/core/rawdb/table.go index cb9156173a..5dc709080c 100644 --- a/core/rawdb/table.go +++ b/core/rawdb/table.go @@ -27,7 +27,7 @@ package rawdb import ( - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/ethdb" ) // table is a wrapper around a database that prefixes each key access with a pre- diff --git a/core/rawdb/table_test.go b/core/rawdb/table_test.go index a6f4b454f6..9cb913c2a1 100644 --- a/core/rawdb/table_test.go +++ b/core/rawdb/table_test.go @@ -30,7 +30,7 @@ import ( "bytes" "testing" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/ethdb" ) func TestTableDatabase(t *testing.T) { testTableDatabase(t, "prefix") } diff --git a/core/rlp_test.go b/core/rlp_test.go index f43f487aab..d6a36ef6b1 100644 --- a/core/rlp_test.go +++ b/core/rlp_test.go @@ -34,9 +34,9 @@ import ( "github.com/ava-labs/coreth/consensus/dummy" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/rlp" "golang.org/x/crypto/sha3" ) diff --git a/core/state/database.go b/core/state/database.go index b810bf2c3d..60f971fda7 100644 --- a/core/state/database.go +++ b/core/state/database.go @@ -31,15 +31,15 @@ import ( "fmt" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/lru" - ethstate "github.com/ava-labs/libevm/core/state" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/trie/utils" - "github.com/ava-labs/libevm/triedb" "github.com/crate-crypto/go-ipa/banderwagon" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/lru" + ethstate "github.com/ethereum/go-ethereum/core/state" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/trie/utils" + "github.com/ethereum/go-ethereum/triedb" ) const ( diff --git a/core/state/dump.go b/core/state/dump.go index deac606017..c3c6dde9d9 100644 --- a/core/state/dump.go +++ b/core/state/dump.go @@ -27,7 +27,7 @@ package state import ( - ethstate "github.com/ava-labs/libevm/core/state" + ethstate "github.com/ethereum/go-ethereum/core/state" ) type ( diff --git a/core/state/pruner/bloom.go b/core/state/pruner/bloom.go index a228b84f8f..b7f673b80d 100644 --- a/core/state/pruner/bloom.go +++ b/core/state/pruner/bloom.go @@ -32,8 +32,8 @@ import ( "os" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" bloomfilter "github.com/holiman/bloomfilter/v2" ) diff --git a/core/state/pruner/pruner.go b/core/state/pruner/pruner.go index a71ba5601b..a5940752f2 100644 --- a/core/state/pruner/pruner.go +++ b/core/state/pruner/pruner.go @@ -40,12 +40,12 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/triedb" ) const ( diff --git a/core/state/snapshot/context.go b/core/state/snapshot/context.go index 45acfbba29..35b22c6ea3 100644 --- a/core/state/snapshot/context.go +++ b/core/state/snapshot/context.go @@ -34,8 +34,8 @@ import ( "golang.org/x/exp/slog" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) // generatorStats is a collection of statistics gathered by the snapshot generator diff --git a/core/state/snapshot/conversion.go b/core/state/snapshot/conversion.go index ea2b8f7c79..350036d88f 100644 --- a/core/state/snapshot/conversion.go +++ b/core/state/snapshot/conversion.go @@ -37,11 +37,11 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie" ) // trieKV represents a trie key-value pair diff --git a/core/state/snapshot/difflayer.go b/core/state/snapshot/difflayer.go index 0e3b38d509..d8d3b750e2 100644 --- a/core/state/snapshot/difflayer.go +++ b/core/state/snapshot/difflayer.go @@ -36,8 +36,8 @@ import ( "time" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/rlp" bloomfilter "github.com/holiman/bloomfilter/v2" "golang.org/x/exp/slices" ) diff --git a/core/state/snapshot/difflayer_test.go b/core/state/snapshot/difflayer_test.go index 85e774fdec..24fc3fdc69 100644 --- a/core/state/snapshot/difflayer_test.go +++ b/core/state/snapshot/difflayer_test.go @@ -33,9 +33,9 @@ import ( "testing" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/ethdb/memorydb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethdb/memorydb" ) func copyDestructs(destructs map[common.Hash]struct{}) map[common.Hash]struct{} { diff --git a/core/state/snapshot/disklayer.go b/core/state/snapshot/disklayer.go index 87fc3f4e2f..9a8ae65943 100644 --- a/core/state/snapshot/disklayer.go +++ b/core/state/snapshot/disklayer.go @@ -34,10 +34,10 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/triedb" ) // diskLayer is a low level persistent snapshot built on top of a key-value store. diff --git a/core/state/snapshot/disklayer_test.go b/core/state/snapshot/disklayer_test.go index 1f76dbf1e0..6094e32fee 100644 --- a/core/state/snapshot/disklayer_test.go +++ b/core/state/snapshot/disklayer_test.go @@ -31,9 +31,9 @@ import ( "testing" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb/memorydb" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb/memorydb" + "github.com/ethereum/go-ethereum/rlp" ) // reverse reverses the contents of a byte slice. It's used to update random accs diff --git a/core/state/snapshot/generate.go b/core/state/snapshot/generate.go index 1021cd1ed6..21e47b8682 100644 --- a/core/state/snapshot/generate.go +++ b/core/state/snapshot/generate.go @@ -34,12 +34,12 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/triedb" ) const ( diff --git a/core/state/snapshot/generate_test.go b/core/state/snapshot/generate_test.go index fe1b33f17b..66044c3f17 100644 --- a/core/state/snapshot/generate_test.go +++ b/core/state/snapshot/generate_test.go @@ -36,13 +36,13 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/triedb/hashdb" "github.com/ava-labs/coreth/triedb/pathdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/trie/trienode" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ethereum/go-ethereum/triedb" "github.com/holiman/uint256" "golang.org/x/crypto/sha3" ) diff --git a/core/state/snapshot/iterator.go b/core/state/snapshot/iterator.go index addae92deb..746a69a1bc 100644 --- a/core/state/snapshot/iterator.go +++ b/core/state/snapshot/iterator.go @@ -32,9 +32,9 @@ import ( "sort" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - ethsnapshot "github.com/ava-labs/libevm/core/state/snapshot" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + ethsnapshot "github.com/ethereum/go-ethereum/core/state/snapshot" + "github.com/ethereum/go-ethereum/ethdb" ) // Iterator is an iterator to step over all the accounts or the specific diff --git a/core/state/snapshot/iterator_binary.go b/core/state/snapshot/iterator_binary.go index 68f95901f7..cff012402c 100644 --- a/core/state/snapshot/iterator_binary.go +++ b/core/state/snapshot/iterator_binary.go @@ -29,7 +29,7 @@ package snapshot import ( "bytes" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // binaryIterator is a simplistic iterator to step over the accounts or storage diff --git a/core/state/snapshot/iterator_fast.go b/core/state/snapshot/iterator_fast.go index d8dda5f71c..4e324ee28b 100644 --- a/core/state/snapshot/iterator_fast.go +++ b/core/state/snapshot/iterator_fast.go @@ -31,7 +31,7 @@ import ( "fmt" "sort" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "golang.org/x/exp/slices" ) diff --git a/core/state/snapshot/iterator_test.go b/core/state/snapshot/iterator_test.go index b2862407b2..d7b7e56cb3 100644 --- a/core/state/snapshot/iterator_test.go +++ b/core/state/snapshot/iterator_test.go @@ -35,7 +35,7 @@ import ( "testing" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // TestAccountIteratorBasics tests some simple single-layer(diff and disk) iteration diff --git a/core/state/snapshot/journal.go b/core/state/snapshot/journal.go index f793ffb832..b1d6c338b3 100644 --- a/core/state/snapshot/journal.go +++ b/core/state/snapshot/journal.go @@ -33,11 +33,11 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/triedb" ) // journalGenerator is a disk layer entry containing the generator progress marker. diff --git a/core/state/snapshot/snapshot.go b/core/state/snapshot/snapshot.go index b025498e0b..f96e6f1382 100644 --- a/core/state/snapshot/snapshot.go +++ b/core/state/snapshot/snapshot.go @@ -36,12 +36,12 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/metrics" - "github.com/ava-labs/libevm/common" - ethsnapshot "github.com/ava-labs/libevm/core/state/snapshot" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/libevm/stateconf" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + ethsnapshot "github.com/ethereum/go-ethereum/core/state/snapshot" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/libevm/stateconf" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/triedb" ) const ( diff --git a/core/state/snapshot/snapshot_ext.go b/core/state/snapshot/snapshot_ext.go index 8b73f83fcc..3566d7ed54 100644 --- a/core/state/snapshot/snapshot_ext.go +++ b/core/state/snapshot/snapshot_ext.go @@ -4,8 +4,8 @@ import ( "time" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" ) func (t *Tree) DiskAccountIterator(seek common.Hash) AccountIterator { diff --git a/core/state/snapshot/snapshot_test.go b/core/state/snapshot/snapshot_test.go index cc98830e13..91a59d48c3 100644 --- a/core/state/snapshot/snapshot_test.go +++ b/core/state/snapshot/snapshot_test.go @@ -35,8 +35,8 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/rlp" "github.com/holiman/uint256" ) diff --git a/core/state/snapshot/utils.go b/core/state/snapshot/utils.go index 4a31a25a76..f9e2db5ad6 100644 --- a/core/state/snapshot/utils.go +++ b/core/state/snapshot/utils.go @@ -32,9 +32,9 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" ) // CheckDanglingStorage iterates the snap storage data, and verifies that all diff --git a/core/state/snapshot/wipe.go b/core/state/snapshot/wipe.go index c5dffd648e..37963032e6 100644 --- a/core/state/snapshot/wipe.go +++ b/core/state/snapshot/wipe.go @@ -31,9 +31,9 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" ) // WipeSnapshot starts a goroutine to iterate over the entire key-value database diff --git a/core/state/snapshot/wipe_test.go b/core/state/snapshot/wipe_test.go index 5fc6110bd0..74afec5fce 100644 --- a/core/state/snapshot/wipe_test.go +++ b/core/state/snapshot/wipe_test.go @@ -31,8 +31,8 @@ import ( "testing" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb/memorydb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb/memorydb" ) // Tests that given a database with random data content, all parts of a snapshot diff --git a/core/state/state_object_test.go b/core/state/state_object_test.go index f5f59acb2f..96132277fe 100644 --- a/core/state/state_object_test.go +++ b/core/state/state_object_test.go @@ -7,7 +7,7 @@ import ( "bytes" "testing" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) func TestStateObjectPartition(t *testing.T) { diff --git a/core/state/state_test.go b/core/state/state_test.go index 1b9484514b..fce725f78b 100644 --- a/core/state/state_test.go +++ b/core/state/state_test.go @@ -31,8 +31,8 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" ) type stateEnv struct { diff --git a/core/state/statedb_multicoin_test.go b/core/state/statedb_multicoin_test.go index 95cc98ef71..a653d9f334 100644 --- a/core/state/statedb_multicoin_test.go +++ b/core/state/statedb_multicoin_test.go @@ -10,8 +10,8 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" "github.com/holiman/uint256" ) diff --git a/core/state_manager.go b/core/state_manager.go index 73dc6d3806..8fc7de11c3 100644 --- a/core/state_manager.go +++ b/core/state_manager.go @@ -32,8 +32,8 @@ import ( "time" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" ) func init() { diff --git a/core/state_manager_test.go b/core/state_manager_test.go index 32f74c2dda..2fb47add49 100644 --- a/core/state_manager_test.go +++ b/core/state_manager_test.go @@ -9,7 +9,7 @@ import ( "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/assert" ) diff --git a/core/state_processor.go b/core/state_processor.go index 563485f67e..67e59d9cf5 100644 --- a/core/state_processor.go +++ b/core/state_processor.go @@ -34,10 +34,10 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/log" ) // StateProcessor is a basic Processor, which takes care of transitioning diff --git a/core/state_processor_ext.go b/core/state_processor_ext.go index e1d6ef43b9..db17b15028 100644 --- a/core/state_processor_ext.go +++ b/core/state_processor_ext.go @@ -11,7 +11,7 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/precompile/contract" "github.com/ava-labs/coreth/precompile/modules" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) // ApplyPrecompileActivations checks if any of the precompiles specified by the chain config are enabled or disabled by the block diff --git a/core/state_processor_test.go b/core/state_processor_test.go index 64179f4290..682bc0e33e 100644 --- a/core/state_processor_test.go +++ b/core/state_processor_test.go @@ -40,10 +40,10 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/trie" "github.com/holiman/uint256" "golang.org/x/crypto/sha3" ) diff --git a/core/state_transition.go b/core/state_transition.go index 099692b9ce..c7a3186d81 100644 --- a/core/state_transition.go +++ b/core/state_transition.go @@ -35,10 +35,10 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/utils" "github.com/ava-labs/coreth/vmerrs" - "github.com/ava-labs/libevm/common" - cmath "github.com/ava-labs/libevm/common/math" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto/kzg4844" + "github.com/ethereum/go-ethereum/common" + cmath "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto/kzg4844" "github.com/holiman/uint256" ) diff --git a/core/state_transition_test.go b/core/state_transition_test.go index 0db4bcf578..28a37acdaf 100644 --- a/core/state_transition_test.go +++ b/core/state_transition_test.go @@ -37,10 +37,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/nativeasset" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - ethCrypto "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + ethCrypto "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" ) diff --git a/core/test_blockchain.go b/core/test_blockchain.go index 254d19ff43..fcabdc41b3 100644 --- a/core/test_blockchain.go +++ b/core/test_blockchain.go @@ -15,9 +15,9 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethdb" "github.com/holiman/uint256" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/core/txindexer.go b/core/txindexer.go index 4dc963b94c..39c5fe51b0 100644 --- a/core/txindexer.go +++ b/core/txindexer.go @@ -21,8 +21,8 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" ) // TxIndexProgress is the struct describing the progress for transaction indexing. diff --git a/core/txindexer_test.go b/core/txindexer_test.go index b1bbdc83db..5c212bc953 100644 --- a/core/txindexer_test.go +++ b/core/txindexer_test.go @@ -25,9 +25,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethdb" "github.com/stretchr/testify/require" ) diff --git a/core/txpool/blobpool/blobpool.go b/core/txpool/blobpool/blobpool.go index 63b363ca1c..63d79e4372 100644 --- a/core/txpool/blobpool/blobpool.go +++ b/core/txpool/blobpool/blobpool.go @@ -47,10 +47,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/event" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/event" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" "github.com/holiman/billy" "github.com/holiman/uint256" ) diff --git a/core/txpool/blobpool/blobpool_test.go b/core/txpool/blobpool/blobpool_test.go index a33dcbd56c..694ca2a971 100644 --- a/core/txpool/blobpool/blobpool_test.go +++ b/core/txpool/blobpool/blobpool_test.go @@ -47,12 +47,12 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/crypto/kzg4844" - "github.com/ava-labs/libevm/ethdb/memorydb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/crypto/kzg4844" + "github.com/ethereum/go-ethereum/ethdb/memorydb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" "github.com/holiman/billy" "github.com/holiman/uint256" ) diff --git a/core/txpool/blobpool/config.go b/core/txpool/blobpool/config.go index d7b94535a7..5df7885fb3 100644 --- a/core/txpool/blobpool/config.go +++ b/core/txpool/blobpool/config.go @@ -27,7 +27,7 @@ package blobpool import ( - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) // Config are the configuration parameters of the blob transaction pool. diff --git a/core/txpool/blobpool/evictheap.go b/core/txpool/blobpool/evictheap.go index 7c7525371c..0824ddf735 100644 --- a/core/txpool/blobpool/evictheap.go +++ b/core/txpool/blobpool/evictheap.go @@ -32,7 +32,7 @@ import ( "math" "sort" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/holiman/uint256" ) diff --git a/core/txpool/blobpool/evictheap_test.go b/core/txpool/blobpool/evictheap_test.go index 70bd772b5d..69b02447bf 100644 --- a/core/txpool/blobpool/evictheap_test.go +++ b/core/txpool/blobpool/evictheap_test.go @@ -32,7 +32,7 @@ import ( "testing" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/holiman/uint256" ) diff --git a/core/txpool/blobpool/interface.go b/core/txpool/blobpool/interface.go index d25250e887..c544efa872 100644 --- a/core/txpool/blobpool/interface.go +++ b/core/txpool/blobpool/interface.go @@ -30,7 +30,7 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // BlockChain defines the minimal set of methods needed to back a blob pool with diff --git a/core/txpool/blobpool/limbo.go b/core/txpool/blobpool/limbo.go index 541b1309e8..63f31031ab 100644 --- a/core/txpool/blobpool/limbo.go +++ b/core/txpool/blobpool/limbo.go @@ -30,9 +30,9 @@ import ( "errors" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" "github.com/holiman/billy" ) diff --git a/core/txpool/legacypool/journal.go b/core/txpool/legacypool/journal.go index f29d4f2855..c586cab543 100644 --- a/core/txpool/legacypool/journal.go +++ b/core/txpool/legacypool/journal.go @@ -33,9 +33,9 @@ import ( "os" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" ) // errNoActiveJournal is returned if a transaction is attempted to be inserted diff --git a/core/txpool/legacypool/legacypool.go b/core/txpool/legacypool/legacypool.go index c8c4d70c72..621bd5adc5 100644 --- a/core/txpool/legacypool/legacypool.go +++ b/core/txpool/legacypool/legacypool.go @@ -44,10 +44,10 @@ import ( "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/prque" - "github.com/ava-labs/libevm/event" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/prque" + "github.com/ethereum/go-ethereum/event" + "github.com/ethereum/go-ethereum/log" "github.com/holiman/uint256" ) diff --git a/core/txpool/legacypool/legacypool2_test.go b/core/txpool/legacypool/legacypool2_test.go index dd10a4ab46..566cfc820e 100644 --- a/core/txpool/legacypool/legacypool2_test.go +++ b/core/txpool/legacypool/legacypool2_test.go @@ -33,9 +33,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/event" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/event" "github.com/holiman/uint256" ) diff --git a/core/txpool/legacypool/legacypool_test.go b/core/txpool/legacypool/legacypool_test.go index a193510b2d..d62310cd40 100644 --- a/core/txpool/legacypool/legacypool_test.go +++ b/core/txpool/legacypool/legacypool_test.go @@ -45,10 +45,10 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/event" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/event" + "github.com/ethereum/go-ethereum/trie" "github.com/holiman/uint256" ) diff --git a/core/txpool/legacypool/list.go b/core/txpool/legacypool/list.go index be458113b2..0b523c3795 100644 --- a/core/txpool/legacypool/list.go +++ b/core/txpool/legacypool/list.go @@ -36,7 +36,7 @@ import ( "time" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/holiman/uint256" "golang.org/x/exp/slices" ) diff --git a/core/txpool/legacypool/list_test.go b/core/txpool/legacypool/list_test.go index d94dc5c683..116e80a707 100644 --- a/core/txpool/legacypool/list_test.go +++ b/core/txpool/legacypool/list_test.go @@ -32,8 +32,8 @@ import ( "testing" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" "github.com/holiman/uint256" ) diff --git a/core/txpool/legacypool/noncer.go b/core/txpool/legacypool/noncer.go index 425748d6f1..dd880a6ba3 100644 --- a/core/txpool/legacypool/noncer.go +++ b/core/txpool/legacypool/noncer.go @@ -30,7 +30,7 @@ import ( "sync" "github.com/ava-labs/coreth/core/state" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // noncer is a tiny virtual state database to manage the executable nonces of diff --git a/core/txpool/subpool.go b/core/txpool/subpool.go index 9059556094..4ebbf97c4f 100644 --- a/core/txpool/subpool.go +++ b/core/txpool/subpool.go @@ -32,8 +32,8 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/event" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/event" "github.com/holiman/uint256" ) diff --git a/core/txpool/txpool.go b/core/txpool/txpool.go index fc4ecf8bf5..adfc616a82 100644 --- a/core/txpool/txpool.go +++ b/core/txpool/txpool.go @@ -36,9 +36,9 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/metrics" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/event" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/event" + "github.com/ethereum/go-ethereum/log" ) var ( diff --git a/core/txpool/validation.go b/core/txpool/validation.go index fad1d39ad3..08206a7e6f 100644 --- a/core/txpool/validation.go +++ b/core/txpool/validation.go @@ -36,9 +36,9 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/vmerrs" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto/kzg4844" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto/kzg4844" + "github.com/ethereum/go-ethereum/log" ) var ( diff --git a/core/types.go b/core/types.go index 6339d7578b..e5e2e44774 100644 --- a/core/types.go +++ b/core/types.go @@ -29,7 +29,7 @@ package core import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/core/vm" + "github.com/ethereum/go-ethereum/core/vm" ) // Validator is an interface which defines the standard for block validation. It diff --git a/core/types/account.go b/core/types/account.go index efc0927770..bb0f4ca02e 100644 --- a/core/types/account.go +++ b/core/types/account.go @@ -23,9 +23,9 @@ import ( "fmt" "math/big" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/common/math" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/common/math" ) //go:generate go run github.com/fjl/gencodec -type Account -field-override accountMarshaling -out gen_account.go diff --git a/core/types/block.go b/core/types/block.go index b47048fa62..1be71c96d1 100644 --- a/core/types/block.go +++ b/core/types/block.go @@ -34,9 +34,9 @@ import ( "reflect" "sync/atomic" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/rlp" ) // A BlockNonce is a 64-bit hash which proves (combined with the diff --git a/core/types/block_ext.go b/core/types/block_ext.go index c186e5d241..5ebb7aeb31 100644 --- a/core/types/block_ext.go +++ b/core/types/block_ext.go @@ -6,7 +6,7 @@ package types import ( "math/big" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) func (b *Block) WithExtData(version uint32, extdata *[]byte) *Block { diff --git a/core/types/block_test.go b/core/types/block_test.go index 75bb428853..fb6b045aa6 100644 --- a/core/types/block_test.go +++ b/core/types/block_test.go @@ -33,11 +33,11 @@ import ( "testing" "github.com/ava-labs/coreth/internal/blocktest" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/math" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/params" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/params" + "github.com/ethereum/go-ethereum/rlp" ) // This test has been modified from https://github.com/ethereum/go-ethereum/blob/v1.9.21/core/types/block_test.go#L35 to fit diff --git a/core/types/gen_account.go b/core/types/gen_account.go index c3c7fb3fdf..4e475896a7 100644 --- a/core/types/gen_account.go +++ b/core/types/gen_account.go @@ -7,9 +7,9 @@ import ( "errors" "math/big" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/common/math" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/common/math" ) var _ = (*accountMarshaling)(nil) diff --git a/core/types/gen_header_json.go b/core/types/gen_header_json.go index 0c1f588944..632a6ed48e 100644 --- a/core/types/gen_header_json.go +++ b/core/types/gen_header_json.go @@ -7,8 +7,8 @@ import ( "errors" "math/big" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" ) var _ = (*headerMarshaling)(nil) diff --git a/core/types/gen_header_rlp.go b/core/types/gen_header_rlp.go index e7c98e851f..711a33b8ca 100644 --- a/core/types/gen_header_rlp.go +++ b/core/types/gen_header_rlp.go @@ -2,7 +2,7 @@ package types -import "github.com/ava-labs/libevm/rlp" +import "github.com/ethereum/go-ethereum/rlp" import "io" func (obj *Header) EncodeRLP(_w io.Writer) error { diff --git a/core/types/hashes.go b/core/types/hashes.go index 2a5ed05aa5..3d8a8a013b 100644 --- a/core/types/hashes.go +++ b/core/types/hashes.go @@ -27,9 +27,9 @@ package types import ( - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/log" ) var ( diff --git a/core/types/hashing.go b/core/types/hashing.go index b6b631c7bc..c7e03a2b03 100644 --- a/core/types/hashing.go +++ b/core/types/hashing.go @@ -30,9 +30,9 @@ import ( "bytes" "sync" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/rlp" "golang.org/x/crypto/sha3" ) diff --git a/core/types/hashing_test.go b/core/types/hashing_test.go index 94dd5631d2..a56c5f4941 100644 --- a/core/types/hashing_test.go +++ b/core/types/hashing_test.go @@ -36,12 +36,12 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/triedb" ) func TestDeriveSha(t *testing.T) { diff --git a/core/types/header_ext.go b/core/types/header_ext.go index e680ee7798..0a61055b6d 100644 --- a/core/types/header_ext.go +++ b/core/types/header_ext.go @@ -6,8 +6,8 @@ package types import ( "io" - ethtypes "github.com/ava-labs/libevm/core/types" - "github.com/ava-labs/libevm/rlp" + ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/rlp" ) // HeaderExtra is a struct that contains extra fields used by Avalanche diff --git a/core/types/imports.go b/core/types/imports.go index e286bc9b4c..b1761a4f16 100644 --- a/core/types/imports.go +++ b/core/types/imports.go @@ -4,7 +4,7 @@ package types import ( - ethtypes "github.com/ava-labs/libevm/core/types" + ethtypes "github.com/ethereum/go-ethereum/core/types" ) // The following types are used directly as their upstream definitions. diff --git a/core/types/log.go b/core/types/log.go index 5ddb090034..600415d979 100644 --- a/core/types/log.go +++ b/core/types/log.go @@ -26,7 +26,7 @@ package types -import ethtypes "github.com/ava-labs/libevm/core/types" +import ethtypes "github.com/ethereum/go-ethereum/core/types" // Log represents a contract log event. These events are generated by the LOG opcode and // stored/indexed by the node. diff --git a/core/types/rlp_fuzzer_test.go b/core/types/rlp_fuzzer_test.go index 4e3645874a..a3b9f72436 100644 --- a/core/types/rlp_fuzzer_test.go +++ b/core/types/rlp_fuzzer_test.go @@ -22,7 +22,7 @@ import ( "math/big" "testing" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/rlp" "github.com/holiman/uint256" ) diff --git a/core/types/state_account.go b/core/types/state_account.go index 0c3cb7ab8d..9d4299d7fe 100644 --- a/core/types/state_account.go +++ b/core/types/state_account.go @@ -27,7 +27,7 @@ package types import ( - ethtypes "github.com/ava-labs/libevm/core/types" + ethtypes "github.com/ethereum/go-ethereum/core/types" ) type ( diff --git a/core/types/types_test.go b/core/types/types_test.go index 7620aafb7f..7b68db9b4b 100644 --- a/core/types/types_test.go +++ b/core/types/types_test.go @@ -30,9 +30,9 @@ import ( "math/big" "testing" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/rlp" ) type devnull struct{ len int } diff --git a/core/vm/runtime/env.go b/core/vm/runtime/env.go index a59d623b79..8440a2cd61 100644 --- a/core/vm/runtime/env.go +++ b/core/vm/runtime/env.go @@ -28,7 +28,7 @@ package runtime import ( "github.com/ava-labs/coreth/core" - "github.com/ava-labs/libevm/core/vm" + "github.com/ethereum/go-ethereum/core/vm" ) func NewEnv(cfg *Config) *vm.EVM { diff --git a/core/vm/runtime/runtime.go b/core/vm/runtime/runtime.go index c66342e918..89bd4f194c 100644 --- a/core/vm/runtime/runtime.go +++ b/core/vm/runtime/runtime.go @@ -35,9 +35,9 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/params/extras" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" "github.com/holiman/uint256" ) diff --git a/core/vm/runtime/runtime_example_test.go b/core/vm/runtime/runtime_example_test.go index 82651d3f1d..9850e283be 100644 --- a/core/vm/runtime/runtime_example_test.go +++ b/core/vm/runtime/runtime_example_test.go @@ -30,7 +30,7 @@ import ( "fmt" "github.com/ava-labs/coreth/core/vm/runtime" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) func ExampleExecute() { diff --git a/core/vm/runtime/runtime_test.go b/core/vm/runtime/runtime_test.go index bef1a5bd93..b0b72e6f54 100644 --- a/core/vm/runtime/runtime_test.go +++ b/core/vm/runtime/runtime_test.go @@ -41,13 +41,13 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/eth/tracers" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/asm" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/eth/tracers/logger" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/asm" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/eth/tracers/logger" // force-load js tracers to trigger registration - _ "github.com/ava-labs/libevm/eth/tracers/js" + _ "github.com/ethereum/go-ethereum/eth/tracers/js" "github.com/holiman/uint256" ) diff --git a/eth/api.go b/eth/api.go index dbea129203..5842cb5625 100644 --- a/eth/api.go +++ b/eth/api.go @@ -27,7 +27,7 @@ package eth import ( - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // EthereumAPI provides an API to access Ethereum full node-related information. diff --git a/eth/api_admin.go b/eth/api_admin.go index 1531af6427..f8945c1d2d 100644 --- a/eth/api_admin.go +++ b/eth/api_admin.go @@ -36,7 +36,7 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/rlp" ) // AdminAPI is the collection of Ethereum full node related APIs for node diff --git a/eth/api_backend.go b/eth/api_backend.go index 4cd3444ef4..7e6d00d82f 100644 --- a/eth/api_backend.go +++ b/eth/api_backend.go @@ -43,11 +43,11 @@ import ( "github.com/ava-labs/coreth/eth/tracers" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/accounts" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/event" + "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/event" ) var ErrUnfinalizedData = errors.New("cannot query unfinalized data") diff --git a/eth/api_backend_test.go b/eth/api_backend_test.go index e8fc92b569..e58fab0954 100644 --- a/eth/api_backend_test.go +++ b/eth/api_backend_test.go @@ -31,8 +31,8 @@ import ( "testing" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/rlp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/eth/api_debug.go b/eth/api_debug.go index e5073e4f63..8e926c7ead 100644 --- a/eth/api_debug.go +++ b/eth/api_debug.go @@ -37,12 +37,12 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/internal/ethapi" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie" ) // DebugAPI is the collection of Ethereum full node APIs for debugging the diff --git a/eth/api_debug_test.go b/eth/api_debug_test.go index 926e4de48d..e6690bd81f 100644 --- a/eth/api_debug_test.go +++ b/eth/api_debug_test.go @@ -36,13 +36,13 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/triedb" "github.com/holiman/uint256" "github.com/davecgh/go-spew/spew" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" "golang.org/x/exp/slices" ) diff --git a/eth/backend.go b/eth/backend.go index 50c22cd232..4a74dec4d8 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -53,12 +53,12 @@ import ( "github.com/ava-labs/coreth/node" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/accounts" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/event" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/event" + "github.com/ethereum/go-ethereum/log" ) // Config contains the configuration options of the ETH protocol. diff --git a/eth/bloombits.go b/eth/bloombits.go index 2fddfc0707..ecc0aaf157 100644 --- a/eth/bloombits.go +++ b/eth/bloombits.go @@ -30,7 +30,7 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common/bitutil" + "github.com/ethereum/go-ethereum/common/bitutil" ) const ( diff --git a/eth/ethconfig/config.go b/eth/ethconfig/config.go index 6032bc0e0b..e82d73d4e2 100644 --- a/eth/ethconfig/config.go +++ b/eth/ethconfig/config.go @@ -35,7 +35,7 @@ import ( "github.com/ava-labs/coreth/eth/gasprice" "github.com/ava-labs/coreth/miner" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // DefaultFullGPOConfig contains default gasprice oracle settings for full node. diff --git a/eth/filters/api.go b/eth/filters/api.go index 1ed17ec6db..fb8178ed63 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -39,9 +39,9 @@ import ( "github.com/ava-labs/coreth/interfaces" "github.com/ava-labs/coreth/internal/ethapi" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/event" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/event" ) var ( diff --git a/eth/filters/api_test.go b/eth/filters/api_test.go index 5bb2d0a6cb..72838b4d8c 100644 --- a/eth/filters/api_test.go +++ b/eth/filters/api_test.go @@ -22,7 +22,7 @@ import ( "testing" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) func TestUnmarshalJSONNewFilterArgs(t *testing.T) { diff --git a/eth/filters/bench_test.go b/eth/filters/bench_test.go index 26a478235a..77f0567870 100644 --- a/eth/filters/bench_test.go +++ b/eth/filters/bench_test.go @@ -35,9 +35,9 @@ import ( "github.com/ava-labs/coreth/core/bloombits" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/bitutil" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/bitutil" + "github.com/ethereum/go-ethereum/ethdb" ) func BenchmarkBloomBits512(b *testing.B) { diff --git a/eth/filters/filter.go b/eth/filters/filter.go index f58db13a5c..6b77ee68e1 100644 --- a/eth/filters/filter.go +++ b/eth/filters/filter.go @@ -35,7 +35,7 @@ import ( "github.com/ava-labs/coreth/core/bloombits" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // Filter can be used to retrieve and filter logs. diff --git a/eth/filters/filter_system.go b/eth/filters/filter_system.go index 425617b899..6a312df2ee 100644 --- a/eth/filters/filter_system.go +++ b/eth/filters/filter_system.go @@ -40,10 +40,10 @@ import ( "github.com/ava-labs/coreth/interfaces" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/event" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/event" + "github.com/ethereum/go-ethereum/log" ) // Config represents the configuration of the filter system. diff --git a/eth/filters/filter_system_test.go b/eth/filters/filter_system_test.go index ea180d0eed..073049a256 100644 --- a/eth/filters/filter_system_test.go +++ b/eth/filters/filter_system_test.go @@ -46,9 +46,9 @@ import ( "github.com/ava-labs/coreth/internal/ethapi" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/event" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/event" "github.com/stretchr/testify/require" ) diff --git a/eth/filters/filter_test.go b/eth/filters/filter_test.go index 583f97ad8e..b71360c62d 100644 --- a/eth/filters/filter_test.go +++ b/eth/filters/filter_test.go @@ -41,10 +41,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/triedb" "github.com/stretchr/testify/require" ) diff --git a/eth/gasestimator/gasestimator.go b/eth/gasestimator/gasestimator.go index 464904b5c4..fc8a669fd1 100644 --- a/eth/gasestimator/gasestimator.go +++ b/eth/gasestimator/gasestimator.go @@ -38,9 +38,9 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/vmerrs" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/log" ) // Options are the contextual parameters to execute the requested call. diff --git a/eth/gasprice/fee_info_provider_test.go b/eth/gasprice/fee_info_provider_test.go index c157b3fc97..182c3378ea 100644 --- a/eth/gasprice/fee_info_provider_test.go +++ b/eth/gasprice/fee_info_provider_test.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" ) diff --git a/eth/gasprice/feehistory.go b/eth/gasprice/feehistory.go index cd955414a9..448c2a69db 100644 --- a/eth/gasprice/feehistory.go +++ b/eth/gasprice/feehistory.go @@ -35,8 +35,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) var ( diff --git a/eth/gasprice/feehistory_test.go b/eth/gasprice/feehistory_test.go index f4ef530415..f8234d1d18 100644 --- a/eth/gasprice/feehistory_test.go +++ b/eth/gasprice/feehistory_test.go @@ -38,7 +38,7 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) func TestFeeHistory(t *testing.T) { diff --git a/eth/gasprice/gasprice.go b/eth/gasprice/gasprice.go index ca8fff8bf1..31a2c7b554 100644 --- a/eth/gasprice/gasprice.go +++ b/eth/gasprice/gasprice.go @@ -37,11 +37,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/lru" - "github.com/ava-labs/libevm/common/math" - "github.com/ava-labs/libevm/event" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/lru" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/event" + "github.com/ethereum/go-ethereum/log" "golang.org/x/exp/slices" ) diff --git a/eth/gasprice/gasprice_test.go b/eth/gasprice/gasprice_test.go index 1b1f2379cf..f38c3a5b2c 100644 --- a/eth/gasprice/gasprice_test.go +++ b/eth/gasprice/gasprice_test.go @@ -39,10 +39,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/event" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/event" "github.com/stretchr/testify/require" ) diff --git a/eth/state_accessor.go b/eth/state_accessor.go index 858fa7ce73..dc02b8f033 100644 --- a/eth/state_accessor.go +++ b/eth/state_accessor.go @@ -37,11 +37,11 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/eth/tracers" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/triedb" ) // noopReleaser is returned in case there is no operation expected diff --git a/eth/tracers/api.go b/eth/tracers/api.go index b439f3171d..9f669e08fc 100644 --- a/eth/tracers/api.go +++ b/eth/tracers/api.go @@ -44,13 +44,13 @@ import ( "github.com/ava-labs/coreth/internal/ethapi" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/eth/tracers/logger" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/eth/tracers/logger" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" ) const ( diff --git a/eth/tracers/api_test.go b/eth/tracers/api_test.go index e91108822d..2dc7149cc2 100644 --- a/eth/tracers/api_test.go +++ b/eth/tracers/api_test.go @@ -46,12 +46,12 @@ import ( "github.com/ava-labs/coreth/internal/ethapi" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/eth/tracers/logger" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/eth/tracers/logger" + "github.com/ethereum/go-ethereum/ethdb" "golang.org/x/exp/slices" ) diff --git a/eth/tracers/tracers.go b/eth/tracers/tracers.go index e235b4c5e6..1b17ad650b 100644 --- a/eth/tracers/tracers.go +++ b/eth/tracers/tracers.go @@ -21,8 +21,8 @@ import ( "errors" "fmt" - "github.com/ava-labs/libevm/core/vm" - ethtracers "github.com/ava-labs/libevm/eth/tracers" + "github.com/ethereum/go-ethereum/core/vm" + ethtracers "github.com/ethereum/go-ethereum/eth/tracers" ) // Context contains some contextual infos for a transaction execution that is not diff --git a/eth/tracers/tracers_test.go b/eth/tracers/tracers_test.go index b8703f9772..b92d033b16 100644 --- a/eth/tracers/tracers_test.go +++ b/eth/tracers/tracers_test.go @@ -35,10 +35,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/tests" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/eth/tracers/logger" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/eth/tracers/logger" ) func BenchmarkTransactionTrace(b *testing.B) { diff --git a/ethclient/corethclient/corethclient.go b/ethclient/corethclient/corethclient.go index 47f8dcb987..448b10b6af 100644 --- a/ethclient/corethclient/corethclient.go +++ b/ethclient/corethclient/corethclient.go @@ -37,8 +37,8 @@ import ( "github.com/ava-labs/coreth/ethclient" "github.com/ava-labs/coreth/interfaces" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" ) // Client is a wrapper around rpc.Client that implements geth-specific functionality. diff --git a/ethclient/ethclient.go b/ethclient/ethclient.go index fda588e45b..422cf37fcb 100644 --- a/ethclient/ethclient.go +++ b/ethclient/ethclient.go @@ -38,8 +38,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/interfaces" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" // Force-load precompiles to trigger registration _ "github.com/ava-labs/coreth/precompile/registry" diff --git a/ethclient/signer.go b/ethclient/signer.go index 82b8ee48ca..ba647de1a6 100644 --- a/ethclient/signer.go +++ b/ethclient/signer.go @@ -31,7 +31,7 @@ import ( "math/big" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // senderFromServer is a types.Signer that remembers the sender address returned by the RPC diff --git a/ethclient/simulated/backend.go b/ethclient/simulated/backend.go index f58e3dff8b..c4a3cb8971 100644 --- a/ethclient/simulated/backend.go +++ b/ethclient/simulated/backend.go @@ -34,7 +34,7 @@ import ( "github.com/ava-labs/coreth/node" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) var _ eth.PushGossiper = (*fakePushGossiper)(nil) diff --git a/ethclient/simulated/backend_test.go b/ethclient/simulated/backend_test.go index 99b37b8996..34a4855cfb 100644 --- a/ethclient/simulated/backend_test.go +++ b/ethclient/simulated/backend_test.go @@ -28,8 +28,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" ) diff --git a/interfaces/interfaces.go b/interfaces/interfaces.go index d980d915ff..ec900b6e04 100644 --- a/interfaces/interfaces.go +++ b/interfaces/interfaces.go @@ -33,8 +33,8 @@ import ( "math/big" "github.com/ava-labs/coreth/core/types" - ethereum "github.com/ava-labs/libevm" - "github.com/ava-labs/libevm/common" + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/common" ) // NotFound is returned by API methods if the requested item does not exist. diff --git a/internal/blocktest/test_hash.go b/internal/blocktest/test_hash.go index 4dae6f75f7..014e9ff4b0 100644 --- a/internal/blocktest/test_hash.go +++ b/internal/blocktest/test_hash.go @@ -35,7 +35,7 @@ package blocktest import ( "hash" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "golang.org/x/crypto/sha3" ) diff --git a/internal/debug/api.go b/internal/debug/api.go index 044a601f3c..6ac4f5110b 100644 --- a/internal/debug/api.go +++ b/internal/debug/api.go @@ -45,7 +45,7 @@ import ( "sync" "time" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" "github.com/hashicorp/go-bexpr" "golang.org/x/exp/slog" ) diff --git a/internal/debug/flags.go b/internal/debug/flags.go index bb148bf40e..94cffe5a0e 100644 --- a/internal/debug/flags.go +++ b/internal/debug/flags.go @@ -37,7 +37,7 @@ import ( "runtime" "github.com/ava-labs/coreth/internal/flags" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" "github.com/mattn/go-colorable" "github.com/mattn/go-isatty" "github.com/urfave/cli/v2" diff --git a/internal/debug/trace.go b/internal/debug/trace.go index dd9a873595..12f7bfdb05 100644 --- a/internal/debug/trace.go +++ b/internal/debug/trace.go @@ -31,7 +31,7 @@ import ( "os" "runtime/trace" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) // StartGoTrace turns on tracing, writing to the given file. diff --git a/internal/ethapi/addrlock.go b/internal/ethapi/addrlock.go index 2cd32605c1..2d00fdd2e7 100644 --- a/internal/ethapi/addrlock.go +++ b/internal/ethapi/addrlock.go @@ -29,7 +29,7 @@ package ethapi import ( "sync" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) type AddrLocker struct { diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index a39fd3fbef..a0570f9026 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -42,19 +42,19 @@ import ( "github.com/ava-labs/coreth/eth/gasestimator" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/accounts" - "github.com/ava-labs/libevm/accounts/keystore" - "github.com/ava-labs/libevm/accounts/scwallet" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/common/math" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/eth/tracers/logger" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie" "github.com/davecgh/go-spew/spew" + "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/accounts/keystore" + "github.com/ethereum/go-ethereum/accounts/scwallet" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/eth/tracers/logger" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie" "github.com/holiman/uint256" "github.com/tyler-smith/go-bip39" ) diff --git a/internal/ethapi/api_extra.go b/internal/ethapi/api_extra.go index 109b1ac2f4..a56830988f 100644 --- a/internal/ethapi/api_extra.go +++ b/internal/ethapi/api_extra.go @@ -10,9 +10,9 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/rlp" ) // GetChainConfig returns the chain config. diff --git a/internal/ethapi/api_test.go b/internal/ethapi/api_test.go index c3a6c7c880..4738c861f8 100644 --- a/internal/ethapi/api_test.go +++ b/internal/ethapi/api_test.go @@ -52,15 +52,15 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/accounts" - "github.com/ava-labs/libevm/accounts/keystore" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/crypto/kzg4844" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/event" + "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/accounts/keystore" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/crypto/kzg4844" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/event" "github.com/holiman/uint256" "github.com/stretchr/testify/require" "golang.org/x/exp/slices" diff --git a/internal/ethapi/backend.go b/internal/ethapi/backend.go index 5758b3b9d1..73ac329def 100644 --- a/internal/ethapi/backend.go +++ b/internal/ethapi/backend.go @@ -39,11 +39,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/accounts" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/event" + "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/event" ) // Backend interface provides the common API services (that are provided by diff --git a/internal/ethapi/errors.go b/internal/ethapi/errors.go index 84a186ecd0..928dded8b7 100644 --- a/internal/ethapi/errors.go +++ b/internal/ethapi/errors.go @@ -31,7 +31,7 @@ import ( "github.com/ava-labs/coreth/accounts/abi" "github.com/ava-labs/coreth/vmerrs" - "github.com/ava-labs/libevm/common/hexutil" + "github.com/ethereum/go-ethereum/common/hexutil" ) // revertError is an API error that encompasses an EVM revert with JSON error diff --git a/internal/ethapi/transaction_args.go b/internal/ethapi/transaction_args.go index 85d3804e67..f79a11367e 100644 --- a/internal/ethapi/transaction_args.go +++ b/internal/ethapi/transaction_args.go @@ -39,11 +39,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/common/math" - "github.com/ava-labs/libevm/crypto/kzg4844" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/crypto/kzg4844" + "github.com/ethereum/go-ethereum/log" "github.com/holiman/uint256" ) diff --git a/internal/ethapi/transaction_args_test.go b/internal/ethapi/transaction_args_test.go index 9cbef3f329..23690fd52d 100644 --- a/internal/ethapi/transaction_args_test.go +++ b/internal/ethapi/transaction_args_test.go @@ -35,8 +35,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" ) var _ feeBackend = &backendMock{} diff --git a/internal/shutdowncheck/shutdown_tracker.go b/internal/shutdowncheck/shutdown_tracker.go index 9499a91032..35382305c4 100644 --- a/internal/shutdowncheck/shutdown_tracker.go +++ b/internal/shutdowncheck/shutdown_tracker.go @@ -30,9 +30,9 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" ) // ShutdownTracker is a service that reports previous unclean shutdowns diff --git a/metrics/cpu_enabled.go b/metrics/cpu_enabled.go index 34f450e1ab..7b5fe4d207 100644 --- a/metrics/cpu_enabled.go +++ b/metrics/cpu_enabled.go @@ -30,7 +30,7 @@ package metrics import ( - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" "github.com/shirou/gopsutil/cpu" ) diff --git a/metrics/cputime_unix.go b/metrics/cputime_unix.go index c02303bdce..5a479d8aa8 100644 --- a/metrics/cputime_unix.go +++ b/metrics/cputime_unix.go @@ -32,7 +32,7 @@ package metrics import ( syscall "golang.org/x/sys/unix" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) // getProcessCPUTime retrieves the process' CPU time since program startup. diff --git a/miner/miner.go b/miner/miner.go index a20bb85b14..512b99c1bb 100644 --- a/miner/miner.go +++ b/miner/miner.go @@ -35,8 +35,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/precompile/precompileconfig" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/event" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/event" ) // Backend wraps all methods required for mining. diff --git a/miner/ordering.go b/miner/ordering.go index 2131e2e658..07fa390e4b 100644 --- a/miner/ordering.go +++ b/miner/ordering.go @@ -32,7 +32,7 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/holiman/uint256" ) diff --git a/miner/ordering_ext.go b/miner/ordering_ext.go index 31ec24024d..f9ce97ce90 100644 --- a/miner/ordering_ext.go +++ b/miner/ordering_ext.go @@ -5,7 +5,7 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) type TransactionsByPriceAndNonce = transactionsByPriceAndNonce diff --git a/miner/ordering_test.go b/miner/ordering_test.go index 6fa4797700..27d6b96761 100644 --- a/miner/ordering_test.go +++ b/miner/ordering_test.go @@ -35,8 +35,8 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" "github.com/holiman/uint256" ) diff --git a/miner/worker.go b/miner/worker.go index cc3af7cabd..bbabe7c269 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -48,10 +48,10 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/predicate" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/event" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/event" + "github.com/ethereum/go-ethereum/log" "github.com/holiman/uint256" ) diff --git a/nativeasset/contract.go b/nativeasset/contract.go index 523e55b33c..0d6c28337a 100644 --- a/nativeasset/contract.go +++ b/nativeasset/contract.go @@ -9,9 +9,9 @@ import ( "github.com/ava-labs/coreth/precompile/contract" "github.com/ava-labs/coreth/vmerrs" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/log" "github.com/holiman/uint256" ) diff --git a/nativeasset/contract_test.go b/nativeasset/contract_test.go index 06e0636687..715bd8e222 100644 --- a/nativeasset/contract_test.go +++ b/nativeasset/contract_test.go @@ -12,9 +12,9 @@ import ( . "github.com/ava-labs/coreth/nativeasset" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/vmerrs" - "github.com/ava-labs/libevm/common" - ethtypes "github.com/ava-labs/libevm/core/types" - "github.com/ava-labs/libevm/core/vm" + "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/core/vm" "github.com/holiman/uint256" "github.com/stretchr/testify/assert" diff --git a/node/api.go b/node/api.go index 1a404b0d10..f0be57313f 100644 --- a/node/api.go +++ b/node/api.go @@ -29,8 +29,8 @@ package node import ( "github.com/ava-labs/coreth/internal/debug" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/crypto" ) // apis returns the collection of built-in RPC APIs. diff --git a/node/config.go b/node/config.go index c96004e110..c0b675a45d 100644 --- a/node/config.go +++ b/node/config.go @@ -31,10 +31,10 @@ import ( "os" "path/filepath" - "github.com/ava-labs/libevm/accounts" - "github.com/ava-labs/libevm/accounts/external" - "github.com/ava-labs/libevm/accounts/keystore" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/accounts/external" + "github.com/ethereum/go-ethereum/accounts/keystore" + "github.com/ethereum/go-ethereum/log" ) // Config represents a small collection of configuration values to fine tune the diff --git a/node/node.go b/node/node.go index 64ddfe4d8c..3879e2b299 100644 --- a/node/node.go +++ b/node/node.go @@ -28,7 +28,7 @@ package node import ( "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/accounts" + "github.com/ethereum/go-ethereum/accounts" ) // Node is a container on which services can be registered. diff --git a/params/config.go b/params/config.go index e44e41e287..6e4e7dee7b 100644 --- a/params/config.go +++ b/params/config.go @@ -33,7 +33,7 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/utils" - ethparams "github.com/ava-labs/libevm/params" + ethparams "github.com/ethereum/go-ethereum/params" ) // Avalanche ChainIDs diff --git a/params/config_libevm.go b/params/config_libevm.go index 6ab46dbe7e..a9ef2aa5f3 100644 --- a/params/config_libevm.go +++ b/params/config_libevm.go @@ -9,8 +9,8 @@ import ( "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/precompile/modules" "github.com/ava-labs/coreth/precompile/precompileconfig" - "github.com/ava-labs/libevm/common" - ethparams "github.com/ava-labs/libevm/params" + "github.com/ethereum/go-ethereum/common" + ethparams "github.com/ethereum/go-ethereum/params" ) // libevmInit would ideally be a regular init() function, but it MUST be run diff --git a/params/extras/config.go b/params/extras/config.go index 14b17bc56e..9037c90f0e 100644 --- a/params/extras/config.go +++ b/params/extras/config.go @@ -10,8 +10,8 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - ethparams "github.com/ava-labs/libevm/params" + "github.com/ethereum/go-ethereum/common" + ethparams "github.com/ethereum/go-ethereum/params" ) // UpgradeConfig includes the following configs that may be specified in upgradeBytes: diff --git a/params/extras/precompile_upgrade.go b/params/extras/precompile_upgrade.go index 6f1522673d..42805b2962 100644 --- a/params/extras/precompile_upgrade.go +++ b/params/extras/precompile_upgrade.go @@ -11,7 +11,7 @@ import ( "github.com/ava-labs/coreth/precompile/modules" "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) var errNoKey = errors.New("PrecompileUpgrade cannot be empty") diff --git a/params/extras/rules.go b/params/extras/rules.go index 40b51a3ba2..d5a378739a 100644 --- a/params/extras/rules.go +++ b/params/extras/rules.go @@ -5,7 +5,7 @@ package extras import ( "github.com/ava-labs/coreth/precompile/precompileconfig" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) type Rules struct { diff --git a/params/hooks_libevm.go b/params/hooks_libevm.go index 759bd189cb..7bc68dc787 100644 --- a/params/hooks_libevm.go +++ b/params/hooks_libevm.go @@ -13,10 +13,10 @@ import ( "github.com/ava-labs/coreth/precompile/modules" "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/predicate" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/libevm" - "github.com/ava-labs/libevm/libevm/legacy" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/libevm" + "github.com/ethereum/go-ethereum/libevm/legacy" "github.com/holiman/uint256" "golang.org/x/exp/maps" ) diff --git a/params/protocol_params.go b/params/protocol_params.go index 6bdb5893c1..a09de7025c 100644 --- a/params/protocol_params.go +++ b/params/protocol_params.go @@ -29,7 +29,7 @@ package params import ( "math/big" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) const ( diff --git a/peer/network.go b/peer/network.go index 7ce1203b45..a4dfd015f6 100644 --- a/peer/network.go +++ b/peer/network.go @@ -12,7 +12,7 @@ import ( "golang.org/x/sync/semaphore" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/ids" diff --git a/peer/peer_tracker.go b/peer/peer_tracker.go index bc06e9b267..8070005ca6 100644 --- a/peer/peer_tracker.go +++ b/peer/peer_tracker.go @@ -13,7 +13,7 @@ import ( "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/version" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" "github.com/ava-labs/coreth/metrics" ) diff --git a/plugin/evm/admin.go b/plugin/evm/admin.go index bd3308e7ee..34595a0b0e 100644 --- a/plugin/evm/admin.go +++ b/plugin/evm/admin.go @@ -10,7 +10,7 @@ import ( "github.com/ava-labs/avalanchego/api" "github.com/ava-labs/avalanchego/utils/profiler" "github.com/ava-labs/coreth/plugin/evm/client" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) // Admin is the API service for admin API calls diff --git a/plugin/evm/api.go b/plugin/evm/api.go index d9a36a787f..49ad2a895f 100644 --- a/plugin/evm/api.go +++ b/plugin/evm/api.go @@ -18,9 +18,9 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/plugin/evm/client" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/log" ) // test constants diff --git a/plugin/evm/atomic/export_tx.go b/plugin/evm/atomic/export_tx.go index 0b092ee03a..7867573385 100644 --- a/plugin/evm/atomic/export_tx.go +++ b/plugin/evm/atomic/export_tx.go @@ -24,8 +24,8 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) var ( diff --git a/plugin/evm/atomic/import_tx.go b/plugin/evm/atomic/import_tx.go index 2d98e53fbb..e3104d9042 100644 --- a/plugin/evm/atomic/import_tx.go +++ b/plugin/evm/atomic/import_tx.go @@ -23,8 +23,8 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) var ( diff --git a/plugin/evm/atomic/mempool.go b/plugin/evm/atomic/mempool.go index 30b5f511c6..f74eacda7e 100644 --- a/plugin/evm/atomic/mempool.go +++ b/plugin/evm/atomic/mempool.go @@ -16,7 +16,7 @@ import ( "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/plugin/evm/config" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) const ( diff --git a/plugin/evm/atomic/tx.go b/plugin/evm/atomic/tx.go index 72337a4829..4d670d9c7f 100644 --- a/plugin/evm/atomic/tx.go +++ b/plugin/evm/atomic/tx.go @@ -11,7 +11,7 @@ import ( "math/big" "sort" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/holiman/uint256" "github.com/ava-labs/coreth/params/extras" diff --git a/plugin/evm/atomic_backend.go b/plugin/evm/atomic_backend.go index ecbfb6c2b6..2420021d6f 100644 --- a/plugin/evm/atomic_backend.go +++ b/plugin/evm/atomic_backend.go @@ -18,8 +18,8 @@ import ( "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/coreth/plugin/evm/atomic" syncclient "github.com/ava-labs/coreth/sync/client" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) var _ AtomicBackend = &atomicBackend{} diff --git a/plugin/evm/atomic_state.go b/plugin/evm/atomic_state.go index 7647a4cbab..911f1afb3a 100644 --- a/plugin/evm/atomic_state.go +++ b/plugin/evm/atomic_state.go @@ -10,8 +10,8 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) var _ AtomicState = &atomicState{} diff --git a/plugin/evm/atomic_syncer.go b/plugin/evm/atomic_syncer.go index 2da188d47a..6b173c8242 100644 --- a/plugin/evm/atomic_syncer.go +++ b/plugin/evm/atomic_syncer.go @@ -12,11 +12,11 @@ import ( "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/ava-labs/coreth/plugin/evm/message" syncclient "github.com/ava-labs/coreth/sync/client" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/trie" ) var ( diff --git a/plugin/evm/atomic_syncer_test.go b/plugin/evm/atomic_syncer_test.go index a3562c91ab..ab47d8431b 100644 --- a/plugin/evm/atomic_syncer_test.go +++ b/plugin/evm/atomic_syncer_test.go @@ -23,9 +23,9 @@ import ( "github.com/ava-labs/coreth/sync/handlers" handlerstats "github.com/ava-labs/coreth/sync/handlers/stats" "github.com/ava-labs/coreth/sync/syncutils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/triedb" ) const commitInterval = 1024 diff --git a/plugin/evm/atomic_trie.go b/plugin/evm/atomic_trie.go index 7966c79b72..a2d272d9fd 100644 --- a/plugin/evm/atomic_trie.go +++ b/plugin/evm/atomic_trie.go @@ -20,12 +20,12 @@ import ( "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/plugin/evm/database" "github.com/ava-labs/coreth/triedb/hashdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/trie/trienode" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ethereum/go-ethereum/triedb" ) const ( diff --git a/plugin/evm/atomic_trie_iterator.go b/plugin/evm/atomic_trie_iterator.go index 6fd636d744..588fc4e90c 100644 --- a/plugin/evm/atomic_trie_iterator.go +++ b/plugin/evm/atomic_trie_iterator.go @@ -12,8 +12,8 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/trie" ) const atomicTrieKeyLen = wrappers.LongLen + common.HashLength diff --git a/plugin/evm/atomic_trie_iterator_test.go b/plugin/evm/atomic_trie_iterator_test.go index 8da2e03127..21ec9913f9 100644 --- a/plugin/evm/atomic_trie_iterator_test.go +++ b/plugin/evm/atomic_trie_iterator_test.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/plugin/evm/atomic_trie_test.go b/plugin/evm/atomic_trie_test.go index 071cbfd5c8..2a82964e94 100644 --- a/plugin/evm/atomic_trie_test.go +++ b/plugin/evm/atomic_trie_test.go @@ -21,7 +21,7 @@ import ( "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) const testCommitInterval = 100 diff --git a/plugin/evm/atomic_tx_repository.go b/plugin/evm/atomic_tx_repository.go index 08c4c4d5c4..d1074f60f2 100644 --- a/plugin/evm/atomic_tx_repository.go +++ b/plugin/evm/atomic_tx_repository.go @@ -8,8 +8,8 @@ import ( "fmt" "time" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/database" diff --git a/plugin/evm/atomic_tx_repository_test.go b/plugin/evm/atomic_tx_repository_test.go index 9c5616004b..224f8fa726 100644 --- a/plugin/evm/atomic_tx_repository_test.go +++ b/plugin/evm/atomic_tx_repository_test.go @@ -13,7 +13,7 @@ import ( "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/utils/set" diff --git a/plugin/evm/block.go b/plugin/evm/block.go index 766167e21f..c462c693f8 100644 --- a/plugin/evm/block.go +++ b/plugin/evm/block.go @@ -10,9 +10,9 @@ import ( "fmt" "time" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/rawdb" diff --git a/plugin/evm/block_builder.go b/plugin/evm/block_builder.go index c621c7ff1b..721561ff40 100644 --- a/plugin/evm/block_builder.go +++ b/plugin/evm/block_builder.go @@ -16,7 +16,7 @@ import ( "github.com/ava-labs/avalanchego/snow" commonEng "github.com/ava-labs/avalanchego/snow/engine/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) const ( diff --git a/plugin/evm/block_verification.go b/plugin/evm/block_verification.go index 9b6eeaae65..2b6f929ad6 100644 --- a/plugin/evm/block_verification.go +++ b/plugin/evm/block_verification.go @@ -8,14 +8,14 @@ import ( "fmt" "math/big" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" safemath "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/coreth/constants" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/trie" ) var ( diff --git a/plugin/evm/client/client.go b/plugin/evm/client/client.go index cb7b9194db..a6716b4b27 100644 --- a/plugin/evm/client/client.go +++ b/plugin/evm/client/client.go @@ -8,8 +8,8 @@ import ( "errors" "fmt" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" "golang.org/x/exp/slog" "github.com/ava-labs/avalanchego/api" diff --git a/plugin/evm/client/utils.go b/plugin/evm/client/utils.go index 7d1e35e4ae..5ea43f4a20 100644 --- a/plugin/evm/client/utils.go +++ b/plugin/evm/client/utils.go @@ -3,7 +3,7 @@ package client -import "github.com/ava-labs/libevm/common" +import "github.com/ethereum/go-ethereum/common" func ParseEthAddress(addrStr string) (common.Address, error) { if !common.IsHexAddress(addrStr) { diff --git a/plugin/evm/config/config.go b/plugin/evm/config/config.go index 864c990911..f5bf644657 100644 --- a/plugin/evm/config/config.go +++ b/plugin/evm/config/config.go @@ -9,8 +9,8 @@ import ( "time" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" "github.com/spf13/cast" ) diff --git a/plugin/evm/config/config_test.go b/plugin/evm/config/config_test.go index 7b96a11742..ad13ebdfed 100644 --- a/plugin/evm/config/config_test.go +++ b/plugin/evm/config/config_test.go @@ -9,7 +9,7 @@ import ( "testing" "time" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/assert" ) diff --git a/plugin/evm/database/wrapped_database.go b/plugin/evm/database/wrapped_database.go index 86e3bbd239..f8a36913bb 100644 --- a/plugin/evm/database/wrapped_database.go +++ b/plugin/evm/database/wrapped_database.go @@ -7,7 +7,7 @@ import ( "errors" "github.com/ava-labs/avalanchego/database" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/ethdb" ) var ( diff --git a/plugin/evm/export_tx_test.go b/plugin/evm/export_tx_test.go index df6103555a..258762883d 100644 --- a/plugin/evm/export_tx_test.go +++ b/plugin/evm/export_tx_test.go @@ -20,7 +20,7 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/holiman/uint256" ) diff --git a/plugin/evm/ext_data_hashes.go b/plugin/evm/ext_data_hashes.go index ae2b4612cc..7648c3bcdb 100644 --- a/plugin/evm/ext_data_hashes.go +++ b/plugin/evm/ext_data_hashes.go @@ -4,7 +4,7 @@ import ( _ "embed" "encoding/json" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) var ( diff --git a/plugin/evm/gossip.go b/plugin/evm/gossip.go index 1197562865..16d632bd94 100644 --- a/plugin/evm/gossip.go +++ b/plugin/evm/gossip.go @@ -12,8 +12,8 @@ import ( "sync/atomic" "time" - ethcommon "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + ethcommon "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" "github.com/prometheus/client_golang/prometheus" "github.com/ava-labs/avalanchego/ids" diff --git a/plugin/evm/gossip_test.go b/plugin/evm/gossip_test.go index 03bb31431a..c690c04add 100644 --- a/plugin/evm/gossip_test.go +++ b/plugin/evm/gossip_test.go @@ -17,9 +17,9 @@ import ( "github.com/ava-labs/coreth/core/txpool/legacypool" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/core/vm" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/crypto" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/plugin/evm/gossiper_eth_gossiping_test.go b/plugin/evm/gossiper_eth_gossiping_test.go index e323308a58..64c68010e0 100644 --- a/plugin/evm/gossiper_eth_gossiping_test.go +++ b/plugin/evm/gossiper_eth_gossiping_test.go @@ -18,8 +18,8 @@ import ( commonEng "github.com/ava-labs/avalanchego/snow/engine/common" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/assert" diff --git a/plugin/evm/import_tx_test.go b/plugin/evm/import_tx_test.go index bc57aec0d3..eaf2b39cf3 100644 --- a/plugin/evm/import_tx_test.go +++ b/plugin/evm/import_tx_test.go @@ -9,7 +9,7 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/holiman/uint256" avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" diff --git a/plugin/evm/log.go b/plugin/evm/log.go index 83612ce03c..fe92f1fb7f 100644 --- a/plugin/evm/log.go +++ b/plugin/evm/log.go @@ -11,7 +11,7 @@ import ( "strings" "github.com/ava-labs/coreth/log" - ethlog "github.com/ava-labs/libevm/log" + ethlog "github.com/ethereum/go-ethereum/log" "golang.org/x/exp/slog" ) diff --git a/plugin/evm/log_test.go b/plugin/evm/log_test.go index eb61a4e5e5..b39fa8cc3c 100644 --- a/plugin/evm/log_test.go +++ b/plugin/evm/log_test.go @@ -7,7 +7,7 @@ import ( "os" "testing" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" "github.com/stretchr/testify/require" ) diff --git a/plugin/evm/message/block_request.go b/plugin/evm/message/block_request.go index 009e6b0155..f1f353f2f7 100644 --- a/plugin/evm/message/block_request.go +++ b/plugin/evm/message/block_request.go @@ -9,7 +9,7 @@ import ( "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) var ( diff --git a/plugin/evm/message/block_request_test.go b/plugin/evm/message/block_request_test.go index 7d5b286551..cd9070117d 100644 --- a/plugin/evm/message/block_request_test.go +++ b/plugin/evm/message/block_request_test.go @@ -8,7 +8,7 @@ import ( "math/rand" "testing" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/assert" ) diff --git a/plugin/evm/message/code_request.go b/plugin/evm/message/code_request.go index d1aeb7f2f6..cd1ffef844 100644 --- a/plugin/evm/message/code_request.go +++ b/plugin/evm/message/code_request.go @@ -9,7 +9,7 @@ import ( "strings" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) var _ Request = CodeRequest{} diff --git a/plugin/evm/message/code_request_test.go b/plugin/evm/message/code_request_test.go index 3faf12949d..88cedb54d4 100644 --- a/plugin/evm/message/code_request_test.go +++ b/plugin/evm/message/code_request_test.go @@ -8,7 +8,7 @@ import ( "math/rand" "testing" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/assert" ) diff --git a/plugin/evm/message/leafs_request.go b/plugin/evm/message/leafs_request.go index 32ae4dc45d..22629e62ef 100644 --- a/plugin/evm/message/leafs_request.go +++ b/plugin/evm/message/leafs_request.go @@ -8,8 +8,8 @@ import ( "fmt" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) const MaxCodeHashesPerRequest = 5 diff --git a/plugin/evm/message/leafs_request_test.go b/plugin/evm/message/leafs_request_test.go index 68784fe04c..ab6cab5124 100644 --- a/plugin/evm/message/leafs_request_test.go +++ b/plugin/evm/message/leafs_request_test.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/assert" ) diff --git a/plugin/evm/message/syncable.go b/plugin/evm/message/syncable.go index 680a18b421..c8631bbb5e 100644 --- a/plugin/evm/message/syncable.go +++ b/plugin/evm/message/syncable.go @@ -8,8 +8,8 @@ import ( "fmt" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" ) diff --git a/plugin/evm/network_handler.go b/plugin/evm/network_handler.go index 15dca8ce38..0a6df6e552 100644 --- a/plugin/evm/network_handler.go +++ b/plugin/evm/network_handler.go @@ -14,8 +14,8 @@ import ( syncStats "github.com/ava-labs/coreth/sync/handlers/stats" "github.com/ava-labs/coreth/warp" warpHandlers "github.com/ava-labs/coreth/warp/handlers" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/triedb" ) var _ message.RequestHandler = &networkHandler{} diff --git a/plugin/evm/prestate_tracer_test.go b/plugin/evm/prestate_tracer_test.go index 8de9762efa..3b38e52412 100644 --- a/plugin/evm/prestate_tracer_test.go +++ b/plugin/evm/prestate_tracer_test.go @@ -17,10 +17,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/eth/tracers" "github.com/ava-labs/coreth/tests" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/math" - ethtypes "github.com/ava-labs/libevm/core/types" - "github.com/ava-labs/libevm/core/vm" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" + ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/core/vm" ) func TestPrestateWithDiffModeANTTracer(t *testing.T) { diff --git a/plugin/evm/syncervm_client.go b/plugin/evm/syncervm_client.go index 2807b6b0da..0b704d6233 100644 --- a/plugin/evm/syncervm_client.go +++ b/plugin/evm/syncervm_client.go @@ -21,9 +21,9 @@ import ( "github.com/ava-labs/coreth/plugin/evm/message" syncclient "github.com/ava-labs/coreth/sync/client" "github.com/ava-labs/coreth/sync/statesync" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" ) const ( diff --git a/plugin/evm/syncervm_server.go b/plugin/evm/syncervm_server.go index f249169193..3bf051bf87 100644 --- a/plugin/evm/syncervm_server.go +++ b/plugin/evm/syncervm_server.go @@ -12,8 +12,8 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/plugin/evm/message" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) type stateSyncServerConfig struct { diff --git a/plugin/evm/syncervm_test.go b/plugin/evm/syncervm_test.go index 65aff9b080..66d5c95443 100644 --- a/plugin/evm/syncervm_test.go +++ b/plugin/evm/syncervm_test.go @@ -40,12 +40,12 @@ import ( statesyncclient "github.com/ava-labs/coreth/sync/client" "github.com/ava-labs/coreth/sync/statesync" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/triedb" ) func TestSkipStateSync(t *testing.T) { diff --git a/plugin/evm/tx_test.go b/plugin/evm/tx_test.go index 5e63eeb090..4001fa4ebc 100644 --- a/plugin/evm/tx_test.go +++ b/plugin/evm/tx_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/params/extras" diff --git a/plugin/evm/user.go b/plugin/evm/user.go index 4f004db867..8cb3f73f34 100644 --- a/plugin/evm/user.go +++ b/plugin/evm/user.go @@ -10,7 +10,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // Key in the database whose corresponding value is the list of diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 99374fc3ab..be96f07ff6 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -46,7 +46,7 @@ import ( "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/triedb/hashdb" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/triedb" warpcontract "github.com/ava-labs/coreth/precompile/contracts/warp" "github.com/ava-labs/coreth/rpc" @@ -59,17 +59,17 @@ import ( // We must import this package (not referenced elsewhere) so that the native "callTracer" // is added to a map of client-accessible tracers. In geth, this is done // inside of cmd/geth. - _ "github.com/ava-labs/libevm/eth/tracers/js" - _ "github.com/ava-labs/libevm/eth/tracers/native" + _ "github.com/ethereum/go-ethereum/eth/tracers/js" + _ "github.com/ethereum/go-ethereum/eth/tracers/native" "github.com/ava-labs/coreth/precompile/precompileconfig" // Force-load precompiles to trigger registration _ "github.com/ava-labs/coreth/precompile/registry" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" avalancheRPC "github.com/gorilla/rpc/v2" diff --git a/plugin/evm/vm_database.go b/plugin/evm/vm_database.go index 958f22db57..f2a5b4c344 100644 --- a/plugin/evm/vm_database.go +++ b/plugin/evm/vm_database.go @@ -11,8 +11,8 @@ import ( "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/plugin/evm/database" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) // initializeDBs initializes the databases used by the VM. diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 5f56e69c87..0990462616 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -16,9 +16,9 @@ import ( "testing" "time" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" "github.com/holiman/uint256" "github.com/ava-labs/coreth/constants" @@ -27,7 +27,7 @@ import ( "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/plugin/evm/config" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/trie" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/plugin/evm/vm_warp_test.go b/plugin/evm/vm_warp_test.go index d746931e06..d4a54a5e5b 100644 --- a/plugin/evm/vm_warp_test.go +++ b/plugin/evm/vm_warp_test.go @@ -37,8 +37,8 @@ import ( "github.com/ava-labs/coreth/predicate" "github.com/ava-labs/coreth/utils" "github.com/ava-labs/coreth/warp" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" "github.com/stretchr/testify/require" ) diff --git a/precompile/contract/contract.go b/precompile/contract/contract.go index b64c8058dc..0be76a8955 100644 --- a/precompile/contract/contract.go +++ b/precompile/contract/contract.go @@ -6,7 +6,7 @@ package contract import ( "fmt" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) const ( diff --git a/precompile/contract/interfaces.go b/precompile/contract/interfaces.go index a1ae9d5682..958283b3c2 100644 --- a/precompile/contract/interfaces.go +++ b/precompile/contract/interfaces.go @@ -9,9 +9,9 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/coreth/precompile/precompileconfig" - "github.com/ava-labs/libevm/common" - ethtypes "github.com/ava-labs/libevm/core/types" - "github.com/ava-labs/libevm/core/vm" + "github.com/ethereum/go-ethereum/common" + ethtypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/core/vm" "github.com/holiman/uint256" ) diff --git a/precompile/contract/mocks.go b/precompile/contract/mocks.go index 6da91cc237..9001ded654 100644 --- a/precompile/contract/mocks.go +++ b/precompile/contract/mocks.go @@ -15,8 +15,8 @@ import ( snow "github.com/ava-labs/avalanchego/snow" precompileconfig "github.com/ava-labs/coreth/precompile/precompileconfig" - common "github.com/ava-labs/libevm/common" - vm "github.com/ava-labs/libevm/core/vm" + common "github.com/ethereum/go-ethereum/common" + vm "github.com/ethereum/go-ethereum/core/vm" uint256 "github.com/holiman/uint256" gomock "go.uber.org/mock/gomock" ) diff --git a/precompile/contract/utils.go b/precompile/contract/utils.go index 8484415397..6b8ed7c832 100644 --- a/precompile/contract/utils.go +++ b/precompile/contract/utils.go @@ -10,7 +10,7 @@ import ( "github.com/ava-labs/coreth/accounts/abi" "github.com/ava-labs/coreth/vmerrs" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/crypto" ) // Gas costs for stateful precompiles diff --git a/precompile/contracts/warp/config.go b/precompile/contracts/warp/config.go index 52966a72b5..fae9328675 100644 --- a/precompile/contracts/warp/config.go +++ b/precompile/contracts/warp/config.go @@ -13,9 +13,9 @@ import ( "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/predicate" warpValidators "github.com/ava-labs/coreth/warp/validators" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/math" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" + "github.com/ethereum/go-ethereum/log" ) const ( diff --git a/precompile/contracts/warp/contract.go b/precompile/contracts/warp/contract.go index 295b154bc8..932c19ea31 100644 --- a/precompile/contracts/warp/contract.go +++ b/precompile/contracts/warp/contract.go @@ -15,8 +15,8 @@ import ( _ "embed" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/math" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" ) const ( diff --git a/precompile/contracts/warp/contract_test.go b/precompile/contracts/warp/contract_test.go index 9ba15a8be9..9e8973523a 100644 --- a/precompile/contracts/warp/contract_test.go +++ b/precompile/contracts/warp/contract_test.go @@ -19,7 +19,7 @@ import ( "github.com/ava-labs/coreth/predicate" "github.com/ava-labs/coreth/utils" "github.com/ava-labs/coreth/vmerrs" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" ) diff --git a/precompile/contracts/warp/contract_warp_handler.go b/precompile/contracts/warp/contract_warp_handler.go index a28afc9ef1..3dc7191ef1 100644 --- a/precompile/contracts/warp/contract_warp_handler.go +++ b/precompile/contracts/warp/contract_warp_handler.go @@ -12,8 +12,8 @@ import ( "github.com/ava-labs/coreth/precompile/contract" "github.com/ava-labs/coreth/predicate" "github.com/ava-labs/coreth/vmerrs" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/math" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" ) var ( diff --git a/precompile/contracts/warp/module.go b/precompile/contracts/warp/module.go index b333d8f7ec..336100da34 100644 --- a/precompile/contracts/warp/module.go +++ b/precompile/contracts/warp/module.go @@ -10,7 +10,7 @@ import ( "github.com/ava-labs/coreth/precompile/modules" "github.com/ava-labs/coreth/precompile/precompileconfig" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) var _ contract.Configurator = &configurator{} diff --git a/precompile/modules/module.go b/precompile/modules/module.go index a5fca0cc38..fefa9fd2da 100644 --- a/precompile/modules/module.go +++ b/precompile/modules/module.go @@ -7,7 +7,7 @@ import ( "bytes" "github.com/ava-labs/coreth/precompile/contract" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) type Module struct { diff --git a/precompile/modules/registerer.go b/precompile/modules/registerer.go index 068170bd2c..a7f3b92c60 100644 --- a/precompile/modules/registerer.go +++ b/precompile/modules/registerer.go @@ -9,7 +9,7 @@ import ( "github.com/ava-labs/coreth/constants" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) var ( diff --git a/precompile/modules/registerer_test.go b/precompile/modules/registerer_test.go index 665f1aa860..f2519046df 100644 --- a/precompile/modules/registerer_test.go +++ b/precompile/modules/registerer_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/ava-labs/coreth/constants" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" ) diff --git a/precompile/precompileconfig/config.go b/precompile/precompileconfig/config.go index 7dd027aadc..eb741cbc55 100644 --- a/precompile/precompileconfig/config.go +++ b/precompile/precompileconfig/config.go @@ -8,7 +8,7 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "github.com/ava-labs/avalanchego/vms/platformvm/warp" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // StatefulPrecompileConfig defines the interface for a stateful precompile to diff --git a/precompile/precompileconfig/mocks.go b/precompile/precompileconfig/mocks.go index 6843eaa6b4..cba1ca13a3 100644 --- a/precompile/precompileconfig/mocks.go +++ b/precompile/precompileconfig/mocks.go @@ -12,7 +12,7 @@ package precompileconfig import ( reflect "reflect" - common "github.com/ava-labs/libevm/common" + common "github.com/ethereum/go-ethereum/common" gomock "go.uber.org/mock/gomock" ) diff --git a/precompile/testutils/test_precompile.go b/precompile/testutils/test_precompile.go index 86c29c6323..a0bc279ff9 100644 --- a/precompile/testutils/test_precompile.go +++ b/precompile/testutils/test_precompile.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/coreth/precompile/modules" "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" ) diff --git a/predicate/predicate_bytes.go b/predicate/predicate_bytes.go index 1d487a99d9..5c93bb5e3b 100644 --- a/predicate/predicate_bytes.go +++ b/predicate/predicate_bytes.go @@ -6,7 +6,7 @@ package predicate import ( "fmt" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // DynamicFeeExtraDataSize is defined in the predicate package to avoid a circular dependency. diff --git a/predicate/predicate_results.go b/predicate/predicate_results.go index a79417329c..f28b790821 100644 --- a/predicate/predicate_results.go +++ b/predicate/predicate_results.go @@ -11,7 +11,7 @@ import ( "github.com/ava-labs/avalanchego/codec/linearcodec" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) const ( diff --git a/predicate/predicate_results_test.go b/predicate/predicate_results_test.go index 45b8efc0d6..e3daefa706 100644 --- a/predicate/predicate_results_test.go +++ b/predicate/predicate_results_test.go @@ -6,7 +6,7 @@ package predicate import ( "testing" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" ) diff --git a/predicate/predicate_slots.go b/predicate/predicate_slots.go index f71145fbdd..5ce3d2f1ea 100644 --- a/predicate/predicate_slots.go +++ b/predicate/predicate_slots.go @@ -6,7 +6,7 @@ package predicate import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) type predicaters interface { diff --git a/predicate/predicate_tx.go b/predicate/predicate_tx.go index f2b101bb67..76bb3ce6bd 100644 --- a/predicate/predicate_tx.go +++ b/predicate/predicate_tx.go @@ -8,7 +8,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // NewPredicateTx returns a transaction with the predicateAddress/predicateBytes tuple diff --git a/rpc/client.go b/rpc/client.go index ff351485f0..6c11365560 100644 --- a/rpc/client.go +++ b/rpc/client.go @@ -37,7 +37,7 @@ import ( "sync/atomic" "time" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) var ( diff --git a/rpc/client_test.go b/rpc/client_test.go index 826d1eed48..97bc69e61b 100644 --- a/rpc/client_test.go +++ b/rpc/client_test.go @@ -42,8 +42,8 @@ import ( "testing" "time" - "github.com/ava-labs/libevm/log" "github.com/davecgh/go-spew/spew" + "github.com/ethereum/go-ethereum/log" ) func TestClientRequest(t *testing.T) { diff --git a/rpc/handler.go b/rpc/handler.go index 427af29cd7..ef35a61ca8 100644 --- a/rpc/handler.go +++ b/rpc/handler.go @@ -39,7 +39,7 @@ import ( "time" "github.com/ava-labs/coreth/metrics" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" "golang.org/x/time/rate" ) diff --git a/rpc/server.go b/rpc/server.go index d41ce1cc32..054bd2de92 100644 --- a/rpc/server.go +++ b/rpc/server.go @@ -33,7 +33,7 @@ import ( "sync/atomic" "time" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) const MetadataApi = "rpc" diff --git a/rpc/service.go b/rpc/service.go index d8fe238844..eecd70e90e 100644 --- a/rpc/service.go +++ b/rpc/service.go @@ -35,7 +35,7 @@ import ( "sync" "unicode" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) var ( diff --git a/rpc/subscription_test.go b/rpc/subscription_test.go index 06a2bb0660..5e3143c9fe 100644 --- a/rpc/subscription_test.go +++ b/rpc/subscription_test.go @@ -39,7 +39,7 @@ import ( "time" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) func TestNewID(t *testing.T) { diff --git a/rpc/types.go b/rpc/types.go index 38123bb430..c96e7bc74f 100644 --- a/rpc/types.go +++ b/rpc/types.go @@ -34,8 +34,8 @@ import ( "math" "strings" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" ) // API describes the set of methods offered over the RPC interface diff --git a/rpc/types_test.go b/rpc/types_test.go index d37632d62e..779b23296f 100644 --- a/rpc/types_test.go +++ b/rpc/types_test.go @@ -31,8 +31,8 @@ import ( "reflect" "testing" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/math" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/math" ) func TestBlockNumberJSONUnmarshal(t *testing.T) { diff --git a/rpc/websocket.go b/rpc/websocket.go index 6f545477ad..1be8364955 100644 --- a/rpc/websocket.go +++ b/rpc/websocket.go @@ -37,8 +37,8 @@ import ( "sync" "time" - "github.com/ava-labs/libevm/log" mapset "github.com/deckarep/golang-set/v2" + "github.com/ethereum/go-ethereum/log" "github.com/gorilla/websocket" ) diff --git a/scripts/eth-allowed-packages.txt b/scripts/eth-allowed-packages.txt index 0f200f77f5..4b4dbdd6bd 100644 --- a/scripts/eth-allowed-packages.txt +++ b/scripts/eth-allowed-packages.txt @@ -1,39 +1,39 @@ -"github.com/ava-labs/libevm/accounts" -"github.com/ava-labs/libevm/accounts/external" -"github.com/ava-labs/libevm/accounts/keystore" -"github.com/ava-labs/libevm/accounts/scwallet" -"github.com/ava-labs/libevm/common" -"github.com/ava-labs/libevm/common/bitutil" -"github.com/ava-labs/libevm/common/compiler" -"github.com/ava-labs/libevm/common/hexutil" -"github.com/ava-labs/libevm/common/lru" -"github.com/ava-labs/libevm/common/math" -"github.com/ava-labs/libevm/common/prque" -"github.com/ava-labs/libevm/core/asm" -"github.com/ava-labs/libevm/core/vm" -"github.com/ava-labs/libevm/crypto" -"github.com/ava-labs/libevm/crypto/blake2b" -"github.com/ava-labs/libevm/crypto/bls12381" -"github.com/ava-labs/libevm/crypto/bn256" -"github.com/ava-labs/libevm/crypto/kzg4844" -"github.com/ava-labs/libevm/eth/tracers/js" -"github.com/ava-labs/libevm/eth/tracers/logger" -"github.com/ava-labs/libevm/eth/tracers/native" -"github.com/ava-labs/libevm/ethdb" -"github.com/ava-labs/libevm/ethdb/leveldb" -"github.com/ava-labs/libevm/ethdb/memorydb" -"github.com/ava-labs/libevm/ethdb/pebble" -"github.com/ava-labs/libevm/event" -"github.com/ava-labs/libevm/libevm" -"github.com/ava-labs/libevm/libevm/legacy" -"github.com/ava-labs/libevm/libevm/stateconf" -"github.com/ava-labs/libevm/log" -"github.com/ava-labs/libevm/params" -"github.com/ava-labs/libevm/rlp" -"github.com/ava-labs/libevm/trie" -"github.com/ava-labs/libevm/trie/testutil" -"github.com/ava-labs/libevm/trie/trienode" -"github.com/ava-labs/libevm/trie/triestate" -"github.com/ava-labs/libevm/trie/utils" -"github.com/ava-labs/libevm/triedb" -"github.com/ava-labs/libevm/triedb/database" \ No newline at end of file +"github.com/ethereum/go-ethereum/accounts" +"github.com/ethereum/go-ethereum/accounts/external" +"github.com/ethereum/go-ethereum/accounts/keystore" +"github.com/ethereum/go-ethereum/accounts/scwallet" +"github.com/ethereum/go-ethereum/common" +"github.com/ethereum/go-ethereum/common/bitutil" +"github.com/ethereum/go-ethereum/common/compiler" +"github.com/ethereum/go-ethereum/common/hexutil" +"github.com/ethereum/go-ethereum/common/lru" +"github.com/ethereum/go-ethereum/common/math" +"github.com/ethereum/go-ethereum/common/prque" +"github.com/ethereum/go-ethereum/core/asm" +"github.com/ethereum/go-ethereum/core/vm" +"github.com/ethereum/go-ethereum/crypto" +"github.com/ethereum/go-ethereum/crypto/blake2b" +"github.com/ethereum/go-ethereum/crypto/bls12381" +"github.com/ethereum/go-ethereum/crypto/bn256" +"github.com/ethereum/go-ethereum/crypto/kzg4844" +"github.com/ethereum/go-ethereum/eth/tracers/js" +"github.com/ethereum/go-ethereum/eth/tracers/logger" +"github.com/ethereum/go-ethereum/eth/tracers/native" +"github.com/ethereum/go-ethereum/ethdb" +"github.com/ethereum/go-ethereum/ethdb/leveldb" +"github.com/ethereum/go-ethereum/ethdb/memorydb" +"github.com/ethereum/go-ethereum/ethdb/pebble" +"github.com/ethereum/go-ethereum/event" +"github.com/ethereum/go-ethereum/libevm" +"github.com/ethereum/go-ethereum/libevm/legacy" +"github.com/ethereum/go-ethereum/libevm/stateconf" +"github.com/ethereum/go-ethereum/log" +"github.com/ethereum/go-ethereum/params" +"github.com/ethereum/go-ethereum/rlp" +"github.com/ethereum/go-ethereum/trie" +"github.com/ethereum/go-ethereum/trie/testutil" +"github.com/ethereum/go-ethereum/trie/trienode" +"github.com/ethereum/go-ethereum/trie/triestate" +"github.com/ethereum/go-ethereum/trie/utils" +"github.com/ethereum/go-ethereum/triedb" +"github.com/ethereum/go-ethereum/triedb/database" \ No newline at end of file diff --git a/scripts/lint_allowed_eth_imports.sh b/scripts/lint_allowed_eth_imports.sh index fcbfe7c6f4..4580505b46 100755 --- a/scripts/lint_allowed_eth_imports.sh +++ b/scripts/lint_allowed_eth_imports.sh @@ -9,7 +9,7 @@ set -o pipefail # 2. Ignore lines that import libevm with a named import starting with "eth" # 3. Sort the unique results # 4. Print out the difference between the search results and the list of specified allowed package imports from libevm. -libevm_regexp='"github.com/ava-labs/libevm/.*"' +libevm_regexp='"github.com/ethereum/go-ethereum/.*"' allow_named_imports='eth\w\+ "' extra_imports=$(grep -r --include='*.go' --exclude=mocks.go "${libevm_regexp}" -h | grep -v "${allow_named_imports}" | grep -o "${libevm_regexp}" | sort -u | comm -23 - ./scripts/eth-allowed-packages.txt) if [ -n "${extra_imports}" ]; then diff --git a/signer/core/apitypes/types.go b/signer/core/apitypes/types.go index 8ea190cbb5..9f85e9ce7e 100644 --- a/signer/core/apitypes/types.go +++ b/signer/core/apitypes/types.go @@ -33,8 +33,8 @@ import ( "strings" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" ) type ValidationInfo struct { diff --git a/sync/client/client.go b/sync/client/client.go index 6a1348679e..1d8b95d64a 100644 --- a/sync/client/client.go +++ b/sync/client/client.go @@ -19,16 +19,16 @@ import ( "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/version" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/log" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/peer" "github.com/ava-labs/coreth/plugin/evm/message" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/trie" ) const ( diff --git a/sync/client/client_test.go b/sync/client/client_test.go index 70c7f6f118..efe92d454e 100644 --- a/sync/client/client_test.go +++ b/sync/client/client_test.go @@ -25,9 +25,9 @@ import ( "github.com/ava-labs/coreth/sync/handlers" handlerstats "github.com/ava-labs/coreth/sync/handlers/stats" "github.com/ava-labs/coreth/sync/syncutils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/triedb" ) func TestGetCode(t *testing.T) { diff --git a/sync/client/leaf_syncer.go b/sync/client/leaf_syncer.go index db59bb305e..2ca82b7560 100644 --- a/sync/client/leaf_syncer.go +++ b/sync/client/leaf_syncer.go @@ -11,8 +11,8 @@ import ( "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" "golang.org/x/sync/errgroup" ) diff --git a/sync/client/mock_client.go b/sync/client/mock_client.go index 2d2b5180f7..038bdf73bf 100644 --- a/sync/client/mock_client.go +++ b/sync/client/mock_client.go @@ -13,8 +13,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/sync/handlers" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/rlp" ) var ( diff --git a/sync/handlers/block_request.go b/sync/handlers/block_request.go index 1bbad650ad..2bbb21b012 100644 --- a/sync/handlers/block_request.go +++ b/sync/handlers/block_request.go @@ -14,8 +14,8 @@ import ( "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/sync/handlers/stats" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) const ( diff --git a/sync/handlers/block_request_test.go b/sync/handlers/block_request_test.go index bd9bf8ce4f..ed1f6c5dc0 100644 --- a/sync/handlers/block_request_test.go +++ b/sync/handlers/block_request_test.go @@ -17,10 +17,10 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/sync/handlers/stats" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/triedb" "github.com/stretchr/testify/assert" ) diff --git a/sync/handlers/code_request.go b/sync/handlers/code_request.go index 5f0b3ee59d..b756507f75 100644 --- a/sync/handlers/code_request.go +++ b/sync/handlers/code_request.go @@ -13,9 +13,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/sync/handlers/stats" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" ) // CodeRequestHandler is a peer.RequestHandler for message.CodeRequest diff --git a/sync/handlers/code_request_test.go b/sync/handlers/code_request_test.go index 13c9306ac9..1bf5bd5223 100644 --- a/sync/handlers/code_request_test.go +++ b/sync/handlers/code_request_test.go @@ -14,9 +14,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/sync/handlers/stats" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/ethdb/memorydb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethdb/memorydb" "github.com/stretchr/testify/assert" ) diff --git a/sync/handlers/handler.go b/sync/handlers/handler.go index eece20e4d0..71bff519de 100644 --- a/sync/handlers/handler.go +++ b/sync/handlers/handler.go @@ -6,7 +6,7 @@ package handlers import ( "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) type BlockProvider interface { diff --git a/sync/handlers/leafs_request.go b/sync/handlers/leafs_request.go index c9df10ef10..b6c1316944 100644 --- a/sync/handlers/leafs_request.go +++ b/sync/handlers/leafs_request.go @@ -19,12 +19,12 @@ import ( "github.com/ava-labs/coreth/sync/handlers/stats" "github.com/ava-labs/coreth/sync/syncutils" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/ethdb/memorydb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/ethdb/memorydb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/triedb" ) const ( diff --git a/sync/handlers/leafs_request_test.go b/sync/handlers/leafs_request_test.go index a98f398cb4..bc7e19b324 100644 --- a/sync/handlers/leafs_request_test.go +++ b/sync/handlers/leafs_request_test.go @@ -16,11 +16,11 @@ import ( "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/sync/handlers/stats" "github.com/ava-labs/coreth/sync/syncutils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/triedb" "github.com/stretchr/testify/assert" ) diff --git a/sync/handlers/test_providers.go b/sync/handlers/test_providers.go index a16410d71a..81dafbfd00 100644 --- a/sync/handlers/test_providers.go +++ b/sync/handlers/test_providers.go @@ -6,7 +6,7 @@ package handlers import ( "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) var ( diff --git a/sync/statesync/code_syncer.go b/sync/statesync/code_syncer.go index 196fefea58..97164b2658 100644 --- a/sync/statesync/code_syncer.go +++ b/sync/statesync/code_syncer.go @@ -14,8 +14,8 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/plugin/evm/message" statesyncclient "github.com/ava-labs/coreth/sync/client" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" ) const ( diff --git a/sync/statesync/code_syncer_test.go b/sync/statesync/code_syncer_test.go index c1741760d4..574290e286 100644 --- a/sync/statesync/code_syncer_test.go +++ b/sync/statesync/code_syncer_test.go @@ -14,9 +14,9 @@ import ( statesyncclient "github.com/ava-labs/coreth/sync/client" "github.com/ava-labs/coreth/sync/handlers" handlerstats "github.com/ava-labs/coreth/sync/handlers/stats" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/ethdb/memorydb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethdb/memorydb" "github.com/stretchr/testify/assert" ) diff --git a/sync/statesync/state_syncer.go b/sync/statesync/state_syncer.go index d2f3159e27..7f3e70c7a6 100644 --- a/sync/statesync/state_syncer.go +++ b/sync/statesync/state_syncer.go @@ -10,9 +10,9 @@ import ( "github.com/ava-labs/coreth/core/state/snapshot" syncclient "github.com/ava-labs/coreth/sync/client" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/triedb" "golang.org/x/sync/errgroup" ) diff --git a/sync/statesync/sync_helpers.go b/sync/statesync/sync_helpers.go index 22874b0017..f4590024f6 100644 --- a/sync/statesync/sync_helpers.go +++ b/sync/statesync/sync_helpers.go @@ -6,9 +6,9 @@ package statesync import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/trie" ) // writeAccountSnapshot stores the account represented by [acc] to the snapshot at [accHash], using diff --git a/sync/statesync/sync_test.go b/sync/statesync/sync_test.go index 14a096a7fd..8a099bc0db 100644 --- a/sync/statesync/sync_test.go +++ b/sync/statesync/sync_test.go @@ -21,12 +21,12 @@ import ( "github.com/ava-labs/coreth/sync/handlers" handlerstats "github.com/ava-labs/coreth/sync/handlers/stats" "github.com/ava-labs/coreth/sync/syncutils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/triedb" "github.com/stretchr/testify/assert" ) diff --git a/sync/statesync/test_sync.go b/sync/statesync/test_sync.go index e3083e3484..1495813d2c 100644 --- a/sync/statesync/test_sync.go +++ b/sync/statesync/test_sync.go @@ -12,11 +12,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/sync/syncutils" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/triedb" "github.com/stretchr/testify/assert" ) diff --git a/sync/statesync/trie_queue.go b/sync/statesync/trie_queue.go index 3c8f3abf23..3ec7c87a49 100644 --- a/sync/statesync/trie_queue.go +++ b/sync/statesync/trie_queue.go @@ -5,8 +5,8 @@ package statesync import ( "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" ) // trieQueue persists storage trie roots with their associated diff --git a/sync/statesync/trie_segments.go b/sync/statesync/trie_segments.go index d0665ace9e..637d8e66a8 100644 --- a/sync/statesync/trie_segments.go +++ b/sync/statesync/trie_segments.go @@ -15,10 +15,10 @@ import ( "github.com/ava-labs/coreth/plugin/evm/message" syncclient "github.com/ava-labs/coreth/sync/client" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/trie" ) var ( diff --git a/sync/statesync/trie_sync_stats.go b/sync/statesync/trie_sync_stats.go index 3bf124d55d..c55fc8da35 100644 --- a/sync/statesync/trie_sync_stats.go +++ b/sync/statesync/trie_sync_stats.go @@ -11,8 +11,8 @@ import ( utils_math "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/timer" "github.com/ava-labs/coreth/metrics" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" ) const ( diff --git a/sync/statesync/trie_sync_tasks.go b/sync/statesync/trie_sync_tasks.go index a0c4d4845f..c691d82595 100644 --- a/sync/statesync/trie_sync_tasks.go +++ b/sync/statesync/trie_sync_tasks.go @@ -9,11 +9,11 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/sync/syncutils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie" ) var ( diff --git a/sync/syncutils/iterators.go b/sync/syncutils/iterators.go index c15409d96e..2ae6bfcc80 100644 --- a/sync/syncutils/iterators.go +++ b/sync/syncutils/iterators.go @@ -6,7 +6,7 @@ package syncutils import ( "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/ethdb" + "github.com/ethereum/go-ethereum/ethdb" ) var ( diff --git a/sync/syncutils/test_trie.go b/sync/syncutils/test_trie.go index c244d7bb1c..eb4e2c6a11 100644 --- a/sync/syncutils/test_trie.go +++ b/sync/syncutils/test_trie.go @@ -12,14 +12,14 @@ import ( "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/trie/trienode" - "github.com/ava-labs/libevm/triedb" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ethereum/go-ethereum/triedb" "github.com/holiman/uint256" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/rlp" "github.com/stretchr/testify/assert" ) diff --git a/tests/rlp_test_util.go b/tests/rlp_test_util.go index b5df73438e..5af235bc5a 100644 --- a/tests/rlp_test_util.go +++ b/tests/rlp_test_util.go @@ -34,7 +34,7 @@ import ( "math/big" "strings" - "github.com/ava-labs/libevm/rlp" + "github.com/ethereum/go-ethereum/rlp" ) // RLPTest is the JSON structure of a single RLP test. diff --git a/triedb/hashdb/database.go b/triedb/hashdb/database.go index 56beaa53ac..18121745f4 100644 --- a/triedb/hashdb/database.go +++ b/triedb/hashdb/database.go @@ -37,15 +37,15 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/metrics" "github.com/ava-labs/coreth/utils" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie" - "github.com/ava-labs/libevm/trie/trienode" - "github.com/ava-labs/libevm/trie/triestate" - "github.com/ava-labs/libevm/triedb" - "github.com/ava-labs/libevm/triedb/database" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie" + "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ethereum/go-ethereum/trie/triestate" + "github.com/ethereum/go-ethereum/triedb" + "github.com/ethereum/go-ethereum/triedb/database" ) const ( diff --git a/triedb/pathdb/database.go b/triedb/pathdb/database.go index c38c54fca8..6743ad1092 100644 --- a/triedb/pathdb/database.go +++ b/triedb/pathdb/database.go @@ -35,13 +35,13 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/trie/trienode" - "github.com/ava-labs/libevm/trie/triestate" - "github.com/ava-labs/libevm/triedb" - "github.com/ava-labs/libevm/triedb/database" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ethereum/go-ethereum/trie/triestate" + "github.com/ethereum/go-ethereum/triedb" + "github.com/ethereum/go-ethereum/triedb/database" ) const ( diff --git a/triedb/pathdb/database_test.go b/triedb/pathdb/database_test.go index bf1934c97b..750d56ab1a 100644 --- a/triedb/pathdb/database_test.go +++ b/triedb/pathdb/database_test.go @@ -35,12 +35,12 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie/testutil" - "github.com/ava-labs/libevm/trie/trienode" - "github.com/ava-labs/libevm/trie/triestate" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie/testutil" + "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ethereum/go-ethereum/trie/triestate" "github.com/holiman/uint256" "github.com/stretchr/testify/require" ) diff --git a/triedb/pathdb/difflayer.go b/triedb/pathdb/difflayer.go index eea8dc4126..47081a29a6 100644 --- a/triedb/pathdb/difflayer.go +++ b/triedb/pathdb/difflayer.go @@ -30,10 +30,10 @@ import ( "fmt" "sync" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/trie/trienode" - "github.com/ava-labs/libevm/trie/triestate" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ethereum/go-ethereum/trie/triestate" ) // diffLayer represents a collection of modifications made to the in-memory tries diff --git a/triedb/pathdb/difflayer_test.go b/triedb/pathdb/difflayer_test.go index d7f975ffad..6f1a648392 100644 --- a/triedb/pathdb/difflayer_test.go +++ b/triedb/pathdb/difflayer_test.go @@ -31,9 +31,9 @@ import ( "testing" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/trie/testutil" - "github.com/ava-labs/libevm/trie/trienode" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/trie/testutil" + "github.com/ethereum/go-ethereum/trie/trienode" ) func emptyLayer() *diskLayer { diff --git a/triedb/pathdb/disklayer.go b/triedb/pathdb/disklayer.go index c13b46e710..53bda1a01f 100644 --- a/triedb/pathdb/disklayer.go +++ b/triedb/pathdb/disklayer.go @@ -33,11 +33,11 @@ import ( "github.com/VictoriaMetrics/fastcache" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/trie/trienode" - "github.com/ava-labs/libevm/trie/triestate" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ethereum/go-ethereum/trie/triestate" "golang.org/x/crypto/sha3" ) diff --git a/triedb/pathdb/errors.go b/triedb/pathdb/errors.go index 6186091e30..af6e3464d2 100644 --- a/triedb/pathdb/errors.go +++ b/triedb/pathdb/errors.go @@ -30,8 +30,8 @@ import ( "errors" "fmt" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/common/hexutil" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" ) var ( diff --git a/triedb/pathdb/history.go b/triedb/pathdb/history.go index 14e53383a3..6f937dfb90 100644 --- a/triedb/pathdb/history.go +++ b/triedb/pathdb/history.go @@ -32,8 +32,8 @@ import ( "errors" "fmt" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/trie/triestate" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/trie/triestate" "golang.org/x/exp/slices" ) diff --git a/triedb/pathdb/history_test.go b/triedb/pathdb/history_test.go index 4d30831c81..fdeaccd2af 100644 --- a/triedb/pathdb/history_test.go +++ b/triedb/pathdb/history_test.go @@ -32,10 +32,10 @@ import ( "testing" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie/testutil" - "github.com/ava-labs/libevm/trie/triestate" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie/testutil" + "github.com/ethereum/go-ethereum/trie/triestate" ) // randomStateSet generates a random state change set. diff --git a/triedb/pathdb/journal.go b/triedb/pathdb/journal.go index a245e7f8c3..9d63de40ab 100644 --- a/triedb/pathdb/journal.go +++ b/triedb/pathdb/journal.go @@ -35,12 +35,12 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/rlp" - "github.com/ava-labs/libevm/trie/trienode" - "github.com/ava-labs/libevm/trie/triestate" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/rlp" + "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ethereum/go-ethereum/trie/triestate" ) var ( diff --git a/triedb/pathdb/layertree.go b/triedb/pathdb/layertree.go index a52eded0f6..f52d879390 100644 --- a/triedb/pathdb/layertree.go +++ b/triedb/pathdb/layertree.go @@ -32,9 +32,9 @@ import ( "sync" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/trie/trienode" - "github.com/ava-labs/libevm/trie/triestate" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ethereum/go-ethereum/trie/triestate" ) // layerTree is a group of state layers identified by the state root. diff --git a/triedb/pathdb/nodebuffer.go b/triedb/pathdb/nodebuffer.go index 7a461b60ad..cf493ca69c 100644 --- a/triedb/pathdb/nodebuffer.go +++ b/triedb/pathdb/nodebuffer.go @@ -32,11 +32,11 @@ import ( "github.com/VictoriaMetrics/fastcache" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/ethdb" - "github.com/ava-labs/libevm/log" - "github.com/ava-labs/libevm/trie/trienode" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/trie/trienode" ) // nodebuffer is a collection of modified trie nodes to aggregate the disk diff --git a/triedb/pathdb/testutils.go b/triedb/pathdb/testutils.go index a7ada9947e..a3023e607c 100644 --- a/triedb/pathdb/testutils.go +++ b/triedb/pathdb/testutils.go @@ -31,10 +31,10 @@ import ( "fmt" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" - "github.com/ava-labs/libevm/trie/trienode" - "github.com/ava-labs/libevm/trie/triestate" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ethereum/go-ethereum/trie/triestate" "golang.org/x/exp/slices" ) diff --git a/utils/address_range.go b/utils/address_range.go index a10794f03d..940c39e8a1 100644 --- a/utils/address_range.go +++ b/utils/address_range.go @@ -6,7 +6,7 @@ package utils import ( "bytes" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" ) // AddressRange represents a continuous range of addresses diff --git a/utils/bytes.go b/utils/bytes.go index 86382cf156..54258b20f4 100644 --- a/utils/bytes.go +++ b/utils/bytes.go @@ -3,7 +3,7 @@ package utils -import "github.com/ava-labs/libevm/common" +import "github.com/ethereum/go-ethereum/common" // IncrOne increments bytes value by one func IncrOne(bytes []byte) { diff --git a/utils/bytes_test.go b/utils/bytes_test.go index 7b4fc9d05c..b1bbc8fa6b 100644 --- a/utils/bytes_test.go +++ b/utils/bytes_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/ava-labs/avalanchego/utils" - "github.com/ava-labs/libevm/common" + "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/utils/key.go b/utils/key.go index ab4db85b94..a6515af062 100644 --- a/utils/key.go +++ b/utils/key.go @@ -7,8 +7,8 @@ import ( "crypto/ecdsa" "io" - "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" ) type Key struct { diff --git a/vmerrs/vmerrs.go b/vmerrs/vmerrs.go index 26a3dbd967..9f64349f2f 100644 --- a/vmerrs/vmerrs.go +++ b/vmerrs/vmerrs.go @@ -29,7 +29,7 @@ package vmerrs import ( "errors" - "github.com/ava-labs/libevm/core/vm" + "github.com/ethereum/go-ethereum/core/vm" ) // List evm execution errors diff --git a/warp/aggregator/aggregator.go b/warp/aggregator/aggregator.go index 9cc66fae38..9c6c3aa322 100644 --- a/warp/aggregator/aggregator.go +++ b/warp/aggregator/aggregator.go @@ -7,7 +7,7 @@ import ( "context" "fmt" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/set" diff --git a/warp/backend.go b/warp/backend.go index 77167f3fd8..d35c96b8fb 100644 --- a/warp/backend.go +++ b/warp/backend.go @@ -15,7 +15,7 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowman" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) var ( diff --git a/warp/client.go b/warp/client.go index 55d99621a4..90633d6b47 100644 --- a/warp/client.go +++ b/warp/client.go @@ -9,7 +9,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/coreth/rpc" - "github.com/ava-labs/libevm/common/hexutil" + "github.com/ethereum/go-ethereum/common/hexutil" ) var _ Client = (*client)(nil) diff --git a/warp/handlers/signature_request.go b/warp/handlers/signature_request.go index 9a5dbfd77f..bb9c2c7855 100644 --- a/warp/handlers/signature_request.go +++ b/warp/handlers/signature_request.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/warp" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/log" ) // SignatureRequestHandler serves warp signature requests. It is a peer.RequestHandler for message.MessageSignatureRequest. diff --git a/warp/service.go b/warp/service.go index 7e4f11c98f..610fc85a91 100644 --- a/warp/service.go +++ b/warp/service.go @@ -15,8 +15,8 @@ import ( "github.com/ava-labs/coreth/peer" "github.com/ava-labs/coreth/warp/aggregator" warpValidators "github.com/ava-labs/coreth/warp/validators" - "github.com/ava-labs/libevm/common/hexutil" - "github.com/ava-labs/libevm/log" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/log" ) var errNoValidators = errors.New("cannot aggregate signatures from subnet with no validators") From 41ecca22170ba2e43f219856ff13acdcf8bf526f Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 18 Feb 2025 17:54:24 -0800 Subject: [PATCH 61/69] changes --- accounts/abi/abi.go | 4 +- accounts/abi/abi_extra_test.go | 2 +- accounts/abi/abi_test.go | 6 +- accounts/abi/bind/auth.go | 12 +-- accounts/abi/bind/backend.go | 2 +- accounts/abi/bind/backends/simulated.go | 2 +- accounts/abi/bind/base.go | 6 +- accounts/abi/bind/base_test.go | 8 +- accounts/abi/bind/bind.go | 2 +- accounts/abi/bind/bind_extra_test.go | 4 +- accounts/abi/bind/bind_test.go | 74 ++++++------- accounts/abi/bind/template.go | 4 +- accounts/abi/bind/util.go | 4 +- accounts/abi/bind/util_test.go | 4 +- accounts/abi/error.go | 4 +- accounts/abi/event.go | 4 +- accounts/abi/event_test.go | 4 +- accounts/abi/method.go | 2 +- accounts/abi/pack.go | 4 +- accounts/abi/pack_test.go | 2 +- accounts/abi/packing_test.go | 2 +- accounts/abi/topics.go | 6 +- accounts/abi/topics_test.go | 4 +- accounts/abi/type.go | 2 +- accounts/abi/type_test.go | 2 +- accounts/abi/unpack.go | 2 +- accounts/abi/unpack_test.go | 2 +- cmd/abigen/main.go | 6 +- consensus/consensus.go | 2 +- consensus/dummy/consensus.go | 23 ++-- consensus/dummy/consensus_test.go | 2 +- consensus/dummy/dynamic_fee_window.go | 2 +- consensus/dummy/dynamic_fee_window_test.go | 2 +- consensus/dummy/dynamic_fees.go | 24 +++-- consensus/dummy/dynamic_fees_test.go | 21 ++-- constants/constants.go | 2 +- core/bench_test.go | 10 +- core/block_validator.go | 2 +- core/blockchain.go | 18 ++-- core/blockchain_log_test.go | 6 +- core/blockchain_reader.go | 8 +- core/blockchain_repair_test.go | 8 +- core/blockchain_snapshot_test.go | 6 +- core/blockchain_test.go | 10 +- core/bloom_indexer.go | 6 +- core/bloombits/matcher.go | 4 +- core/bloombits/matcher_test.go | 2 +- core/chain_indexer.go | 8 +- core/chain_indexer_test.go | 2 +- core/chain_makers.go | 8 +- core/chain_makers_test.go | 8 +- core/events.go | 2 +- core/evm.go | 8 +- core/extstate/statedb.go | 4 +- core/extstate/test_statedb.go | 2 +- core/gen_genesis.go | 8 +- core/genesis.go | 14 +-- core/genesis_extra_test.go | 4 +- core/genesis_test.go | 10 +- core/headerchain.go | 6 +- core/headerchain_test.go | 4 +- core/main_test.go | 2 +- core/mkalloc.go | 4 +- core/predicate_check.go | 4 +- core/predicate_check_test.go | 2 +- core/rawdb/accessors_chain.go | 8 +- core/rawdb/accessors_chain_test.go | 4 +- core/rawdb/accessors_indexes.go | 8 +- core/rawdb/accessors_indexes_test.go | 6 +- core/rawdb/accessors_metadata.go | 8 +- core/rawdb/accessors_snapshot.go | 6 +- core/rawdb/accessors_state.go | 6 +- core/rawdb/accessors_state_sync.go | 6 +- core/rawdb/accessors_state_sync_test.go | 2 +- core/rawdb/accessors_trie.go | 8 +- core/rawdb/chain_iterator.go | 10 +- core/rawdb/chain_iterator_test.go | 2 +- core/rawdb/database.go | 12 +-- core/rawdb/key_length_iterator.go | 2 +- core/rawdb/schema.go | 6 +- core/rawdb/table.go | 2 +- core/rawdb/table_test.go | 2 +- core/rlp_test.go | 6 +- core/state/database.go | 16 +-- core/state/dump.go | 2 +- core/state/pruner/bloom.go | 4 +- core/state/pruner/pruner.go | 12 +-- core/state/snapshot/context.go | 4 +- core/state/snapshot/conversion.go | 10 +- core/state/snapshot/difflayer.go | 4 +- core/state/snapshot/difflayer_test.go | 6 +- core/state/snapshot/disklayer.go | 8 +- core/state/snapshot/disklayer_test.go | 6 +- core/state/snapshot/generate.go | 12 +-- core/state/snapshot/generate_test.go | 14 +-- core/state/snapshot/iterator.go | 6 +- core/state/snapshot/iterator_binary.go | 2 +- core/state/snapshot/iterator_fast.go | 2 +- core/state/snapshot/iterator_test.go | 2 +- core/state/snapshot/journal.go | 10 +- core/state/snapshot/snapshot.go | 14 +-- core/state/snapshot/snapshot_ext.go | 4 +- core/state/snapshot/snapshot_test.go | 4 +- core/state/snapshot/utils.go | 6 +- core/state/snapshot/wipe.go | 6 +- core/state/snapshot/wipe_test.go | 4 +- core/state/state_object_test.go | 2 +- core/state/state_test.go | 102 ------------------ core/state/statedb_multicoin_test.go | 4 +- core/state_manager.go | 4 +- core/state_manager_test.go | 2 +- core/state_processor.go | 8 +- core/state_processor_ext.go | 2 +- core/state_processor_test.go | 10 +- core/state_transition.go | 8 +- core/state_transition_test.go | 8 +- core/test_blockchain.go | 6 +- core/txindexer.go | 4 +- core/txindexer_test.go | 6 +- core/txpool/blobpool/blobpool.go | 10 +- core/txpool/blobpool/blobpool_test.go | 12 +-- core/txpool/blobpool/config.go | 2 +- core/txpool/blobpool/evictheap.go | 2 +- core/txpool/blobpool/evictheap_test.go | 2 +- core/txpool/blobpool/interface.go | 2 +- core/txpool/blobpool/limbo.go | 6 +- core/txpool/blobpool/metrics.go | 2 +- core/txpool/legacypool/journal.go | 6 +- core/txpool/legacypool/legacypool.go | 10 +- core/txpool/legacypool/legacypool2_test.go | 6 +- core/txpool/legacypool/legacypool_test.go | 8 +- core/txpool/legacypool/list.go | 2 +- core/txpool/legacypool/list_test.go | 4 +- core/txpool/legacypool/noncer.go | 2 +- core/txpool/subpool.go | 4 +- core/txpool/txpool.go | 8 +- core/txpool/validation.go | 6 +- core/types.go | 2 +- core/types/account.go | 6 +- core/types/block.go | 6 +- core/types/block_ext.go | 2 +- core/types/block_test.go | 10 +- core/types/gen_account.go | 6 +- core/types/gen_header_json.go | 4 +- core/types/gen_header_rlp.go | 2 +- core/types/hashes.go | 6 +- core/types/hashing.go | 6 +- core/types/hashing_test.go | 12 +-- core/types/header_ext.go | 4 +- core/types/imports.go | 2 +- core/types/log.go | 2 +- core/types/rlp_fuzzer_test.go | 2 +- core/types/state_account.go | 2 +- core/types/types_test.go | 6 +- core/vm/runtime/env.go | 2 +- core/vm/runtime/runtime.go | 6 +- core/vm/runtime/runtime_example_test.go | 2 +- core/vm/runtime/runtime_test.go | 10 +- eth/api.go | 2 +- eth/api_admin.go | 2 +- eth/api_backend.go | 10 +- eth/api_backend_test.go | 4 +- eth/api_debug.go | 12 +-- eth/api_debug_test.go | 6 +- eth/backend.go | 12 +-- eth/bloombits.go | 2 +- eth/ethconfig/config.go | 2 +- eth/filters/api.go | 6 +- eth/filters/api_test.go | 2 +- eth/filters/bench_test.go | 6 +- eth/filters/filter.go | 2 +- eth/filters/filter_system.go | 8 +- eth/filters/filter_system_test.go | 6 +- eth/filters/filter_test.go | 8 +- eth/gasestimator/gasestimator.go | 6 +- eth/gasprice/fee_info_provider_test.go | 2 +- eth/gasprice/feehistory.go | 4 +- eth/gasprice/feehistory_test.go | 2 +- eth/gasprice/gasprice.go | 10 +- eth/gasprice/gasprice_test.go | 8 +- eth/state_accessor.go | 10 +- eth/tracers/api.go | 18 ++-- eth/tracers/api_test.go | 12 +-- eth/tracers/tracers.go | 4 +- eth/tracers/tracers_test.go | 8 +- ethclient/corethclient/corethclient.go | 4 +- ethclient/ethclient.go | 4 +- ethclient/signer.go | 2 +- ethclient/simulated/backend.go | 2 +- ethclient/simulated/backend_test.go | 4 +- interfaces/interfaces.go | 4 +- internal/blocktest/test_hash.go | 2 +- internal/debug/api.go | 2 +- internal/debug/flags.go | 2 +- internal/debug/trace.go | 2 +- internal/ethapi/addrlock.go | 2 +- internal/ethapi/api.coreth.go | 4 +- internal/ethapi/api.coreth_test.go | 4 +- internal/ethapi/api.go | 24 ++--- internal/ethapi/api_extra.go | 6 +- internal/ethapi/api_extra_test.go | 2 +- internal/ethapi/api_test.go | 18 ++-- internal/ethapi/backend.go | 10 +- internal/ethapi/errors.go | 2 +- internal/ethapi/mocks_test.go | 10 +- internal/ethapi/transaction_args.go | 10 +- internal/ethapi/transaction_args_test.go | 4 +- internal/shutdowncheck/shutdown_tracker.go | 6 +- metrics/prometheus/prometheus.go | 2 +- metrics/prometheus/prometheus_test.go | 2 +- miner/miner.go | 4 +- miner/ordering.go | 2 +- miner/ordering_test.go | 4 +- miner/worker.go | 8 +- nativeasset/contract.go | 6 +- nativeasset/contract_test.go | 6 +- node/api.go | 4 +- node/config.go | 8 +- node/node.go | 2 +- params/config.go | 40 ++++++- params/config_libevm.go | 4 +- params/extras/config.go | 4 +- params/extras/precompile_upgrade.go | 2 +- params/extras/rules.go | 2 +- params/hooks_libevm.go | 8 +- params/protocol_params.go | 2 +- peer/network.go | 2 +- peer/peer_tracker.go | 4 +- peer/stats/stats.go | 2 +- plugin/evm/acp176/acp176_test.go | 2 +- plugin/evm/admin.go | 2 +- plugin/evm/api.go | 4 +- plugin/evm/atomic/export_tx.go | 4 +- plugin/evm/atomic/import_tx.go | 4 +- plugin/evm/atomic/mempool.go | 4 +- plugin/evm/atomic/tx.go | 2 +- plugin/evm/atomic_backend.go | 4 +- plugin/evm/atomic_state.go | 4 +- plugin/evm/atomic_syncer.go | 4 +- plugin/evm/atomic_syncer_test.go | 6 +- plugin/evm/atomic_trie.go | 12 +-- plugin/evm/atomic_trie_iterator.go | 4 +- plugin/evm/atomic_trie_iterator_test.go | 2 +- plugin/evm/atomic_trie_test.go | 6 +- plugin/evm/atomic_tx_repository.go | 4 +- plugin/evm/atomic_tx_repository_test.go | 2 +- plugin/evm/block.go | 8 +- plugin/evm/block_builder.go | 2 +- plugin/evm/block_verification.go | 7 +- plugin/evm/client/utils.go | 2 +- plugin/evm/config/config.go | 4 +- plugin/evm/config/config_test.go | 2 +- plugin/evm/database/wrapped_database.go | 2 +- plugin/evm/export_tx_test.go | 2 +- plugin/evm/ext_data_hashes.go | 2 +- plugin/evm/gossip.go | 4 +- plugin/evm/gossip_test.go | 6 +- plugin/evm/gossiper_eth_gossiping_test.go | 4 +- plugin/evm/header/block_gas_cost.go | 4 +- plugin/evm/header/block_gas_cost_test.go | 6 +- plugin/evm/header/extra.go | 3 +- plugin/evm/header/extra_test.go | 23 ++-- plugin/evm/import_tx_test.go | 2 +- plugin/evm/log.go | 2 +- plugin/evm/log_test.go | 2 +- plugin/evm/message/block_request.go | 2 +- plugin/evm/message/block_request_test.go | 2 +- plugin/evm/message/code_request.go | 2 +- plugin/evm/message/code_request_test.go | 2 +- plugin/evm/message/leafs_request.go | 4 +- plugin/evm/message/leafs_request_test.go | 2 +- plugin/evm/message/syncable.go | 4 +- plugin/evm/network_handler.go | 6 +- plugin/evm/prestate_tracer_test.go | 8 +- plugin/evm/syncervm_client.go | 6 +- plugin/evm/syncervm_server.go | 4 +- plugin/evm/syncervm_test.go | 12 +-- plugin/evm/testutils/metrics.go | 2 +- plugin/evm/tx_test.go | 2 +- plugin/evm/vm.go | 20 ++-- plugin/evm/vm_database.go | 4 +- plugin/evm/vm_test.go | 14 ++- plugin/evm/vm_warp_test.go | 4 +- precompile/contract/contract.go | 2 +- precompile/contract/interfaces.go | 6 +- precompile/contract/mocks.go | 4 +- precompile/contract/utils.go | 2 +- precompile/contracts/warp/config.go | 6 +- precompile/contracts/warp/contract.go | 4 +- precompile/contracts/warp/contract_test.go | 2 +- .../contracts/warp/contract_warp_handler.go | 4 +- precompile/contracts/warp/module.go | 2 +- precompile/modules/module.go | 2 +- precompile/modules/registerer.go | 2 +- precompile/modules/registerer_test.go | 2 +- precompile/precompileconfig/config.go | 2 +- precompile/precompileconfig/mocks.go | 2 +- precompile/testutils/test_precompile.go | 2 +- predicate/predicate_bytes.go | 2 +- predicate/predicate_results.go | 2 +- predicate/predicate_results_test.go | 2 +- predicate/predicate_slots.go | 2 +- predicate/predicate_tx.go | 2 +- rpc/client.go | 2 +- rpc/client_test.go | 2 +- rpc/handler.go | 4 +- rpc/metrics.go | 2 +- rpc/server.go | 2 +- rpc/service.go | 2 +- rpc/subscription_test.go | 2 +- rpc/types.go | 4 +- rpc/types_test.go | 4 +- rpc/websocket.go | 2 +- scripts/eth-allowed-packages.txt | 80 +++++++------- scripts/lint_allowed_eth_imports.sh | 4 +- signer/core/apitypes/types.go | 4 +- sync/client/client.go | 10 +- sync/client/client_test.go | 6 +- sync/client/leaf_syncer.go | 4 +- sync/client/mock_client.go | 4 +- sync/client/stats/stats.go | 2 +- sync/handlers/block_request.go | 4 +- sync/handlers/block_request_test.go | 8 +- sync/handlers/code_request.go | 6 +- sync/handlers/code_request_test.go | 6 +- sync/handlers/handler.go | 2 +- sync/handlers/leafs_request.go | 12 +-- sync/handlers/leafs_request_test.go | 10 +- sync/handlers/stats/stats.go | 2 +- sync/handlers/test_providers.go | 2 +- sync/statesync/code_syncer.go | 4 +- sync/statesync/code_syncer_test.go | 6 +- sync/statesync/state_syncer.go | 6 +- sync/statesync/sync_helpers.go | 6 +- sync/statesync/sync_test.go | 12 +-- sync/statesync/test_sync.go | 10 +- sync/statesync/trie_queue.go | 4 +- sync/statesync/trie_segments.go | 8 +- sync/statesync/trie_sync_stats.go | 6 +- sync/statesync/trie_sync_stats_test.go | 2 +- sync/statesync/trie_sync_tasks.go | 10 +- sync/syncutils/iterators.go | 2 +- sync/syncutils/test_trie.go | 12 +-- tests/rlp_test_util.go | 2 +- triedb/hashdb/database.go | 22 ++-- triedb/pathdb/database.go | 14 +-- triedb/pathdb/database_test.go | 12 +-- triedb/pathdb/difflayer.go | 8 +- triedb/pathdb/difflayer_test.go | 6 +- triedb/pathdb/disklayer.go | 10 +- triedb/pathdb/errors.go | 4 +- triedb/pathdb/history.go | 4 +- triedb/pathdb/history_test.go | 8 +- triedb/pathdb/journal.go | 12 +-- triedb/pathdb/layertree.go | 6 +- triedb/pathdb/metrics.go | 2 +- triedb/pathdb/nodebuffer.go | 10 +- triedb/pathdb/testutils.go | 8 +- utils/address_range.go | 2 +- utils/bytes.go | 2 +- utils/bytes_test.go | 2 +- utils/key.go | 4 +- utils/metered_cache.go | 2 +- vmerrs/vmerrs.go | 2 +- warp/aggregator/aggregator.go | 2 +- warp/backend.go | 2 +- warp/client.go | 2 +- warp/handlers/signature_request.go | 2 +- warp/handlers/stats.go | 2 +- warp/service.go | 4 +- warp/verifier_stats.go | 2 +- 371 files changed, 1088 insertions(+), 1143 deletions(-) diff --git a/accounts/abi/abi.go b/accounts/abi/abi.go index 1a6e224090..cb924a0189 100644 --- a/accounts/abi/abi.go +++ b/accounts/abi/abi.go @@ -34,8 +34,8 @@ import ( "io" "math/big" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" ) // The ABI holds information about a contract's context and available diff --git a/accounts/abi/abi_extra_test.go b/accounts/abi/abi_extra_test.go index 52bce1b0a4..32d3c2d0b5 100644 --- a/accounts/abi/abi_extra_test.go +++ b/accounts/abi/abi_extra_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/require" ) diff --git a/accounts/abi/abi_test.go b/accounts/abi/abi_test.go index 023ff5cc4e..ee46105203 100644 --- a/accounts/abi/abi_test.go +++ b/accounts/abi/abi_test.go @@ -36,9 +36,9 @@ import ( "strings" "testing" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/math" + "github.com/ava-labs/libevm/crypto" "github.com/stretchr/testify/assert" ) diff --git a/accounts/abi/bind/auth.go b/accounts/abi/bind/auth.go index ec313dffbb..5de9741d05 100644 --- a/accounts/abi/bind/auth.go +++ b/accounts/abi/bind/auth.go @@ -34,12 +34,12 @@ import ( "math/big" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/accounts/external" - "github.com/ethereum/go-ethereum/accounts/keystore" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/accounts" + "github.com/ava-labs/libevm/accounts/external" + "github.com/ava-labs/libevm/accounts/keystore" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/log" ) // ErrNoChainID is returned whenever the user failed to specify a chain id. diff --git a/accounts/abi/bind/backend.go b/accounts/abi/bind/backend.go index 4cd21c399b..1aaf78161b 100644 --- a/accounts/abi/bind/backend.go +++ b/accounts/abi/bind/backend.go @@ -33,7 +33,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/interfaces" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) var ( diff --git a/accounts/abi/bind/backends/simulated.go b/accounts/abi/bind/backends/simulated.go index f1594e525b..9dadf11482 100644 --- a/accounts/abi/bind/backends/simulated.go +++ b/accounts/abi/bind/backends/simulated.go @@ -33,7 +33,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/ethclient/simulated" "github.com/ava-labs/coreth/interfaces" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // Verify that SimulatedBackend implements required interfaces diff --git a/accounts/abi/bind/base.go b/accounts/abi/bind/base.go index f3132a6614..92da2b79ac 100644 --- a/accounts/abi/bind/base.go +++ b/accounts/abi/bind/base.go @@ -39,9 +39,9 @@ import ( "github.com/ava-labs/coreth/interfaces" "github.com/ava-labs/coreth/nativeasset" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/event" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/event" ) const basefeeWiggleMultiplier = 2 diff --git a/accounts/abi/bind/base_test.go b/accounts/abi/bind/base_test.go index 0605dc2653..d6c0a50e6e 100644 --- a/accounts/abi/bind/base_test.go +++ b/accounts/abi/bind/base_test.go @@ -40,10 +40,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/interfaces" "github.com/ava-labs/coreth/nativeasset" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/rlp" "github.com/stretchr/testify/assert" ) diff --git a/accounts/abi/bind/bind.go b/accounts/abi/bind/bind.go index 3dfbb6d243..4347ba8169 100644 --- a/accounts/abi/bind/bind.go +++ b/accounts/abi/bind/bind.go @@ -40,7 +40,7 @@ import ( "unicode" "github.com/ava-labs/coreth/accounts/abi" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" ) // Lang is a target programming language selector to generate bindings for. diff --git a/accounts/abi/bind/bind_extra_test.go b/accounts/abi/bind/bind_extra_test.go index 661eca3296..80e5932648 100644 --- a/accounts/abi/bind/bind_extra_test.go +++ b/accounts/abi/bind/bind_extra_test.go @@ -16,8 +16,8 @@ import ( "github.com/ava-labs/coreth/ethclient/simulated" "github.com/ava-labs/coreth/node" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" ) // TestGetSenderNativeAssetCall checks that the NativeAssetCall proxies the diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index a54919722c..c1035f6b8a 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -35,7 +35,7 @@ import ( "strings" "testing" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) var bindTests = []struct { @@ -56,7 +56,7 @@ var bindTests = []struct { `contract NilContract {}`, []string{`606060405260068060106000396000f3606060405200`}, []string{`[]`}, - `"github.com/ethereum/go-ethereum/common"`, + `"github.com/ava-labs/libevm/common"`, ` if b, err := NewEmpty(common.Address{}, nil); b == nil || err != nil { t.Fatalf("combined binding (%v) nil or error (%v) not nil", b, nil) @@ -79,7 +79,7 @@ var bindTests = []struct { `https://ethereum.org/token`, []string{`60606040526040516107fd3803806107fd83398101604052805160805160a05160c051929391820192909101600160a060020a0333166000908152600360209081526040822086905581548551838052601f6002600019610100600186161502019093169290920482018390047f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56390810193919290918801908390106100e857805160ff19168380011785555b506101189291505b8082111561017157600081556001016100b4565b50506002805460ff19168317905550505050610658806101a56000396000f35b828001600101855582156100ac579182015b828111156100ac5782518260005055916020019190600101906100fa565b50508060016000509080519060200190828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061017557805160ff19168380011785555b506100c89291506100b4565b5090565b82800160010185558215610165579182015b8281111561016557825182600050559160200191906001019061018756606060405236156100775760e060020a600035046306fdde03811461007f57806323b872dd146100dc578063313ce5671461010e57806370a082311461011a57806395d89b4114610132578063a9059cbb1461018e578063cae9ca51146101bd578063dc3080f21461031c578063dd62ed3e14610341575b610365610002565b61036760008054602060026001831615610100026000190190921691909104601f810182900490910260809081016040526060828152929190828280156104eb5780601f106104c0576101008083540402835291602001916104eb565b6103d5600435602435604435600160a060020a038316600090815260036020526040812054829010156104f357610002565b6103e760025460ff1681565b6103d560043560036020526000908152604090205481565b610367600180546020600282841615610100026000190190921691909104601f810182900490910260809081016040526060828152929190828280156104eb5780601f106104c0576101008083540402835291602001916104eb565b610365600435602435600160a060020a033316600090815260036020526040902054819010156103f157610002565b60806020604435600481810135601f8101849004909302840160405260608381526103d5948235946024803595606494939101919081908382808284375094965050505050505060006000836004600050600033600160a060020a03168152602001908152602001600020600050600087600160a060020a031681526020019081526020016000206000508190555084905080600160a060020a0316638f4ffcb1338630876040518560e060020a0281526004018085600160a060020a0316815260200184815260200183600160a060020a03168152602001806020018281038252838181518152602001915080519060200190808383829060006004602084601f0104600f02600301f150905090810190601f1680156102f25780820380516001836020036101000a031916815260200191505b50955050505050506000604051808303816000876161da5a03f11561000257505050509392505050565b6005602090815260043560009081526040808220909252602435815220546103d59081565b60046020818152903560009081526040808220909252602435815220546103d59081565b005b60405180806020018281038252838181518152602001915080519060200190808383829060006004602084601f0104600f02600301f150905090810190601f1680156103c75780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60408051918252519081900360200190f35b6060908152602090f35b600160a060020a03821660009081526040902054808201101561041357610002565b806003600050600033600160a060020a03168152602001908152602001600020600082828250540392505081905550806003600050600084600160a060020a0316815260200190815260200160002060008282825054019250508190555081600160a060020a031633600160a060020a03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b820191906000526020600020905b8154815290600101906020018083116104ce57829003601f168201915b505050505081565b600160a060020a03831681526040812054808301101561051257610002565b600160a060020a0380851680835260046020908152604080852033949094168086529382528085205492855260058252808520938552929052908220548301111561055c57610002565b816003600050600086600160a060020a03168152602001908152602001600020600082828250540392505081905550816003600050600085600160a060020a03168152602001908152602001600020600082828250540192505081905550816005600050600086600160a060020a03168152602001908152602001600020600050600033600160a060020a0316815260200190815260200160002060008282825054019250508190555082600160a060020a031633600160a060020a03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3939250505056`}, []string{`[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"},{"name":"_extraData","type":"bytes"}],"name":"approveAndCall","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"spentAllowance","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"inputs":[{"name":"initialSupply","type":"uint256"},{"name":"tokenName","type":"string"},{"name":"decimalUnits","type":"uint8"},{"name":"tokenSymbol","type":"string"}],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]`}, - `"github.com/ethereum/go-ethereum/common"`, + `"github.com/ava-labs/libevm/common"`, ` if b, err := NewToken(common.Address{}, nil); b == nil || err != nil { t.Fatalf("binding (%v) nil or error (%v) not nil", b, nil) @@ -95,7 +95,7 @@ var bindTests = []struct { `https://ethereum.org/crowdsale`, []string{`606060408190526007805460ff1916905560a0806105a883396101006040529051608051915160c05160e05160008054600160a060020a03199081169095178155670de0b6b3a7640000958602600155603c9093024201600355930260045560058054909216909217905561052f90819061007990396000f36060604052361561006c5760e060020a600035046301cb3b20811461008257806329dcb0cf1461014457806338af3eed1461014d5780636e66f6e91461015f5780637a3a0e84146101715780637b3e5e7b1461017a578063a035b1fe14610183578063dc0d3dff1461018c575b61020060075460009060ff161561032357610002565b61020060035460009042106103205760025460015490106103cb576002548154600160a060020a0316908290606082818181858883f150915460025460408051600160a060020a039390931683526020830191909152818101869052517fe842aea7a5f1b01049d752008c53c52890b1a6daf660cf39e8eec506112bbdf6945090819003909201919050a15b60405160008054600160a060020a039081169230909116319082818181858883f150506007805460ff1916600117905550505050565b6103a160035481565b6103ab600054600160a060020a031681565b6103ab600554600160a060020a031681565b6103a160015481565b6103a160025481565b6103a160045481565b6103be60043560068054829081101561000257506000526002027ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f8101547ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d409190910154600160a060020a03919091169082565b005b505050815481101561000257906000526020600020906002020160005060008201518160000160006101000a815481600160a060020a030219169083021790555060208201518160010160005055905050806002600082828250540192505081905550600560009054906101000a9004600160a060020a0316600160a060020a031663a9059cbb3360046000505484046040518360e060020a0281526004018083600160a060020a03168152602001828152602001925050506000604051808303816000876161da5a03f11561000257505060408051600160a060020a03331681526020810184905260018183015290517fe842aea7a5f1b01049d752008c53c52890b1a6daf660cf39e8eec506112bbdf692509081900360600190a15b50565b5060a0604052336060908152346080819052600680546001810180835592939282908280158290116102025760020281600202836000526020600020918201910161020291905b8082111561039d57805473ffffffffffffffffffffffffffffffffffffffff19168155600060019190910190815561036a565b5090565b6060908152602090f35b600160a060020a03166060908152602090f35b6060918252608052604090f35b5b60065481101561010e576006805482908110156100025760009182526002027ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f0190600680549254600160a060020a0316928490811015610002576002027ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d40015460405190915082818181858883f19350505050507fe842aea7a5f1b01049d752008c53c52890b1a6daf660cf39e8eec506112bbdf660066000508281548110156100025760008290526002027ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f01548154600160a060020a039190911691908490811015610002576002027ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d40015460408051600160a060020a0394909416845260208401919091526000838201525191829003606001919050a16001016103cc56`}, []string{`[{"constant":false,"inputs":[],"name":"checkGoalReached","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"deadline","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"beneficiary","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":true,"inputs":[],"name":"tokenReward","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":true,"inputs":[],"name":"fundingGoal","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"amountRaised","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"price","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"funders","outputs":[{"name":"addr","type":"address"},{"name":"amount","type":"uint256"}],"type":"function"},{"inputs":[{"name":"ifSuccessfulSendTo","type":"address"},{"name":"fundingGoalInEthers","type":"uint256"},{"name":"durationInMinutes","type":"uint256"},{"name":"etherCostOfEachToken","type":"uint256"},{"name":"addressOfTokenUsedAsReward","type":"address"}],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"backer","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"isContribution","type":"bool"}],"name":"FundTransfer","type":"event"}]`}, - `"github.com/ethereum/go-ethereum/common"`, + `"github.com/ava-labs/libevm/common"`, ` if b, err := NewCrowdsale(common.Address{}, nil); b == nil || err != nil { t.Fatalf("binding (%v) nil or error (%v) not nil", b, nil) @@ -111,7 +111,7 @@ var bindTests = []struct { `https://ethereum.org/dao`, []string{`606060405260405160808061145f833960e06040529051905160a05160c05160008054600160a060020a03191633179055600184815560028490556003839055600780549182018082558280158290116100b8576003028160030283600052602060002091820191016100b891906101c8565b50506060919091015160029190910155600160a060020a0381166000146100a65760008054600160a060020a031916821790555b505050506111f18061026e6000396000f35b505060408051608081018252600080825260208281018290528351908101845281815292820192909252426060820152600780549194509250811015610002579081527fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c6889050815181546020848101517401000000000000000000000000000000000000000002600160a060020a03199290921690921760a060020a60ff021916178255604083015180516001848101805460008281528690209195600293821615610100026000190190911692909204601f9081018390048201949192919091019083901061023e57805160ff19168380011785555b50610072929150610226565b5050600060028201556001015b8082111561023a578054600160a860020a031916815560018181018054600080835592600290821615610100026000190190911604601f81901061020c57506101bb565b601f0160209004906000526020600020908101906101bb91905b8082111561023a5760008155600101610226565b5090565b828001600101855582156101af579182015b828111156101af57825182600050559160200191906001019061025056606060405236156100b95760e060020a6000350463013cf08b81146100bb578063237e9492146101285780633910682114610281578063400e3949146102995780635daf08ca146102a257806369bd34361461032f5780638160f0b5146103385780638da5cb5b146103415780639644fcbd14610353578063aa02a90f146103be578063b1050da5146103c7578063bcca1fd3146104b5578063d3c0715b146104dc578063eceb29451461058d578063f2fde38b1461067b575b005b61069c6004356004805482908110156100025790600052602060002090600a02016000506005810154815460018301546003840154600485015460068601546007870154600160a060020a03959095169750929560020194919360ff828116946101009093041692919089565b60408051602060248035600481810135601f81018590048502860185019096528585526107759581359591946044949293909201918190840183828082843750949650505050505050600060006004600050848154811015610002575090527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19e600a8402908101547f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b909101904210806101e65750600481015460ff165b8061026757508060000160009054906101000a9004600160a060020a03168160010160005054846040518084600160a060020a0316606060020a0281526014018381526020018280519060200190808383829060006004602084601f0104600f02600301f15090500193505050506040518091039020816007016000505414155b8061027757506001546005820154105b1561109257610002565b61077560043560066020526000908152604090205481565b61077560055481565b61078760043560078054829081101561000257506000526003026000805160206111d18339815191528101547fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c68a820154600160a060020a0382169260a060020a90920460ff16917fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c689019084565b61077560025481565b61077560015481565b610830600054600160a060020a031681565b604080516020604435600481810135601f81018490048402850184019095528484526100b9948135946024803595939460649492939101918190840183828082843750949650505050505050600080548190600160a060020a03908116339091161461084d57610002565b61077560035481565b604080516020604435600481810135601f8101849004840285018401909552848452610775948135946024803595939460649492939101918190840183828082843750506040805160209735808a0135601f81018a90048a0283018a019093528282529698976084979196506024909101945090925082915084018382808284375094965050505050505033600160a060020a031660009081526006602052604081205481908114806104ab5750604081205460078054909190811015610002579082526003026000805160206111d1833981519152015460a060020a900460ff16155b15610ce557610002565b6100b960043560243560443560005433600160a060020a03908116911614610b1857610002565b604080516020604435600481810135601f810184900484028501840190955284845261077594813594602480359593946064949293910191819084018382808284375094965050505050505033600160a060020a031660009081526006602052604081205481908114806105835750604081205460078054909190811015610002579082526003026000805160206111d18339815191520181505460a060020a900460ff16155b15610f1d57610002565b604080516020606435600481810135601f81018490048402850184019095528484526107759481359460248035956044359560849492019190819084018382808284375094965050505050505060006000600460005086815481101561000257908252600a027f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b01815090508484846040518084600160a060020a0316606060020a0281526014018381526020018280519060200190808383829060006004602084601f0104600f02600301f150905001935050505060405180910390208160070160005054149150610cdc565b6100b960043560005433600160a060020a03908116911614610f0857610002565b604051808a600160a060020a031681526020018981526020018060200188815260200187815260200186815260200185815260200184815260200183815260200182810382528981815460018160011615610100020316600290048152602001915080546001816001161561010002031660029004801561075e5780601f106107335761010080835404028352916020019161075e565b820191906000526020600020905b81548152906001019060200180831161074157829003601f168201915b50509a505050505050505050505060405180910390f35b60408051918252519081900360200190f35b60408051600160a060020a038616815260208101859052606081018390526080918101828152845460026001821615610100026000190190911604928201839052909160a08301908590801561081e5780601f106107f35761010080835404028352916020019161081e565b820191906000526020600020905b81548152906001019060200180831161080157829003601f168201915b50509550505050505060405180910390f35b60408051600160a060020a03929092168252519081900360200190f35b600160a060020a03851660009081526006602052604081205414156108a957604060002060078054918290556001820180825582801582901161095c5760030281600302836000526020600020918201910161095c9190610a4f565b600160a060020a03851660009081526006602052604090205460078054919350908390811015610002575060005250600381026000805160206111d183398151915201805474ff0000000000000000000000000000000000000000191660a060020a85021781555b60408051600160a060020a03871681526020810186905281517f27b022af4a8347100c7a041ce5ccf8e14d644ff05de696315196faae8cd50c9b929181900390910190a15050505050565b505050915081506080604051908101604052808681526020018581526020018481526020014281526020015060076000508381548110156100025790600052602060002090600302016000508151815460208481015160a060020a02600160a060020a03199290921690921774ff00000000000000000000000000000000000000001916178255604083015180516001848101805460008281528690209195600293821615610100026000190190911692909204601f90810183900482019491929190910190839010610ad357805160ff19168380011785555b50610b03929150610abb565b5050600060028201556001015b80821115610acf57805474ffffffffffffffffffffffffffffffffffffffffff1916815560018181018054600080835592600290821615610100026000190190911604601f819010610aa15750610a42565b601f016020900490600052602060002090810190610a4291905b80821115610acf5760008155600101610abb565b5090565b82800160010185558215610a36579182015b82811115610a36578251826000505591602001919060010190610ae5565b50506060919091015160029190910155610911565b600183905560028290556003819055604080518481526020810184905280820183905290517fa439d3fa452be5e0e1e24a8145e715f4fd8b9c08c96a42fd82a855a85e5d57de9181900360600190a1505050565b50508585846040518084600160a060020a0316606060020a0281526014018381526020018280519060200190808383829060006004602084601f0104600f02600301f150905001935050505060405180910390208160070160005081905550600260005054603c024201816003016000508190555060008160040160006101000a81548160ff0219169083021790555060008160040160016101000a81548160ff02191690830217905550600081600501600050819055507f646fec02522b41e7125cfc859a64fd4f4cefd5dc3b6237ca0abe251ded1fa881828787876040518085815260200184600160a060020a03168152602001838152602001806020018281038252838181518152602001915080519060200190808383829060006004602084601f0104600f02600301f150905090810190601f168015610cc45780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a1600182016005555b50949350505050565b6004805460018101808355909190828015829011610d1c57600a0281600a028360005260206000209182019101610d1c9190610db8565b505060048054929450918491508110156100025790600052602060002090600a02016000508054600160a060020a031916871781556001818101879055855160028381018054600082815260209081902096975091959481161561010002600019011691909104601f90810182900484019391890190839010610ed857805160ff19168380011785555b50610b6c929150610abb565b50506001015b80821115610acf578054600160a060020a03191681556000600182810182905560028381018054848255909281161561010002600019011604601f819010610e9c57505b5060006003830181905560048301805461ffff191690556005830181905560068301819055600783018190556008830180548282559082526020909120610db2916002028101905b80821115610acf57805474ffffffffffffffffffffffffffffffffffffffffff1916815560018181018054600080835592600290821615610100026000190190911604601f819010610eba57505b5050600101610e44565b601f016020900490600052602060002090810190610dfc9190610abb565b601f016020900490600052602060002090810190610e929190610abb565b82800160010185558215610da6579182015b82811115610da6578251826000505591602001919060010190610eea565b60008054600160a060020a0319168217905550565b600480548690811015610002576000918252600a027f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b01905033600160a060020a0316600090815260098201602052604090205490915060ff1660011415610f8457610002565b33600160a060020a031660009081526009820160205260409020805460ff1916600190811790915560058201805490910190558315610fcd576006810180546001019055610fda565b6006810180546000190190555b7fc34f869b7ff431b034b7b9aea9822dac189a685e0b015c7d1be3add3f89128e8858533866040518085815260200184815260200183600160a060020a03168152602001806020018281038252838181518152602001915080519060200190808383829060006004602084601f0104600f02600301f150905090810190601f16801561107a5780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a1509392505050565b6006810154600354901315611158578060000160009054906101000a9004600160a060020a0316600160a060020a03168160010160005054670de0b6b3a76400000284604051808280519060200190808383829060006004602084601f0104600f02600301f150905090810190601f1680156111225780820380516001836020036101000a031916815260200191505b5091505060006040518083038185876185025a03f15050505060048101805460ff191660011761ff00191661010017905561116d565b60048101805460ff191660011761ff00191690555b60068101546005820154600483015460408051888152602081019490945283810192909252610100900460ff166060830152517fd220b7272a8b6d0d7d6bcdace67b936a8f175e6d5c1b3ee438b72256b32ab3af9181900360800190a1509291505056a66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c688`}, []string{`[{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"proposals","outputs":[{"name":"recipient","type":"address"},{"name":"amount","type":"uint256"},{"name":"description","type":"string"},{"name":"votingDeadline","type":"uint256"},{"name":"executed","type":"bool"},{"name":"proposalPassed","type":"bool"},{"name":"numberOfVotes","type":"uint256"},{"name":"currentResult","type":"int256"},{"name":"proposalHash","type":"bytes32"}],"type":"function"},{"constant":false,"inputs":[{"name":"proposalNumber","type":"uint256"},{"name":"transactionBytecode","type":"bytes"}],"name":"executeProposal","outputs":[{"name":"result","type":"int256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"memberId","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numProposals","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"members","outputs":[{"name":"member","type":"address"},{"name":"canVote","type":"bool"},{"name":"name","type":"string"},{"name":"memberSince","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"debatingPeriodInMinutes","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"minimumQuorum","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":false,"inputs":[{"name":"targetMember","type":"address"},{"name":"canVote","type":"bool"},{"name":"memberName","type":"string"}],"name":"changeMembership","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"majorityMargin","outputs":[{"name":"","type":"int256"}],"type":"function"},{"constant":false,"inputs":[{"name":"beneficiary","type":"address"},{"name":"etherAmount","type":"uint256"},{"name":"JobDescription","type":"string"},{"name":"transactionBytecode","type":"bytes"}],"name":"newProposal","outputs":[{"name":"proposalID","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"minimumQuorumForProposals","type":"uint256"},{"name":"minutesForDebate","type":"uint256"},{"name":"marginOfVotesForMajority","type":"int256"}],"name":"changeVotingRules","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"proposalNumber","type":"uint256"},{"name":"supportsProposal","type":"bool"},{"name":"justificationText","type":"string"}],"name":"vote","outputs":[{"name":"voteID","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[{"name":"proposalNumber","type":"uint256"},{"name":"beneficiary","type":"address"},{"name":"etherAmount","type":"uint256"},{"name":"transactionBytecode","type":"bytes"}],"name":"checkProposalCode","outputs":[{"name":"codeChecksOut","type":"bool"}],"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"type":"function"},{"inputs":[{"name":"minimumQuorumForProposals","type":"uint256"},{"name":"minutesForDebate","type":"uint256"},{"name":"marginOfVotesForMajority","type":"int256"},{"name":"congressLeader","type":"address"}],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"proposalID","type":"uint256"},{"indexed":false,"name":"recipient","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"description","type":"string"}],"name":"ProposalAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"proposalID","type":"uint256"},{"indexed":false,"name":"position","type":"bool"},{"indexed":false,"name":"voter","type":"address"},{"indexed":false,"name":"justification","type":"string"}],"name":"Voted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"proposalID","type":"uint256"},{"indexed":false,"name":"result","type":"int256"},{"indexed":false,"name":"quorum","type":"uint256"},{"indexed":false,"name":"active","type":"bool"}],"name":"ProposalTallied","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"member","type":"address"},{"indexed":false,"name":"isMember","type":"bool"}],"name":"MembershipChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"minimumQuorum","type":"uint256"},{"indexed":false,"name":"debatingPeriodInMinutes","type":"uint256"},{"indexed":false,"name":"majorityMargin","type":"int256"}],"name":"ChangeOfRules","type":"event"}]`}, - `"github.com/ethereum/go-ethereum/common"`, + `"github.com/ava-labs/libevm/common"`, ` if b, err := NewDAO(common.Address{}, nil); b == nil || err != nil { t.Fatalf("binding (%v) nil or error (%v) not nil", b, nil) @@ -138,7 +138,7 @@ var bindTests = []struct { ` "fmt" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" `, `if b, err := NewInputChecker(common.Address{}, nil); b == nil || err != nil { t.Fatalf("binding (%v) nil or error (%v) not nil", b, nil) @@ -176,7 +176,7 @@ var bindTests = []struct { ` "fmt" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" `, `if b, err := NewOutputChecker(common.Address{}, nil); b == nil || err != nil { t.Fatalf("binding (%v) nil or error (%v) not nil", b, nil) @@ -217,7 +217,7 @@ var bindTests = []struct { "math/big" "reflect" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" `, `if e, err := NewEventChecker(common.Address{}, nil); e == nil || err != nil { t.Fatalf("binding (%v) nil or error (%v) not nil", e, nil) @@ -300,7 +300,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -356,7 +356,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -402,7 +402,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -458,9 +458,9 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -508,7 +508,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -575,7 +575,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -619,7 +619,7 @@ var bindTests = []struct { ` "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/ava-labs/coreth/core/types" `, ` @@ -658,7 +658,7 @@ var bindTests = []struct { ` "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/ava-labs/coreth/core/types" `, ` @@ -707,7 +707,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -755,9 +755,9 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -832,7 +832,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -924,9 +924,9 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -1116,7 +1116,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -1251,7 +1251,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` @@ -1393,7 +1393,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -1459,7 +1459,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Initialize test accounts @@ -1567,7 +1567,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" "github.com/ava-labs/coreth/core/types" `, ` @@ -1630,7 +1630,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" "github.com/ava-labs/coreth/core/types" `, ` @@ -1693,7 +1693,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` // Generate a new random account and a funded simulator @@ -1754,7 +1754,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` key, _ := crypto.GenerateKey() @@ -1842,7 +1842,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` var ( @@ -1912,7 +1912,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, ` var ( @@ -1964,7 +1964,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, tester: ` var ( @@ -2012,7 +2012,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, tester: ` var ( @@ -2053,7 +2053,7 @@ var bindTests = []struct { "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/accounts/abi/bind/backends" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" `, tester: ` var ( @@ -2088,7 +2088,7 @@ var bindTests = []struct { bytecode: []string{"0x6080604052348015600f57600080fd5b5060958061001e6000396000f3fe6080604052348015600f57600080fd5b5060043610603c5760003560e01c80639d993132146041578063d02767c7146049578063ffa02795146051575b600080fd5b60476059565b005b604f605b565b005b6057605d565b005b565b565b56fea26469706673582212200382ca602dff96a7e2ba54657985e2b4ac423a56abe4a1f0667bc635c4d4371f64736f6c63430008110033"}, abi: []string{`[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_param","type":"address"}],"name":"_1TestEvent","type":"event"},{"inputs":[],"name":"_1test","outputs":[],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"__1test","outputs":[],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"__2test","outputs":[],"stateMutability":"pure","type":"function"}]`}, imports: ` - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" `, tester: ` if b, err := NewNumericMethodName(common.Address{}, nil); b == nil || err != nil { diff --git a/accounts/abi/bind/template.go b/accounts/abi/bind/template.go index 22dca1e71d..aa1de7f913 100644 --- a/accounts/abi/bind/template.go +++ b/accounts/abi/bind/template.go @@ -105,8 +105,8 @@ import ( "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/interfaces" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/event" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/event" ) // Reference imports to suppress errors if they are not otherwise used. diff --git a/accounts/abi/bind/util.go b/accounts/abi/bind/util.go index 378f7ef877..508caf7cf2 100644 --- a/accounts/abi/bind/util.go +++ b/accounts/abi/bind/util.go @@ -33,8 +33,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/interfaces" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) // WaitMined waits for tx to be mined on the blockchain. diff --git a/accounts/abi/bind/util_test.go b/accounts/abi/bind/util_test.go index ec30d8c832..e1311c47d9 100644 --- a/accounts/abi/bind/util_test.go +++ b/accounts/abi/bind/util_test.go @@ -37,8 +37,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/ethclient/simulated" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" ) var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") diff --git a/accounts/abi/error.go b/accounts/abi/error.go index a968fd20c0..46b056c052 100644 --- a/accounts/abi/error.go +++ b/accounts/abi/error.go @@ -31,8 +31,8 @@ import ( "fmt" "strings" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" ) type Error struct { diff --git a/accounts/abi/event.go b/accounts/abi/event.go index f4f0f5d92d..39b55bb62c 100644 --- a/accounts/abi/event.go +++ b/accounts/abi/event.go @@ -30,8 +30,8 @@ import ( "fmt" "strings" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" ) // Event is an event potentially triggered by the EVM's LOG mechanism. The Event diff --git a/accounts/abi/event_test.go b/accounts/abi/event_test.go index 4a254e9950..63f9fb2ffe 100644 --- a/accounts/abi/event_test.go +++ b/accounts/abi/event_test.go @@ -35,8 +35,8 @@ import ( "strings" "testing" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/accounts/abi/method.go b/accounts/abi/method.go index 1da260da2c..e437d8d2a9 100644 --- a/accounts/abi/method.go +++ b/accounts/abi/method.go @@ -30,7 +30,7 @@ import ( "fmt" "strings" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" ) // FunctionType represents different types of functions a contract might have. diff --git a/accounts/abi/pack.go b/accounts/abi/pack.go index 9f9f2b23d5..830df0b390 100644 --- a/accounts/abi/pack.go +++ b/accounts/abi/pack.go @@ -32,8 +32,8 @@ import ( "math/big" "reflect" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/math" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/math" ) // packBytesSlice packs the given bytes as [L, V] as the canonical representation diff --git a/accounts/abi/pack_test.go b/accounts/abi/pack_test.go index b13de922a5..c76866c369 100644 --- a/accounts/abi/pack_test.go +++ b/accounts/abi/pack_test.go @@ -37,7 +37,7 @@ import ( "strings" "testing" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // TestPack tests the general pack/unpack tests in packing_test.go diff --git a/accounts/abi/packing_test.go b/accounts/abi/packing_test.go index 8e876dcaef..0c2ee00745 100644 --- a/accounts/abi/packing_test.go +++ b/accounts/abi/packing_test.go @@ -29,7 +29,7 @@ package abi import ( "math/big" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) type packUnpackTest struct { diff --git a/accounts/abi/topics.go b/accounts/abi/topics.go index 03082f221e..0e3cb383ee 100644 --- a/accounts/abi/topics.go +++ b/accounts/abi/topics.go @@ -33,9 +33,9 @@ import ( "math/big" "reflect" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/math" + "github.com/ava-labs/libevm/crypto" ) // packTopic packs rule into the corresponding hash value for a log's topic diff --git a/accounts/abi/topics_test.go b/accounts/abi/topics_test.go index 53e4327bf6..cf9ca32b4f 100644 --- a/accounts/abi/topics_test.go +++ b/accounts/abi/topics_test.go @@ -32,8 +32,8 @@ import ( "reflect" "testing" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" ) func TestMakeTopics(t *testing.T) { diff --git a/accounts/abi/type.go b/accounts/abi/type.go index 75a6c15fd7..93678f5578 100644 --- a/accounts/abi/type.go +++ b/accounts/abi/type.go @@ -36,7 +36,7 @@ import ( "unicode" "unicode/utf8" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // Type enumerator diff --git a/accounts/abi/type_test.go b/accounts/abi/type_test.go index ad0daffe06..c55559167f 100644 --- a/accounts/abi/type_test.go +++ b/accounts/abi/type_test.go @@ -31,8 +31,8 @@ import ( "reflect" "testing" + "github.com/ava-labs/libevm/common" "github.com/davecgh/go-spew/spew" - "github.com/ethereum/go-ethereum/common" ) // typeWithoutStringer is a alias for the Type type which simply doesn't implement diff --git a/accounts/abi/unpack.go b/accounts/abi/unpack.go index b975cb8802..c161c81767 100644 --- a/accounts/abi/unpack.go +++ b/accounts/abi/unpack.go @@ -34,7 +34,7 @@ import ( "math/big" "reflect" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) var ( diff --git a/accounts/abi/unpack_test.go b/accounts/abi/unpack_test.go index d7f383a731..ae55cf3250 100644 --- a/accounts/abi/unpack_test.go +++ b/accounts/abi/unpack_test.go @@ -37,7 +37,7 @@ import ( "strings" "testing" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/require" ) diff --git a/cmd/abigen/main.go b/cmd/abigen/main.go index a6f670ea4d..2dd4a35682 100644 --- a/cmd/abigen/main.go +++ b/cmd/abigen/main.go @@ -37,9 +37,9 @@ import ( "github.com/ava-labs/coreth/accounts/abi/bind" "github.com/ava-labs/coreth/cmd/utils" "github.com/ava-labs/coreth/internal/flags" - "github.com/ethereum/go-ethereum/common/compiler" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common/compiler" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/log" "github.com/urfave/cli/v2" ) diff --git a/consensus/consensus.go b/consensus/consensus.go index d4e247ceaf..19252097c7 100644 --- a/consensus/consensus.go +++ b/consensus/consensus.go @@ -33,7 +33,7 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // ChainHeaderReader defines a small collection of methods needed to access the local diff --git a/consensus/dummy/consensus.go b/consensus/dummy/consensus.go index 8733632e04..ae60583bfe 100644 --- a/consensus/dummy/consensus.go +++ b/consensus/dummy/consensus.go @@ -17,10 +17,9 @@ import ( "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/trie" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/trie" customheader "github.com/ava-labs/coreth/plugin/evm/header" ) @@ -172,7 +171,7 @@ func (eng *DummyEngine) verifyHeaderGasFields(config *params.ChainConfig, header // Enforce BlockGasCost constraints expectedBlockGasCost := customheader.BlockGasCost( - config, + configExtra, parent, header.Time, ) @@ -199,8 +198,8 @@ func (eng *DummyEngine) verifyHeader(chain consensus.ChainHeaderReader, header * } // Verify the extra data is well-formed. - configExtra := params.GetExtra(chain.Config()) - rules := config.GetAvalancheRules(header.Time) + config := chain.Config() + rules := params.GetExtra(config).GetAvalancheRules(header.Time) if err := customheader.VerifyExtra(rules, header.Extra); err != nil { return err } @@ -384,7 +383,7 @@ func (eng *DummyEngine) Finalize(chain consensus.ChainHeaderReader, block *types // Verify the BlockGasCost set in the header matches the expected value. blockGasCost := block.BlockGasCost() expectedBlockGasCost := customheader.BlockGasCost( - config, + configExtra, parent, timestamp, ) @@ -422,15 +421,15 @@ func (eng *DummyEngine) FinalizeAndAssemble(chain consensus.ChainHeaderReader, h } } - chainConfigExtra := params.GetExtra(chain.Config()) - if chainConfigExtra.IsApricotPhase4(header.Time) { + configExtra := params.GetExtra(chain.Config()) + if configExtra.IsApricotPhase4(header.Time) { header.ExtDataGasUsed = extDataGasUsed if header.ExtDataGasUsed == nil { header.ExtDataGasUsed = new(big.Int).Set(common.Big0) } // Calculate the required block gas cost for this block. blockGasCost := customheader.BlockGasCost( - config, + configExtra, parent, header.Time, ) @@ -448,12 +447,12 @@ func (eng *DummyEngine) FinalizeAndAssemble(chain consensus.ChainHeaderReader, h } } // commit the final state root - header.Root = state.IntermediateRoot(config.IsEIP158(header.Number)) + header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number)) // Header seems complete, assemble into a block and return return types.NewBlockWithExtData( header, txs, uncles, receipts, trie.NewStackTrie(nil), - extraData, chainConfigExtra.IsApricotPhase1(header.Time), + extraData, configExtra.IsApricotPhase1(header.Time), ), nil } diff --git a/consensus/dummy/consensus_test.go b/consensus/dummy/consensus_test.go index 418c4ecc3f..76b3fb7a5e 100644 --- a/consensus/dummy/consensus_test.go +++ b/consensus/dummy/consensus_test.go @@ -11,7 +11,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/plugin/evm/ap4" "github.com/ava-labs/coreth/plugin/evm/header" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) func TestVerifyBlockFee(t *testing.T) { diff --git a/consensus/dummy/dynamic_fee_window.go b/consensus/dummy/dynamic_fee_window.go index 8c56ba3a29..81d61c5c78 100644 --- a/consensus/dummy/dynamic_fee_window.go +++ b/consensus/dummy/dynamic_fee_window.go @@ -10,7 +10,7 @@ import ( "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common/math" + "github.com/ava-labs/libevm/common/math" ) var ErrDynamicFeeWindowInsufficientLength = errors.New("insufficient length for dynamic fee window") diff --git a/consensus/dummy/dynamic_fee_window_test.go b/consensus/dummy/dynamic_fee_window_test.go index b3ec2297e6..b93dce9d64 100644 --- a/consensus/dummy/dynamic_fee_window_test.go +++ b/consensus/dummy/dynamic_fee_window_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common/math" + "github.com/ava-labs/libevm/common/math" "github.com/stretchr/testify/require" ) diff --git a/consensus/dummy/dynamic_fees.go b/consensus/dummy/dynamic_fees.go index a37337b5d4..0b066203c4 100644 --- a/consensus/dummy/dynamic_fees.go +++ b/consensus/dummy/dynamic_fees.go @@ -10,10 +10,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/plugin/evm/ap4" "github.com/ava-labs/coreth/plugin/evm/header" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/math" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/math" ) const ApricotPhase3BlockGasFee = 1_000_000 @@ -42,9 +43,10 @@ func CalcExtraPrefix( parent *types.Header, timestamp uint64, ) ([]byte, error) { + configExtra := params.GetExtra(config) switch { - case config.IsApricotPhase3(timestamp): - window, err := calcFeeWindow(config, parent, timestamp) + case configExtra.IsApricotPhase3(timestamp): + window, err := calcFeeWindow(configExtra, parent, timestamp) if err != nil { return nil, fmt.Errorf("failed to calculate fee window: %w", err) } @@ -60,9 +62,10 @@ func CalcExtraPrefix( // // Prior to AP3, the returned base fee will be nil. func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uint64) (*big.Int, error) { + configExtra := params.GetExtra(config) switch { - case config.IsApricotPhase3(timestamp): - return calcBaseFeeWithWindow(config, parent, timestamp) + case configExtra.IsApricotPhase3(timestamp): + return calcBaseFeeWithWindow(configExtra, parent, timestamp) default: // Prior to AP3 the expected base fee is nil. return nil, nil @@ -70,7 +73,7 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uin } // calcBaseFeeWithWindow should only be called if `timestamp` >= `config.ApricotPhase3Timestamp` -func calcBaseFeeWithWindow(config *params.ChainConfig, parent *types.Header, timestamp uint64) (*big.Int, error) { +func calcBaseFeeWithWindow(config *extras.ChainConfig, parent *types.Header, timestamp uint64) (*big.Int, error) { // If the current block is the first EIP-1559 block, or it is the genesis block // return the initial slice and initial base fee. if !config.IsApricotPhase3(parent.Time) || parent.Number.Cmp(common.Big0) == 0 { @@ -174,7 +177,7 @@ func calcBaseFeeWithWindow(config *params.ChainConfig, parent *types.Header, tim // // calcFeeWindow should only be called if timestamp >= config.ApricotPhase3Timestamp func calcFeeWindow( - config *params.ChainConfig, + config *extras.ChainConfig, parent *types.Header, timestamp uint64, ) (DynamicFeeWindow, error) { @@ -250,11 +253,12 @@ func calcFeeWindow( // Warning: This function should only be used in estimation and should not be // used when calculating the canonical base fee for a block. func EstimateNextBaseFee(config *params.ChainConfig, parent *types.Header, timestamp uint64) (*big.Int, error) { - if config.ApricotPhase3BlockTimestamp == nil { + configExtra := params.GetExtra(config) + if configExtra.ApricotPhase3BlockTimestamp == nil { return nil, errEstimateBaseFeeWithoutActivation } - timestamp = max(timestamp, parent.Time, *config.ApricotPhase3BlockTimestamp) + timestamp = max(timestamp, parent.Time, *configExtra.ApricotPhase3BlockTimestamp) return CalcBaseFee(config, parent, timestamp) } diff --git a/consensus/dummy/dynamic_fees_test.go b/consensus/dummy/dynamic_fees_test.go index b8b239c708..59021e69cc 100644 --- a/consensus/dummy/dynamic_fees_test.go +++ b/consensus/dummy/dynamic_fees_test.go @@ -9,10 +9,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/plugin/evm/ap4" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/math" + "github.com/ava-labs/libevm/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -371,7 +372,7 @@ func TestEstimateNextBaseFee(t *testing.T) { tests := []struct { name string - upgrades params.NetworkUpgrades + upgrades extras.NetworkUpgrades parentTime uint64 parentNumber int64 @@ -387,7 +388,7 @@ func TestEstimateNextBaseFee(t *testing.T) { }{ { name: "ap3", - upgrades: params.TestApricotPhase3Config.NetworkUpgrades, + upgrades: params.GetExtra(params.TestApricotPhase3Config).NetworkUpgrades, parentNumber: 1, parentExtra: (&DynamicFeeWindow{}).Bytes(), parentBaseFee: big.NewInt(params.ApricotPhase3MaxBaseFee), @@ -408,7 +409,7 @@ func TestEstimateNextBaseFee(t *testing.T) { }, { name: "ap3_not_scheduled", - upgrades: params.TestApricotPhase2Config.NetworkUpgrades, + upgrades: params.GetExtra(params.TestApricotPhase2Config).NetworkUpgrades, wantErr: errEstimateBaseFeeWithoutActivation, }, } @@ -416,9 +417,11 @@ func TestEstimateNextBaseFee(t *testing.T) { t.Run(test.name, func(t *testing.T) { require := require.New(t) - config := ¶ms.ChainConfig{ - NetworkUpgrades: test.upgrades, - } + config := params.WithExtra( + ¶ms.ChainConfig{}, + &extras.ChainConfig{ + NetworkUpgrades: test.upgrades, + }) parentHeader := &types.Header{ Time: test.parentTime, Number: big.NewInt(test.parentNumber), diff --git a/constants/constants.go b/constants/constants.go index 2514f58119..d1523eaa5b 100644 --- a/constants/constants.go +++ b/constants/constants.go @@ -3,7 +3,7 @@ package constants -import "github.com/ethereum/go-ethereum/common" +import "github.com/ava-labs/libevm/common" var ( BlackholeAddr = common.Address{ diff --git a/core/bench_test.go b/core/bench_test.go index 1150d1491d..4e98a6a600 100644 --- a/core/bench_test.go +++ b/core/bench_test.go @@ -35,11 +35,11 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/math" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/ethdb" ) func BenchmarkInsertChain_empty_memdb(b *testing.B) { diff --git a/core/block_validator.go b/core/block_validator.go index 3038ed8b5d..2c0fdceaf3 100644 --- a/core/block_validator.go +++ b/core/block_validator.go @@ -34,7 +34,7 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/trie" ) // BlockValidator is responsible for validating block headers, uncles and diff --git a/core/blockchain.go b/core/blockchain.go index 239c3653a4..6b2b7d4cf5 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -49,15 +49,15 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/triedb/hashdb" "github.com/ava-labs/coreth/triedb/pathdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/lru" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/event" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/metrics" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/lru" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/event" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/metrics" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/triedb" ) var ( diff --git a/core/blockchain_log_test.go b/core/blockchain_log_test.go index 1d430f4089..1dc6b3a3dc 100644 --- a/core/blockchain_log_test.go +++ b/core/blockchain_log_test.go @@ -13,9 +13,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" "github.com/stretchr/testify/require" ) diff --git a/core/blockchain_reader.go b/core/blockchain_reader.go index b023aea345..96199417ee 100644 --- a/core/blockchain_reader.go +++ b/core/blockchain_reader.go @@ -33,10 +33,10 @@ import ( "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/event" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/event" + "github.com/ava-labs/libevm/triedb" ) // CurrentHeader retrieves the current head header of the canonical chain. The diff --git a/core/blockchain_repair_test.go b/core/blockchain_repair_test.go index 6d9af7c2f4..4f29d198ce 100644 --- a/core/blockchain_repair_test.go +++ b/core/blockchain_repair_test.go @@ -38,10 +38,10 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/triedb" "github.com/stretchr/testify/require" ) diff --git a/core/blockchain_snapshot_test.go b/core/blockchain_snapshot_test.go index 6a9e18c446..510065b1b0 100644 --- a/core/blockchain_snapshot_test.go +++ b/core/blockchain_snapshot_test.go @@ -43,9 +43,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/ethdb" ) // snapshotTestBasic wraps the common testing fields in the snapshot tests. diff --git a/core/blockchain_test.go b/core/blockchain_test.go index 2bf4aef6ad..63fb388c4b 100644 --- a/core/blockchain_test.go +++ b/core/blockchain_test.go @@ -17,11 +17,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/params/extras" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/eth/tracers/logger" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/eth/tracers/logger" + "github.com/ava-labs/libevm/ethdb" "github.com/holiman/uint256" ) diff --git a/core/bloom_indexer.go b/core/bloom_indexer.go index ab8bc706f1..01152ec8f9 100644 --- a/core/bloom_indexer.go +++ b/core/bloom_indexer.go @@ -23,9 +23,9 @@ import ( "github.com/ava-labs/coreth/core/bloombits" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/bitutil" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/bitutil" + "github.com/ava-labs/libevm/ethdb" ) const ( diff --git a/core/bloombits/matcher.go b/core/bloombits/matcher.go index 532bc7af93..94bbb59c6b 100644 --- a/core/bloombits/matcher.go +++ b/core/bloombits/matcher.go @@ -36,8 +36,8 @@ import ( "sync/atomic" "time" - "github.com/ethereum/go-ethereum/common/bitutil" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common/bitutil" + "github.com/ava-labs/libevm/crypto" ) // bloomIndexes represents the bit indexes inside the bloom filter that belong diff --git a/core/bloombits/matcher_test.go b/core/bloombits/matcher_test.go index c095ec31e4..04318f3489 100644 --- a/core/bloombits/matcher_test.go +++ b/core/bloombits/matcher_test.go @@ -33,7 +33,7 @@ import ( "testing" "time" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) const testSectionSize = 4096 diff --git a/core/chain_indexer.go b/core/chain_indexer.go index 05cbc54c76..e5b098fae0 100644 --- a/core/chain_indexer.go +++ b/core/chain_indexer.go @@ -37,10 +37,10 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/event" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/event" + "github.com/ava-labs/libevm/log" ) // ChainIndexerBackend defines the methods needed to process chain segments in diff --git a/core/chain_indexer_test.go b/core/chain_indexer_test.go index 3edf175d3d..f284c33f45 100644 --- a/core/chain_indexer_test.go +++ b/core/chain_indexer_test.go @@ -37,7 +37,7 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // Runs multiple tests with randomized parameters. diff --git a/core/chain_makers.go b/core/chain_makers.go index 718f0b15d7..6e3ba925f1 100644 --- a/core/chain_makers.go +++ b/core/chain_makers.go @@ -37,10 +37,10 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/triedb" "github.com/holiman/uint256" ) diff --git a/core/chain_makers_test.go b/core/chain_makers_test.go index e2824ff81e..06b482388d 100644 --- a/core/chain_makers_test.go +++ b/core/chain_makers_test.go @@ -34,10 +34,10 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/triedb" ) func ExampleGenerateChain() { diff --git a/core/events.go b/core/events.go index 462d26d9ee..5a04f9b0ad 100644 --- a/core/events.go +++ b/core/events.go @@ -28,7 +28,7 @@ package core import ( "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // NewTxsEvent is posted when a batch of transactions enter the transaction pool. diff --git a/core/evm.go b/core/evm.go index 7b7825e27e..8f9559b44c 100644 --- a/core/evm.go +++ b/core/evm.go @@ -37,10 +37,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/predicate" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + ethtypes "github.com/ava-labs/libevm/core/types" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/log" "github.com/holiman/uint256" ) diff --git a/core/extstate/statedb.go b/core/extstate/statedb.go index 46e225c734..1c81601064 100644 --- a/core/extstate/statedb.go +++ b/core/extstate/statedb.go @@ -9,8 +9,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/predicate" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" ) type VmStateDB interface { diff --git a/core/extstate/test_statedb.go b/core/extstate/test_statedb.go index aa967aac2b..f6ed3ed77c 100644 --- a/core/extstate/test_statedb.go +++ b/core/extstate/test_statedb.go @@ -8,7 +8,7 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/precompile/contract" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/require" ) diff --git a/core/gen_genesis.go b/core/gen_genesis.go index b1b46a91ba..c3ffd954b3 100644 --- a/core/gen_genesis.go +++ b/core/gen_genesis.go @@ -8,10 +8,10 @@ import ( "math/big" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/params" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/common/math" + "github.com/ava-labs/libevm/params" ) var _ = (*genesisSpecMarshaling)(nil) diff --git a/core/genesis.go b/core/genesis.go index d86f118d1f..39b3a01397 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -38,13 +38,13 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/triedb/pathdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/common/math" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/triedb" "github.com/holiman/uint256" ) diff --git a/core/genesis_extra_test.go b/core/genesis_extra_test.go index 49121ad448..6701fefe0e 100644 --- a/core/genesis_extra_test.go +++ b/core/genesis_extra_test.go @@ -36,8 +36,8 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/triedb" "github.com/stretchr/testify/require" ) diff --git a/core/genesis_test.go b/core/genesis_test.go index 5ebeec3e77..9fba3f209e 100644 --- a/core/genesis_test.go +++ b/core/genesis_test.go @@ -41,12 +41,12 @@ import ( "github.com/ava-labs/coreth/precompile/contracts/warp" "github.com/ava-labs/coreth/triedb/pathdb" "github.com/ava-labs/coreth/utils" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/triedb" "github.com/davecgh/go-spew/spew" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/triedb" "github.com/stretchr/testify/require" ) diff --git a/core/headerchain.go b/core/headerchain.go index fe8f752d41..e7cf80ac4b 100644 --- a/core/headerchain.go +++ b/core/headerchain.go @@ -37,9 +37,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/lru" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/lru" + "github.com/ava-labs/libevm/ethdb" ) const ( diff --git a/core/headerchain_test.go b/core/headerchain_test.go index c9c088f03a..5117e2871e 100644 --- a/core/headerchain_test.go +++ b/core/headerchain_test.go @@ -37,8 +37,8 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" ) func verifyUnbrokenCanonchain(bc *BlockChain) error { diff --git a/core/main_test.go b/core/main_test.go index db4ccc8652..6ea70c4b6c 100644 --- a/core/main_test.go +++ b/core/main_test.go @@ -15,7 +15,7 @@ func TestMain(m *testing.M) { opts := []goleak.Option{ // No good way to shut down these goroutines: goleak.IgnoreTopFunction("github.com/ava-labs/coreth/core/state/snapshot.(*diskLayer).generate"), - goleak.IgnoreTopFunction("github.com/ethereum/go-ethereum/metrics.(*meterArbiter).tick"), + goleak.IgnoreTopFunction("github.com/ava-labs/libevm/metrics.(*meterArbiter).tick"), goleak.IgnoreTopFunction("github.com/syndtr/goleveldb/leveldb.(*DB).mpoolDrain"), } goleak.VerifyTestMain(m, opts...) diff --git a/core/mkalloc.go b/core/mkalloc.go index f481249c60..4fd247323e 100644 --- a/core/mkalloc.go +++ b/core/mkalloc.go @@ -43,8 +43,8 @@ import ( "strconv" "github.com/ava-labs/coreth/core" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/rlp" "golang.org/x/exp/slices" ) diff --git a/core/predicate_check.go b/core/predicate_check.go index 7e19253686..00671bcda6 100644 --- a/core/predicate_check.go +++ b/core/predicate_check.go @@ -12,8 +12,8 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/predicate" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) var ErrMissingPredicateContext = errors.New("missing predicate context") diff --git a/core/predicate_check_test.go b/core/predicate_check_test.go index 66808d977a..de942c1a70 100644 --- a/core/predicate_check_test.go +++ b/core/predicate_check_test.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/precompile/precompileconfig" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" ) diff --git a/core/rawdb/accessors_chain.go b/core/rawdb/accessors_chain.go index d63da4782a..dba05750a7 100644 --- a/core/rawdb/accessors_chain.go +++ b/core/rawdb/accessors_chain.go @@ -35,10 +35,10 @@ import ( "github.com/ava-labs/coreth/consensus/misc/eip4844" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" ) // ReadCanonicalHash retrieves the hash assigned to a canonical block number. diff --git a/core/rawdb/accessors_chain_test.go b/core/rawdb/accessors_chain_test.go index 1157eee792..3ec409066e 100644 --- a/core/rawdb/accessors_chain_test.go +++ b/core/rawdb/accessors_chain_test.go @@ -27,8 +27,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/rlp" "golang.org/x/crypto/sha3" ) diff --git a/core/rawdb/accessors_indexes.go b/core/rawdb/accessors_indexes.go index 511fa39d8f..afb50354c9 100644 --- a/core/rawdb/accessors_indexes.go +++ b/core/rawdb/accessors_indexes.go @@ -32,10 +32,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" ) // ReadTxLookupEntry retrieves the positional metadata associated with a transaction diff --git a/core/rawdb/accessors_indexes_test.go b/core/rawdb/accessors_indexes_test.go index 1930d81e91..e4fac23e75 100644 --- a/core/rawdb/accessors_indexes_test.go +++ b/core/rawdb/accessors_indexes_test.go @@ -23,9 +23,9 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/internal/blocktest" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/rlp" ) var newTestHasher = blocktest.NewHasher diff --git a/core/rawdb/accessors_metadata.go b/core/rawdb/accessors_metadata.go index c6ad7645a3..3bfe634a12 100644 --- a/core/rawdb/accessors_metadata.go +++ b/core/rawdb/accessors_metadata.go @@ -31,10 +31,10 @@ import ( "time" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" ) // ReadDatabaseVersion retrieves the version number of the database. diff --git a/core/rawdb/accessors_snapshot.go b/core/rawdb/accessors_snapshot.go index 06a136ba89..f091b63831 100644 --- a/core/rawdb/accessors_snapshot.go +++ b/core/rawdb/accessors_snapshot.go @@ -27,9 +27,9 @@ package rawdb import ( - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" ) // ReadSnapshotRoot retrieves the root of the block whose state is contained in diff --git a/core/rawdb/accessors_state.go b/core/rawdb/accessors_state.go index 03cbf44b6c..509dfba818 100644 --- a/core/rawdb/accessors_state.go +++ b/core/rawdb/accessors_state.go @@ -29,9 +29,9 @@ package rawdb import ( "encoding/binary" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" ) // ReadPreimage retrieves a single preimage of the provided hash. diff --git a/core/rawdb/accessors_state_sync.go b/core/rawdb/accessors_state_sync.go index 36ba9ef1bd..0781a8c142 100644 --- a/core/rawdb/accessors_state_sync.go +++ b/core/rawdb/accessors_state_sync.go @@ -7,9 +7,9 @@ import ( "encoding/binary" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" ) // ReadSyncRoot reads the root corresponding to the main trie of an in-progress diff --git a/core/rawdb/accessors_state_sync_test.go b/core/rawdb/accessors_state_sync_test.go index 5c51eb7bf3..506e843c8b 100644 --- a/core/rawdb/accessors_state_sync_test.go +++ b/core/rawdb/accessors_state_sync_test.go @@ -6,7 +6,7 @@ package rawdb import ( "testing" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/require" ) diff --git a/core/rawdb/accessors_trie.go b/core/rawdb/accessors_trie.go index e148a4280b..742a462c7c 100644 --- a/core/rawdb/accessors_trie.go +++ b/core/rawdb/accessors_trie.go @@ -30,10 +30,10 @@ import ( "fmt" "sync" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" "golang.org/x/crypto/sha3" ) diff --git a/core/rawdb/chain_iterator.go b/core/rawdb/chain_iterator.go index 5f449e4b6c..f4c79fd0b4 100644 --- a/core/rawdb/chain_iterator.go +++ b/core/rawdb/chain_iterator.go @@ -32,11 +32,11 @@ import ( "time" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/prque" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/prque" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" ) type blockTxHashes struct { diff --git a/core/rawdb/chain_iterator_test.go b/core/rawdb/chain_iterator_test.go index 0e4e762789..2086fa72b5 100644 --- a/core/rawdb/chain_iterator_test.go +++ b/core/rawdb/chain_iterator_test.go @@ -34,7 +34,7 @@ import ( "testing" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) func TestChainIterator(t *testing.T) { diff --git a/core/rawdb/database.go b/core/rawdb/database.go index 75922eba5d..1bf30508c5 100644 --- a/core/rawdb/database.go +++ b/core/rawdb/database.go @@ -33,12 +33,12 @@ import ( "path/filepath" "time" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethdb/leveldb" - "github.com/ethereum/go-ethereum/ethdb/memorydb" - "github.com/ethereum/go-ethereum/ethdb/pebble" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/ethdb/leveldb" + "github.com/ava-labs/libevm/ethdb/memorydb" + "github.com/ava-labs/libevm/ethdb/pebble" + "github.com/ava-labs/libevm/log" "github.com/olekukonko/tablewriter" ) diff --git a/core/rawdb/key_length_iterator.go b/core/rawdb/key_length_iterator.go index fe95d719f0..8d1a7d2f54 100644 --- a/core/rawdb/key_length_iterator.go +++ b/core/rawdb/key_length_iterator.go @@ -26,7 +26,7 @@ package rawdb -import "github.com/ethereum/go-ethereum/ethdb" +import "github.com/ava-labs/libevm/ethdb" // KeyLengthIterator is a wrapper for a database iterator that ensures only key-value pairs // with a specific key length will be returned. diff --git a/core/rawdb/schema.go b/core/rawdb/schema.go index 53fe9ac15f..6fa4741a2e 100644 --- a/core/rawdb/schema.go +++ b/core/rawdb/schema.go @@ -32,9 +32,9 @@ import ( "encoding/binary" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/metrics" ) // The fields below define the low level database schema prefixing. diff --git a/core/rawdb/table.go b/core/rawdb/table.go index 5dc709080c..cb9156173a 100644 --- a/core/rawdb/table.go +++ b/core/rawdb/table.go @@ -27,7 +27,7 @@ package rawdb import ( - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/ethdb" ) // table is a wrapper around a database that prefixes each key access with a pre- diff --git a/core/rawdb/table_test.go b/core/rawdb/table_test.go index 9cb913c2a1..a6f4b454f6 100644 --- a/core/rawdb/table_test.go +++ b/core/rawdb/table_test.go @@ -30,7 +30,7 @@ import ( "bytes" "testing" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/ethdb" ) func TestTableDatabase(t *testing.T) { testTableDatabase(t, "prefix") } diff --git a/core/rlp_test.go b/core/rlp_test.go index d6a36ef6b1..f43f487aab 100644 --- a/core/rlp_test.go +++ b/core/rlp_test.go @@ -34,9 +34,9 @@ import ( "github.com/ava-labs/coreth/consensus/dummy" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/rlp" "golang.org/x/crypto/sha3" ) diff --git a/core/state/database.go b/core/state/database.go index 60f971fda7..b810bf2c3d 100644 --- a/core/state/database.go +++ b/core/state/database.go @@ -31,15 +31,15 @@ import ( "fmt" "github.com/ava-labs/coreth/core/rawdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/lru" + ethstate "github.com/ava-labs/libevm/core/state" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/trie/utils" + "github.com/ava-labs/libevm/triedb" "github.com/crate-crypto/go-ipa/banderwagon" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/lru" - ethstate "github.com/ethereum/go-ethereum/core/state" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/trie/utils" - "github.com/ethereum/go-ethereum/triedb" ) const ( diff --git a/core/state/dump.go b/core/state/dump.go index c3c6dde9d9..deac606017 100644 --- a/core/state/dump.go +++ b/core/state/dump.go @@ -27,7 +27,7 @@ package state import ( - ethstate "github.com/ethereum/go-ethereum/core/state" + ethstate "github.com/ava-labs/libevm/core/state" ) type ( diff --git a/core/state/pruner/bloom.go b/core/state/pruner/bloom.go index b7f673b80d..a228b84f8f 100644 --- a/core/state/pruner/bloom.go +++ b/core/state/pruner/bloom.go @@ -32,8 +32,8 @@ import ( "os" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" bloomfilter "github.com/holiman/bloomfilter/v2" ) diff --git a/core/state/pruner/pruner.go b/core/state/pruner/pruner.go index a5940752f2..a71ba5601b 100644 --- a/core/state/pruner/pruner.go +++ b/core/state/pruner/pruner.go @@ -40,12 +40,12 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/triedb" ) const ( diff --git a/core/state/snapshot/context.go b/core/state/snapshot/context.go index 35b22c6ea3..45acfbba29 100644 --- a/core/state/snapshot/context.go +++ b/core/state/snapshot/context.go @@ -34,8 +34,8 @@ import ( "golang.org/x/exp/slog" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) // generatorStats is a collection of statistics gathered by the snapshot generator diff --git a/core/state/snapshot/conversion.go b/core/state/snapshot/conversion.go index 350036d88f..ea2b8f7c79 100644 --- a/core/state/snapshot/conversion.go +++ b/core/state/snapshot/conversion.go @@ -37,11 +37,11 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie" ) // trieKV represents a trie key-value pair diff --git a/core/state/snapshot/difflayer.go b/core/state/snapshot/difflayer.go index d8d3b750e2..0e3b38d509 100644 --- a/core/state/snapshot/difflayer.go +++ b/core/state/snapshot/difflayer.go @@ -36,8 +36,8 @@ import ( "time" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/rlp" bloomfilter "github.com/holiman/bloomfilter/v2" "golang.org/x/exp/slices" ) diff --git a/core/state/snapshot/difflayer_test.go b/core/state/snapshot/difflayer_test.go index 24fc3fdc69..85e774fdec 100644 --- a/core/state/snapshot/difflayer_test.go +++ b/core/state/snapshot/difflayer_test.go @@ -33,9 +33,9 @@ import ( "testing" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb/memorydb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/ethdb/memorydb" ) func copyDestructs(destructs map[common.Hash]struct{}) map[common.Hash]struct{} { diff --git a/core/state/snapshot/disklayer.go b/core/state/snapshot/disklayer.go index 9a8ae65943..87fc3f4e2f 100644 --- a/core/state/snapshot/disklayer.go +++ b/core/state/snapshot/disklayer.go @@ -34,10 +34,10 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/triedb" ) // diskLayer is a low level persistent snapshot built on top of a key-value store. diff --git a/core/state/snapshot/disklayer_test.go b/core/state/snapshot/disklayer_test.go index 6094e32fee..1f76dbf1e0 100644 --- a/core/state/snapshot/disklayer_test.go +++ b/core/state/snapshot/disklayer_test.go @@ -31,9 +31,9 @@ import ( "testing" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb/memorydb" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb/memorydb" + "github.com/ava-labs/libevm/rlp" ) // reverse reverses the contents of a byte slice. It's used to update random accs diff --git a/core/state/snapshot/generate.go b/core/state/snapshot/generate.go index 21e47b8682..1021cd1ed6 100644 --- a/core/state/snapshot/generate.go +++ b/core/state/snapshot/generate.go @@ -34,12 +34,12 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/triedb" ) const ( diff --git a/core/state/snapshot/generate_test.go b/core/state/snapshot/generate_test.go index 66044c3f17..fe1b33f17b 100644 --- a/core/state/snapshot/generate_test.go +++ b/core/state/snapshot/generate_test.go @@ -36,13 +36,13 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/triedb/hashdb" "github.com/ava-labs/coreth/triedb/pathdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/trie/trienode" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/trie/trienode" + "github.com/ava-labs/libevm/triedb" "github.com/holiman/uint256" "golang.org/x/crypto/sha3" ) diff --git a/core/state/snapshot/iterator.go b/core/state/snapshot/iterator.go index 746a69a1bc..addae92deb 100644 --- a/core/state/snapshot/iterator.go +++ b/core/state/snapshot/iterator.go @@ -32,9 +32,9 @@ import ( "sort" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" - ethsnapshot "github.com/ethereum/go-ethereum/core/state/snapshot" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + ethsnapshot "github.com/ava-labs/libevm/core/state/snapshot" + "github.com/ava-labs/libevm/ethdb" ) // Iterator is an iterator to step over all the accounts or the specific diff --git a/core/state/snapshot/iterator_binary.go b/core/state/snapshot/iterator_binary.go index cff012402c..68f95901f7 100644 --- a/core/state/snapshot/iterator_binary.go +++ b/core/state/snapshot/iterator_binary.go @@ -29,7 +29,7 @@ package snapshot import ( "bytes" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // binaryIterator is a simplistic iterator to step over the accounts or storage diff --git a/core/state/snapshot/iterator_fast.go b/core/state/snapshot/iterator_fast.go index 4e324ee28b..d8dda5f71c 100644 --- a/core/state/snapshot/iterator_fast.go +++ b/core/state/snapshot/iterator_fast.go @@ -31,7 +31,7 @@ import ( "fmt" "sort" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "golang.org/x/exp/slices" ) diff --git a/core/state/snapshot/iterator_test.go b/core/state/snapshot/iterator_test.go index d7b7e56cb3..b2862407b2 100644 --- a/core/state/snapshot/iterator_test.go +++ b/core/state/snapshot/iterator_test.go @@ -35,7 +35,7 @@ import ( "testing" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // TestAccountIteratorBasics tests some simple single-layer(diff and disk) iteration diff --git a/core/state/snapshot/journal.go b/core/state/snapshot/journal.go index b1d6c338b3..f793ffb832 100644 --- a/core/state/snapshot/journal.go +++ b/core/state/snapshot/journal.go @@ -33,11 +33,11 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/triedb" ) // journalGenerator is a disk layer entry containing the generator progress marker. diff --git a/core/state/snapshot/snapshot.go b/core/state/snapshot/snapshot.go index c05f590d82..917bbf368c 100644 --- a/core/state/snapshot/snapshot.go +++ b/core/state/snapshot/snapshot.go @@ -35,13 +35,13 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ava-labs/coreth/metrics" - "github.com/ethereum/go-ethereum/common" - ethsnapshot "github.com/ethereum/go-ethereum/core/state/snapshot" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/libevm/stateconf" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + ethsnapshot "github.com/ava-labs/libevm/core/state/snapshot" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/libevm/stateconf" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/metrics" + "github.com/ava-labs/libevm/triedb" ) const ( diff --git a/core/state/snapshot/snapshot_ext.go b/core/state/snapshot/snapshot_ext.go index 3566d7ed54..8b73f83fcc 100644 --- a/core/state/snapshot/snapshot_ext.go +++ b/core/state/snapshot/snapshot_ext.go @@ -4,8 +4,8 @@ import ( "time" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" ) func (t *Tree) DiskAccountIterator(seek common.Hash) AccountIterator { diff --git a/core/state/snapshot/snapshot_test.go b/core/state/snapshot/snapshot_test.go index 91a59d48c3..cc98830e13 100644 --- a/core/state/snapshot/snapshot_test.go +++ b/core/state/snapshot/snapshot_test.go @@ -35,8 +35,8 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/rlp" "github.com/holiman/uint256" ) diff --git a/core/state/snapshot/utils.go b/core/state/snapshot/utils.go index f9e2db5ad6..4a31a25a76 100644 --- a/core/state/snapshot/utils.go +++ b/core/state/snapshot/utils.go @@ -32,9 +32,9 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" ) // CheckDanglingStorage iterates the snap storage data, and verifies that all diff --git a/core/state/snapshot/wipe.go b/core/state/snapshot/wipe.go index 37963032e6..c5dffd648e 100644 --- a/core/state/snapshot/wipe.go +++ b/core/state/snapshot/wipe.go @@ -31,9 +31,9 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" ) // WipeSnapshot starts a goroutine to iterate over the entire key-value database diff --git a/core/state/snapshot/wipe_test.go b/core/state/snapshot/wipe_test.go index 74afec5fce..5fc6110bd0 100644 --- a/core/state/snapshot/wipe_test.go +++ b/core/state/snapshot/wipe_test.go @@ -31,8 +31,8 @@ import ( "testing" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb/memorydb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb/memorydb" ) // Tests that given a database with random data content, all parts of a snapshot diff --git a/core/state/state_object_test.go b/core/state/state_object_test.go index 96132277fe..f5f59acb2f 100644 --- a/core/state/state_object_test.go +++ b/core/state/state_object_test.go @@ -7,7 +7,7 @@ import ( "bytes" "testing" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) func TestStateObjectPartition(t *testing.T) { diff --git a/core/state/state_test.go b/core/state/state_test.go index 791e854e5e..1b9484514b 100644 --- a/core/state/state_test.go +++ b/core/state/state_test.go @@ -27,15 +27,12 @@ package state import ( - "bytes" "testing" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/libevm/common" - "github.com/ava-labs/libevm/crypto" "github.com/ava-labs/libevm/ethdb" - "github.com/holiman/uint256" ) type stateEnv struct { @@ -106,102 +103,3 @@ func TestSnapshotEmpty(t *testing.T) { s := newStateEnv() s.state.RevertToSnapshot(s.state.Snapshot()) } - -func TestSnapshot2(t *testing.T) { - state, _ := New(types.EmptyRootHash, NewDatabase(rawdb.NewMemoryDatabase()), nil) - - stateobjaddr0 := common.BytesToAddress([]byte("so0")) - stateobjaddr1 := common.BytesToAddress([]byte("so1")) - var storageaddr common.Hash - - data0 := common.BytesToHash([]byte{17}) - data1 := common.BytesToHash([]byte{18}) - - state.SetState(stateobjaddr0, storageaddr, data0) - state.SetState(stateobjaddr1, storageaddr, data1) - - // db, trie are already non-empty values - so0 := state.getStateObject(stateobjaddr0) - so0.SetBalance(uint256.NewInt(42)) - so0.SetNonce(43) - so0.SetCode(crypto.Keccak256Hash([]byte{'c', 'a', 'f', 'e'}), []byte{'c', 'a', 'f', 'e'}) - so0.selfDestructed = false - so0.deleted = false - state.setStateObject(so0) - - root, _ := state.Commit(0, false) - state, _ = New(root, state.db, nil) - - // and one with deleted == true - so1 := state.getStateObject(stateobjaddr1) - so1.SetBalance(uint256.NewInt(52)) - so1.SetNonce(53) - so1.SetCode(crypto.Keccak256Hash([]byte{'c', 'a', 'f', 'e', '2'}), []byte{'c', 'a', 'f', 'e', '2'}) - so1.selfDestructed = true - so1.deleted = true - state.setStateObject(so1) - - so1 = state.getStateObject(stateobjaddr1) - if so1 != nil { - t.Fatalf("deleted object not nil when getting") - } - - snapshot := state.Snapshot() - state.RevertToSnapshot(snapshot) - - so0Restored := state.getStateObject(stateobjaddr0) - // Update lazily-loaded values before comparing. - so0Restored.GetState(storageaddr) - so0Restored.Code() - // non-deleted is equal (restored) - compareStateObjects(so0Restored, so0, t) - - // deleted should be nil, both before and after restore of state copy - so1Restored := state.getStateObject(stateobjaddr1) - if so1Restored != nil { - t.Fatalf("deleted object not nil after restoring snapshot: %+v", so1Restored) - } -} - -func compareStateObjects(so0, so1 *stateObject, t *testing.T) { - if so0.Address() != so1.Address() { - t.Fatalf("Address mismatch: have %v, want %v", so0.address, so1.address) - } - if so0.Balance().Cmp(so1.Balance()) != 0 { - t.Fatalf("Balance mismatch: have %v, want %v", so0.Balance(), so1.Balance()) - } - if so0.Nonce() != so1.Nonce() { - t.Fatalf("Nonce mismatch: have %v, want %v", so0.Nonce(), so1.Nonce()) - } - if so0.data.Root != so1.data.Root { - t.Errorf("Root mismatch: have %x, want %x", so0.data.Root[:], so1.data.Root[:]) - } - if !bytes.Equal(so0.CodeHash(), so1.CodeHash()) { - t.Fatalf("CodeHash mismatch: have %v, want %v", so0.CodeHash(), so1.CodeHash()) - } - if !bytes.Equal(so0.code, so1.code) { - t.Fatalf("Code mismatch: have %v, want %v", so0.code, so1.code) - } - - if len(so1.dirtyStorage) != len(so0.dirtyStorage) { - t.Errorf("Dirty storage size mismatch: have %d, want %d", len(so1.dirtyStorage), len(so0.dirtyStorage)) - } - for k, v := range so1.dirtyStorage { - if so0.dirtyStorage[k] != v { - t.Errorf("Dirty storage key %x mismatch: have %v, want %v", k, so0.dirtyStorage[k], v) - } - } - for k, v := range so0.dirtyStorage { - if so1.dirtyStorage[k] != v { - t.Errorf("Dirty storage key %x mismatch: have %v, want none.", k, v) - } - } - if len(so1.originStorage) != len(so0.originStorage) { - t.Errorf("Origin storage size mismatch: have %d, want %d", len(so1.originStorage), len(so0.originStorage)) - } - for k, v := range so1.originStorage { - if so0.originStorage[k] != v { - t.Errorf("Origin storage key %x mismatch: have %v, want %v", k, so0.originStorage[k], v) - } - } -} diff --git a/core/state/statedb_multicoin_test.go b/core/state/statedb_multicoin_test.go index a653d9f334..95cc98ef71 100644 --- a/core/state/statedb_multicoin_test.go +++ b/core/state/statedb_multicoin_test.go @@ -10,8 +10,8 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" "github.com/holiman/uint256" ) diff --git a/core/state_manager.go b/core/state_manager.go index 59447055b7..30b20be86a 100644 --- a/core/state_manager.go +++ b/core/state_manager.go @@ -32,8 +32,8 @@ import ( "time" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" ) func init() { diff --git a/core/state_manager_test.go b/core/state_manager_test.go index cddb0a6dd8..ea91e0d113 100644 --- a/core/state_manager_test.go +++ b/core/state_manager_test.go @@ -9,7 +9,7 @@ import ( "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/assert" ) diff --git a/core/state_processor.go b/core/state_processor.go index 67e59d9cf5..563485f67e 100644 --- a/core/state_processor.go +++ b/core/state_processor.go @@ -34,10 +34,10 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/log" ) // StateProcessor is a basic Processor, which takes care of transitioning diff --git a/core/state_processor_ext.go b/core/state_processor_ext.go index db17b15028..e1d6ef43b9 100644 --- a/core/state_processor_ext.go +++ b/core/state_processor_ext.go @@ -11,7 +11,7 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/precompile/contract" "github.com/ava-labs/coreth/precompile/modules" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" ) // ApplyPrecompileActivations checks if any of the precompiles specified by the chain config are enabled or disabled by the block diff --git a/core/state_processor_test.go b/core/state_processor_test.go index a3fcacd0b4..f496935b38 100644 --- a/core/state_processor_test.go +++ b/core/state_processor_test.go @@ -40,10 +40,10 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/trie" "github.com/holiman/uint256" "golang.org/x/crypto/sha3" ) @@ -374,7 +374,7 @@ func GenerateBadBlock(parent *types.Block, engine consensus.Engine, txs types.Tr } header.Extra, _ = dummy.CalcExtraPrefix(config, parent.Header(), header.Time) header.BaseFee, _ = dummy.CalcBaseFee(config, parent.Header(), header.Time) - if config.IsApricotPhase4(header.Time) { + if params.GetExtra(config).IsApricotPhase4(header.Time) { header.BlockGasCost = big.NewInt(0) header.ExtDataGasUsed = big.NewInt(0) } diff --git a/core/state_transition.go b/core/state_transition.go index c7a3186d81..099692b9ce 100644 --- a/core/state_transition.go +++ b/core/state_transition.go @@ -35,10 +35,10 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/utils" "github.com/ava-labs/coreth/vmerrs" - "github.com/ethereum/go-ethereum/common" - cmath "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto/kzg4844" + "github.com/ava-labs/libevm/common" + cmath "github.com/ava-labs/libevm/common/math" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto/kzg4844" "github.com/holiman/uint256" ) diff --git a/core/state_transition_test.go b/core/state_transition_test.go index 28a37acdaf..0db4bcf578 100644 --- a/core/state_transition_test.go +++ b/core/state_transition_test.go @@ -37,10 +37,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/nativeasset" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - ethCrypto "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + ethCrypto "github.com/ava-labs/libevm/crypto" "github.com/stretchr/testify/require" ) diff --git a/core/test_blockchain.go b/core/test_blockchain.go index f59ce2981b..3960a10f5f 100644 --- a/core/test_blockchain.go +++ b/core/test_blockchain.go @@ -15,9 +15,9 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/ethdb" "github.com/holiman/uint256" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/core/txindexer.go b/core/txindexer.go index 39c5fe51b0..4dc963b94c 100644 --- a/core/txindexer.go +++ b/core/txindexer.go @@ -21,8 +21,8 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" ) // TxIndexProgress is the struct describing the progress for transaction indexing. diff --git a/core/txindexer_test.go b/core/txindexer_test.go index 5c212bc953..b1bbdc83db 100644 --- a/core/txindexer_test.go +++ b/core/txindexer_test.go @@ -25,9 +25,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/ethdb" "github.com/stretchr/testify/require" ) diff --git a/core/txpool/blobpool/blobpool.go b/core/txpool/blobpool/blobpool.go index 3a4b4cd156..5c945b0a4a 100644 --- a/core/txpool/blobpool/blobpool.go +++ b/core/txpool/blobpool/blobpool.go @@ -46,11 +46,11 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/event" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/metrics" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/event" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/metrics" + "github.com/ava-labs/libevm/rlp" "github.com/holiman/billy" "github.com/holiman/uint256" ) diff --git a/core/txpool/blobpool/blobpool_test.go b/core/txpool/blobpool/blobpool_test.go index 32bdd8eb54..b1958a29b9 100644 --- a/core/txpool/blobpool/blobpool_test.go +++ b/core/txpool/blobpool/blobpool_test.go @@ -47,12 +47,12 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/crypto/kzg4844" - "github.com/ethereum/go-ethereum/ethdb/memorydb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/crypto/kzg4844" + "github.com/ava-labs/libevm/ethdb/memorydb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" "github.com/holiman/billy" "github.com/holiman/uint256" ) diff --git a/core/txpool/blobpool/config.go b/core/txpool/blobpool/config.go index 5df7885fb3..d7b94535a7 100644 --- a/core/txpool/blobpool/config.go +++ b/core/txpool/blobpool/config.go @@ -27,7 +27,7 @@ package blobpool import ( - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" ) // Config are the configuration parameters of the blob transaction pool. diff --git a/core/txpool/blobpool/evictheap.go b/core/txpool/blobpool/evictheap.go index 0824ddf735..7c7525371c 100644 --- a/core/txpool/blobpool/evictheap.go +++ b/core/txpool/blobpool/evictheap.go @@ -32,7 +32,7 @@ import ( "math" "sort" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/holiman/uint256" ) diff --git a/core/txpool/blobpool/evictheap_test.go b/core/txpool/blobpool/evictheap_test.go index 69b02447bf..70bd772b5d 100644 --- a/core/txpool/blobpool/evictheap_test.go +++ b/core/txpool/blobpool/evictheap_test.go @@ -32,7 +32,7 @@ import ( "testing" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/holiman/uint256" ) diff --git a/core/txpool/blobpool/interface.go b/core/txpool/blobpool/interface.go index c544efa872..d25250e887 100644 --- a/core/txpool/blobpool/interface.go +++ b/core/txpool/blobpool/interface.go @@ -30,7 +30,7 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // BlockChain defines the minimal set of methods needed to back a blob pool with diff --git a/core/txpool/blobpool/limbo.go b/core/txpool/blobpool/limbo.go index 63f31031ab..541b1309e8 100644 --- a/core/txpool/blobpool/limbo.go +++ b/core/txpool/blobpool/limbo.go @@ -30,9 +30,9 @@ import ( "errors" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" "github.com/holiman/billy" ) diff --git a/core/txpool/blobpool/metrics.go b/core/txpool/blobpool/metrics.go index 0192e897aa..ccd4dbb574 100644 --- a/core/txpool/blobpool/metrics.go +++ b/core/txpool/blobpool/metrics.go @@ -26,7 +26,7 @@ package blobpool -import "github.com/ethereum/go-ethereum/metrics" +import "github.com/ava-labs/libevm/metrics" var ( // datacapGauge tracks the user's configured capacity for the blob pool. It diff --git a/core/txpool/legacypool/journal.go b/core/txpool/legacypool/journal.go index c586cab543..f29d4f2855 100644 --- a/core/txpool/legacypool/journal.go +++ b/core/txpool/legacypool/journal.go @@ -33,9 +33,9 @@ import ( "os" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" ) // errNoActiveJournal is returned if a transaction is attempted to be inserted diff --git a/core/txpool/legacypool/legacypool.go b/core/txpool/legacypool/legacypool.go index 298018ece7..e25ed902f2 100644 --- a/core/txpool/legacypool/legacypool.go +++ b/core/txpool/legacypool/legacypool.go @@ -43,11 +43,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/prque" - "github.com/ethereum/go-ethereum/event" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/prque" + "github.com/ava-labs/libevm/event" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/metrics" "github.com/holiman/uint256" ) diff --git a/core/txpool/legacypool/legacypool2_test.go b/core/txpool/legacypool/legacypool2_test.go index 566cfc820e..dd10a4ab46 100644 --- a/core/txpool/legacypool/legacypool2_test.go +++ b/core/txpool/legacypool/legacypool2_test.go @@ -33,9 +33,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/event" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/event" "github.com/holiman/uint256" ) diff --git a/core/txpool/legacypool/legacypool_test.go b/core/txpool/legacypool/legacypool_test.go index d62310cd40..a193510b2d 100644 --- a/core/txpool/legacypool/legacypool_test.go +++ b/core/txpool/legacypool/legacypool_test.go @@ -45,10 +45,10 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/event" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/event" + "github.com/ava-labs/libevm/trie" "github.com/holiman/uint256" ) diff --git a/core/txpool/legacypool/list.go b/core/txpool/legacypool/list.go index 0b523c3795..be458113b2 100644 --- a/core/txpool/legacypool/list.go +++ b/core/txpool/legacypool/list.go @@ -36,7 +36,7 @@ import ( "time" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/holiman/uint256" "golang.org/x/exp/slices" ) diff --git a/core/txpool/legacypool/list_test.go b/core/txpool/legacypool/list_test.go index 116e80a707..d94dc5c683 100644 --- a/core/txpool/legacypool/list_test.go +++ b/core/txpool/legacypool/list_test.go @@ -32,8 +32,8 @@ import ( "testing" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" "github.com/holiman/uint256" ) diff --git a/core/txpool/legacypool/noncer.go b/core/txpool/legacypool/noncer.go index dd880a6ba3..425748d6f1 100644 --- a/core/txpool/legacypool/noncer.go +++ b/core/txpool/legacypool/noncer.go @@ -30,7 +30,7 @@ import ( "sync" "github.com/ava-labs/coreth/core/state" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // noncer is a tiny virtual state database to manage the executable nonces of diff --git a/core/txpool/subpool.go b/core/txpool/subpool.go index 4ebbf97c4f..9059556094 100644 --- a/core/txpool/subpool.go +++ b/core/txpool/subpool.go @@ -32,8 +32,8 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/event" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/event" "github.com/holiman/uint256" ) diff --git a/core/txpool/txpool.go b/core/txpool/txpool.go index 71b6ad3c96..de7ed76955 100644 --- a/core/txpool/txpool.go +++ b/core/txpool/txpool.go @@ -35,10 +35,10 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/event" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/event" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/metrics" ) var ( diff --git a/core/txpool/validation.go b/core/txpool/validation.go index 08206a7e6f..fad1d39ad3 100644 --- a/core/txpool/validation.go +++ b/core/txpool/validation.go @@ -36,9 +36,9 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/vmerrs" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto/kzg4844" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto/kzg4844" + "github.com/ava-labs/libevm/log" ) var ( diff --git a/core/types.go b/core/types.go index e5e2e44774..6339d7578b 100644 --- a/core/types.go +++ b/core/types.go @@ -29,7 +29,7 @@ package core import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/core/vm" + "github.com/ava-labs/libevm/core/vm" ) // Validator is an interface which defines the standard for block validation. It diff --git a/core/types/account.go b/core/types/account.go index bb0f4ca02e..efc0927770 100644 --- a/core/types/account.go +++ b/core/types/account.go @@ -23,9 +23,9 @@ import ( "fmt" "math/big" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/common/math" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/common/math" ) //go:generate go run github.com/fjl/gencodec -type Account -field-override accountMarshaling -out gen_account.go diff --git a/core/types/block.go b/core/types/block.go index 1be71c96d1..b47048fa62 100644 --- a/core/types/block.go +++ b/core/types/block.go @@ -34,9 +34,9 @@ import ( "reflect" "sync/atomic" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/rlp" ) // A BlockNonce is a 64-bit hash which proves (combined with the diff --git a/core/types/block_ext.go b/core/types/block_ext.go index 5ebb7aeb31..c186e5d241 100644 --- a/core/types/block_ext.go +++ b/core/types/block_ext.go @@ -6,7 +6,7 @@ package types import ( "math/big" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) func (b *Block) WithExtData(version uint32, extdata *[]byte) *Block { diff --git a/core/types/block_test.go b/core/types/block_test.go index fb6b045aa6..75bb428853 100644 --- a/core/types/block_test.go +++ b/core/types/block_test.go @@ -33,11 +33,11 @@ import ( "testing" "github.com/ava-labs/coreth/internal/blocktest" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/params" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/math" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/params" + "github.com/ava-labs/libevm/rlp" ) // This test has been modified from https://github.com/ethereum/go-ethereum/blob/v1.9.21/core/types/block_test.go#L35 to fit diff --git a/core/types/gen_account.go b/core/types/gen_account.go index 4e475896a7..c3c7fb3fdf 100644 --- a/core/types/gen_account.go +++ b/core/types/gen_account.go @@ -7,9 +7,9 @@ import ( "errors" "math/big" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/common/math" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/common/math" ) var _ = (*accountMarshaling)(nil) diff --git a/core/types/gen_header_json.go b/core/types/gen_header_json.go index 632a6ed48e..0c1f588944 100644 --- a/core/types/gen_header_json.go +++ b/core/types/gen_header_json.go @@ -7,8 +7,8 @@ import ( "errors" "math/big" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" ) var _ = (*headerMarshaling)(nil) diff --git a/core/types/gen_header_rlp.go b/core/types/gen_header_rlp.go index 711a33b8ca..e7c98e851f 100644 --- a/core/types/gen_header_rlp.go +++ b/core/types/gen_header_rlp.go @@ -2,7 +2,7 @@ package types -import "github.com/ethereum/go-ethereum/rlp" +import "github.com/ava-labs/libevm/rlp" import "io" func (obj *Header) EncodeRLP(_w io.Writer) error { diff --git a/core/types/hashes.go b/core/types/hashes.go index 3d8a8a013b..2a5ed05aa5 100644 --- a/core/types/hashes.go +++ b/core/types/hashes.go @@ -27,9 +27,9 @@ package types import ( - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/log" ) var ( diff --git a/core/types/hashing.go b/core/types/hashing.go index c7e03a2b03..b6b631c7bc 100644 --- a/core/types/hashing.go +++ b/core/types/hashing.go @@ -30,9 +30,9 @@ import ( "bytes" "sync" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/rlp" "golang.org/x/crypto/sha3" ) diff --git a/core/types/hashing_test.go b/core/types/hashing_test.go index a56c5f4941..94dd5631d2 100644 --- a/core/types/hashing_test.go +++ b/core/types/hashing_test.go @@ -36,12 +36,12 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/triedb" ) func TestDeriveSha(t *testing.T) { diff --git a/core/types/header_ext.go b/core/types/header_ext.go index 0a61055b6d..e680ee7798 100644 --- a/core/types/header_ext.go +++ b/core/types/header_ext.go @@ -6,8 +6,8 @@ package types import ( "io" - ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/rlp" + ethtypes "github.com/ava-labs/libevm/core/types" + "github.com/ava-labs/libevm/rlp" ) // HeaderExtra is a struct that contains extra fields used by Avalanche diff --git a/core/types/imports.go b/core/types/imports.go index b1761a4f16..e286bc9b4c 100644 --- a/core/types/imports.go +++ b/core/types/imports.go @@ -4,7 +4,7 @@ package types import ( - ethtypes "github.com/ethereum/go-ethereum/core/types" + ethtypes "github.com/ava-labs/libevm/core/types" ) // The following types are used directly as their upstream definitions. diff --git a/core/types/log.go b/core/types/log.go index 600415d979..5ddb090034 100644 --- a/core/types/log.go +++ b/core/types/log.go @@ -26,7 +26,7 @@ package types -import ethtypes "github.com/ethereum/go-ethereum/core/types" +import ethtypes "github.com/ava-labs/libevm/core/types" // Log represents a contract log event. These events are generated by the LOG opcode and // stored/indexed by the node. diff --git a/core/types/rlp_fuzzer_test.go b/core/types/rlp_fuzzer_test.go index a3b9f72436..4e3645874a 100644 --- a/core/types/rlp_fuzzer_test.go +++ b/core/types/rlp_fuzzer_test.go @@ -22,7 +22,7 @@ import ( "math/big" "testing" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/rlp" "github.com/holiman/uint256" ) diff --git a/core/types/state_account.go b/core/types/state_account.go index 9d4299d7fe..0c3cb7ab8d 100644 --- a/core/types/state_account.go +++ b/core/types/state_account.go @@ -27,7 +27,7 @@ package types import ( - ethtypes "github.com/ethereum/go-ethereum/core/types" + ethtypes "github.com/ava-labs/libevm/core/types" ) type ( diff --git a/core/types/types_test.go b/core/types/types_test.go index 7b68db9b4b..7620aafb7f 100644 --- a/core/types/types_test.go +++ b/core/types/types_test.go @@ -30,9 +30,9 @@ import ( "math/big" "testing" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/rlp" ) type devnull struct{ len int } diff --git a/core/vm/runtime/env.go b/core/vm/runtime/env.go index 8440a2cd61..a59d623b79 100644 --- a/core/vm/runtime/env.go +++ b/core/vm/runtime/env.go @@ -28,7 +28,7 @@ package runtime import ( "github.com/ava-labs/coreth/core" - "github.com/ethereum/go-ethereum/core/vm" + "github.com/ava-labs/libevm/core/vm" ) func NewEnv(cfg *Config) *vm.EVM { diff --git a/core/vm/runtime/runtime.go b/core/vm/runtime/runtime.go index 89bd4f194c..c66342e918 100644 --- a/core/vm/runtime/runtime.go +++ b/core/vm/runtime/runtime.go @@ -35,9 +35,9 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/params/extras" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" "github.com/holiman/uint256" ) diff --git a/core/vm/runtime/runtime_example_test.go b/core/vm/runtime/runtime_example_test.go index 9850e283be..82651d3f1d 100644 --- a/core/vm/runtime/runtime_example_test.go +++ b/core/vm/runtime/runtime_example_test.go @@ -30,7 +30,7 @@ import ( "fmt" "github.com/ava-labs/coreth/core/vm/runtime" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) func ExampleExecute() { diff --git a/core/vm/runtime/runtime_test.go b/core/vm/runtime/runtime_test.go index b0b72e6f54..bef1a5bd93 100644 --- a/core/vm/runtime/runtime_test.go +++ b/core/vm/runtime/runtime_test.go @@ -41,13 +41,13 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/eth/tracers" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/asm" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/eth/tracers/logger" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/asm" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/eth/tracers/logger" // force-load js tracers to trigger registration - _ "github.com/ethereum/go-ethereum/eth/tracers/js" + _ "github.com/ava-labs/libevm/eth/tracers/js" "github.com/holiman/uint256" ) diff --git a/eth/api.go b/eth/api.go index 5842cb5625..dbea129203 100644 --- a/eth/api.go +++ b/eth/api.go @@ -27,7 +27,7 @@ package eth import ( - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // EthereumAPI provides an API to access Ethereum full node-related information. diff --git a/eth/api_admin.go b/eth/api_admin.go index f8945c1d2d..1531af6427 100644 --- a/eth/api_admin.go +++ b/eth/api_admin.go @@ -36,7 +36,7 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/rlp" ) // AdminAPI is the collection of Ethereum full node related APIs for node diff --git a/eth/api_backend.go b/eth/api_backend.go index f8fd3aa550..629aaa9f5b 100644 --- a/eth/api_backend.go +++ b/eth/api_backend.go @@ -43,11 +43,11 @@ import ( "github.com/ava-labs/coreth/eth/tracers" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/event" + "github.com/ava-labs/libevm/accounts" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/event" ) var ErrUnfinalizedData = errors.New("cannot query unfinalized data") diff --git a/eth/api_backend_test.go b/eth/api_backend_test.go index e58fab0954..e8fc92b569 100644 --- a/eth/api_backend_test.go +++ b/eth/api_backend_test.go @@ -31,8 +31,8 @@ import ( "testing" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/rlp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/eth/api_debug.go b/eth/api_debug.go index 8e926c7ead..e5073e4f63 100644 --- a/eth/api_debug.go +++ b/eth/api_debug.go @@ -37,12 +37,12 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/internal/ethapi" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie" ) // DebugAPI is the collection of Ethereum full node APIs for debugging the diff --git a/eth/api_debug_test.go b/eth/api_debug_test.go index e6690bd81f..926e4de48d 100644 --- a/eth/api_debug_test.go +++ b/eth/api_debug_test.go @@ -36,13 +36,13 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/triedb" "github.com/holiman/uint256" "github.com/davecgh/go-spew/spew" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" "golang.org/x/exp/slices" ) diff --git a/eth/backend.go b/eth/backend.go index ea3dff8704..59ec5bd056 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -53,12 +53,12 @@ import ( "github.com/ava-labs/coreth/node" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/event" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/accounts" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/event" + "github.com/ava-labs/libevm/log" ) // Config contains the configuration options of the ETH protocol. diff --git a/eth/bloombits.go b/eth/bloombits.go index ecc0aaf157..2fddfc0707 100644 --- a/eth/bloombits.go +++ b/eth/bloombits.go @@ -30,7 +30,7 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common/bitutil" + "github.com/ava-labs/libevm/common/bitutil" ) const ( diff --git a/eth/ethconfig/config.go b/eth/ethconfig/config.go index f7697112ef..b358e9aef0 100644 --- a/eth/ethconfig/config.go +++ b/eth/ethconfig/config.go @@ -35,7 +35,7 @@ import ( "github.com/ava-labs/coreth/eth/gasprice" "github.com/ava-labs/coreth/miner" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // DefaultFullGPOConfig contains default gasprice oracle settings for full node. diff --git a/eth/filters/api.go b/eth/filters/api.go index fb8178ed63..1ed17ec6db 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -39,9 +39,9 @@ import ( "github.com/ava-labs/coreth/interfaces" "github.com/ava-labs/coreth/internal/ethapi" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/event" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/event" ) var ( diff --git a/eth/filters/api_test.go b/eth/filters/api_test.go index 72838b4d8c..5bb2d0a6cb 100644 --- a/eth/filters/api_test.go +++ b/eth/filters/api_test.go @@ -22,7 +22,7 @@ import ( "testing" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) func TestUnmarshalJSONNewFilterArgs(t *testing.T) { diff --git a/eth/filters/bench_test.go b/eth/filters/bench_test.go index 77f0567870..26a478235a 100644 --- a/eth/filters/bench_test.go +++ b/eth/filters/bench_test.go @@ -35,9 +35,9 @@ import ( "github.com/ava-labs/coreth/core/bloombits" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/bitutil" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/bitutil" + "github.com/ava-labs/libevm/ethdb" ) func BenchmarkBloomBits512(b *testing.B) { diff --git a/eth/filters/filter.go b/eth/filters/filter.go index 6b77ee68e1..f58db13a5c 100644 --- a/eth/filters/filter.go +++ b/eth/filters/filter.go @@ -35,7 +35,7 @@ import ( "github.com/ava-labs/coreth/core/bloombits" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // Filter can be used to retrieve and filter logs. diff --git a/eth/filters/filter_system.go b/eth/filters/filter_system.go index 6a312df2ee..425617b899 100644 --- a/eth/filters/filter_system.go +++ b/eth/filters/filter_system.go @@ -40,10 +40,10 @@ import ( "github.com/ava-labs/coreth/interfaces" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/event" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/event" + "github.com/ava-labs/libevm/log" ) // Config represents the configuration of the filter system. diff --git a/eth/filters/filter_system_test.go b/eth/filters/filter_system_test.go index 073049a256..ea180d0eed 100644 --- a/eth/filters/filter_system_test.go +++ b/eth/filters/filter_system_test.go @@ -46,9 +46,9 @@ import ( "github.com/ava-labs/coreth/internal/ethapi" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/event" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/event" "github.com/stretchr/testify/require" ) diff --git a/eth/filters/filter_test.go b/eth/filters/filter_test.go index b71360c62d..583f97ad8e 100644 --- a/eth/filters/filter_test.go +++ b/eth/filters/filter_test.go @@ -41,10 +41,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/triedb" "github.com/stretchr/testify/require" ) diff --git a/eth/gasestimator/gasestimator.go b/eth/gasestimator/gasestimator.go index fc8a669fd1..464904b5c4 100644 --- a/eth/gasestimator/gasestimator.go +++ b/eth/gasestimator/gasestimator.go @@ -38,9 +38,9 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/vmerrs" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/log" ) // Options are the contextual parameters to execute the requested call. diff --git a/eth/gasprice/fee_info_provider_test.go b/eth/gasprice/fee_info_provider_test.go index 182c3378ea..c157b3fc97 100644 --- a/eth/gasprice/fee_info_provider_test.go +++ b/eth/gasprice/fee_info_provider_test.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/require" ) diff --git a/eth/gasprice/feehistory.go b/eth/gasprice/feehistory.go index d86121c003..1a922797e9 100644 --- a/eth/gasprice/feehistory.go +++ b/eth/gasprice/feehistory.go @@ -35,8 +35,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) var ( diff --git a/eth/gasprice/feehistory_test.go b/eth/gasprice/feehistory_test.go index f8234d1d18..f4ef530415 100644 --- a/eth/gasprice/feehistory_test.go +++ b/eth/gasprice/feehistory_test.go @@ -38,7 +38,7 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) func TestFeeHistory(t *testing.T) { diff --git a/eth/gasprice/gasprice.go b/eth/gasprice/gasprice.go index 934c6167c0..206c116b0b 100644 --- a/eth/gasprice/gasprice.go +++ b/eth/gasprice/gasprice.go @@ -37,11 +37,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/lru" - "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/event" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/lru" + "github.com/ava-labs/libevm/common/math" + "github.com/ava-labs/libevm/event" + "github.com/ava-labs/libevm/log" "golang.org/x/exp/slices" ) diff --git a/eth/gasprice/gasprice_test.go b/eth/gasprice/gasprice_test.go index f38c3a5b2c..1b1f2379cf 100644 --- a/eth/gasprice/gasprice_test.go +++ b/eth/gasprice/gasprice_test.go @@ -39,10 +39,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/event" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/event" "github.com/stretchr/testify/require" ) diff --git a/eth/state_accessor.go b/eth/state_accessor.go index dc02b8f033..858fa7ce73 100644 --- a/eth/state_accessor.go +++ b/eth/state_accessor.go @@ -37,11 +37,11 @@ import ( "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/eth/tracers" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/triedb" ) // noopReleaser is returned in case there is no operation expected diff --git a/eth/tracers/api.go b/eth/tracers/api.go index 4f463f33a8..83481901cf 100644 --- a/eth/tracers/api.go +++ b/eth/tracers/api.go @@ -44,13 +44,13 @@ import ( "github.com/ava-labs/coreth/internal/ethapi" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/eth/tracers/logger" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/eth/tracers/logger" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" ) const ( @@ -1108,8 +1108,8 @@ func overrideConfig(original *params.ChainConfig, override *params.ChainConfig) params.GetExtra(copy).EtnaTimestamp = timestamp canon = false } - if timestamp := override.FUpgradeTimestamp; timestamp != nil { - copy.FUpgradeTimestamp = timestamp + if timestamp := overrideExtra.FUpgradeTimestamp; timestamp != nil { + params.GetExtra(copy).FUpgradeTimestamp = timestamp canon = false } if timestamp := override.CancunTime; timestamp != nil { diff --git a/eth/tracers/api_test.go b/eth/tracers/api_test.go index 2dc7149cc2..e91108822d 100644 --- a/eth/tracers/api_test.go +++ b/eth/tracers/api_test.go @@ -46,12 +46,12 @@ import ( "github.com/ava-labs/coreth/internal/ethapi" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/eth/tracers/logger" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/eth/tracers/logger" + "github.com/ava-labs/libevm/ethdb" "golang.org/x/exp/slices" ) diff --git a/eth/tracers/tracers.go b/eth/tracers/tracers.go index 1b17ad650b..e235b4c5e6 100644 --- a/eth/tracers/tracers.go +++ b/eth/tracers/tracers.go @@ -21,8 +21,8 @@ import ( "errors" "fmt" - "github.com/ethereum/go-ethereum/core/vm" - ethtracers "github.com/ethereum/go-ethereum/eth/tracers" + "github.com/ava-labs/libevm/core/vm" + ethtracers "github.com/ava-labs/libevm/eth/tracers" ) // Context contains some contextual infos for a transaction execution that is not diff --git a/eth/tracers/tracers_test.go b/eth/tracers/tracers_test.go index b92d033b16..b8703f9772 100644 --- a/eth/tracers/tracers_test.go +++ b/eth/tracers/tracers_test.go @@ -35,10 +35,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/tests" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/eth/tracers/logger" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/eth/tracers/logger" ) func BenchmarkTransactionTrace(b *testing.B) { diff --git a/ethclient/corethclient/corethclient.go b/ethclient/corethclient/corethclient.go index 448b10b6af..47f8dcb987 100644 --- a/ethclient/corethclient/corethclient.go +++ b/ethclient/corethclient/corethclient.go @@ -37,8 +37,8 @@ import ( "github.com/ava-labs/coreth/ethclient" "github.com/ava-labs/coreth/interfaces" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" ) // Client is a wrapper around rpc.Client that implements geth-specific functionality. diff --git a/ethclient/ethclient.go b/ethclient/ethclient.go index 422cf37fcb..fda588e45b 100644 --- a/ethclient/ethclient.go +++ b/ethclient/ethclient.go @@ -38,8 +38,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/interfaces" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" // Force-load precompiles to trigger registration _ "github.com/ava-labs/coreth/precompile/registry" diff --git a/ethclient/signer.go b/ethclient/signer.go index ba647de1a6..82b8ee48ca 100644 --- a/ethclient/signer.go +++ b/ethclient/signer.go @@ -31,7 +31,7 @@ import ( "math/big" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // senderFromServer is a types.Signer that remembers the sender address returned by the RPC diff --git a/ethclient/simulated/backend.go b/ethclient/simulated/backend.go index c4a3cb8971..f58e3dff8b 100644 --- a/ethclient/simulated/backend.go +++ b/ethclient/simulated/backend.go @@ -34,7 +34,7 @@ import ( "github.com/ava-labs/coreth/node" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) var _ eth.PushGossiper = (*fakePushGossiper)(nil) diff --git a/ethclient/simulated/backend_test.go b/ethclient/simulated/backend_test.go index 34a4855cfb..99b37b8996 100644 --- a/ethclient/simulated/backend_test.go +++ b/ethclient/simulated/backend_test.go @@ -28,8 +28,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" "github.com/stretchr/testify/require" ) diff --git a/interfaces/interfaces.go b/interfaces/interfaces.go index ec900b6e04..d980d915ff 100644 --- a/interfaces/interfaces.go +++ b/interfaces/interfaces.go @@ -33,8 +33,8 @@ import ( "math/big" "github.com/ava-labs/coreth/core/types" - ethereum "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/common" + ethereum "github.com/ava-labs/libevm" + "github.com/ava-labs/libevm/common" ) // NotFound is returned by API methods if the requested item does not exist. diff --git a/internal/blocktest/test_hash.go b/internal/blocktest/test_hash.go index 014e9ff4b0..4dae6f75f7 100644 --- a/internal/blocktest/test_hash.go +++ b/internal/blocktest/test_hash.go @@ -35,7 +35,7 @@ package blocktest import ( "hash" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "golang.org/x/crypto/sha3" ) diff --git a/internal/debug/api.go b/internal/debug/api.go index 6ac4f5110b..044a601f3c 100644 --- a/internal/debug/api.go +++ b/internal/debug/api.go @@ -45,7 +45,7 @@ import ( "sync" "time" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" "github.com/hashicorp/go-bexpr" "golang.org/x/exp/slog" ) diff --git a/internal/debug/flags.go b/internal/debug/flags.go index 94cffe5a0e..bb148bf40e 100644 --- a/internal/debug/flags.go +++ b/internal/debug/flags.go @@ -37,7 +37,7 @@ import ( "runtime" "github.com/ava-labs/coreth/internal/flags" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" "github.com/mattn/go-colorable" "github.com/mattn/go-isatty" "github.com/urfave/cli/v2" diff --git a/internal/debug/trace.go b/internal/debug/trace.go index 12f7bfdb05..dd9a873595 100644 --- a/internal/debug/trace.go +++ b/internal/debug/trace.go @@ -31,7 +31,7 @@ import ( "os" "runtime/trace" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" ) // StartGoTrace turns on tracing, writing to the given file. diff --git a/internal/ethapi/addrlock.go b/internal/ethapi/addrlock.go index 2d00fdd2e7..2cd32605c1 100644 --- a/internal/ethapi/addrlock.go +++ b/internal/ethapi/addrlock.go @@ -29,7 +29,7 @@ package ethapi import ( "sync" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) type AddrLocker struct { diff --git a/internal/ethapi/api.coreth.go b/internal/ethapi/api.coreth.go index 07c285c45e..13cc3f91e3 100644 --- a/internal/ethapi/api.coreth.go +++ b/internal/ethapi/api.coreth.go @@ -9,8 +9,8 @@ import ( "math/big" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/common/math" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/common/math" ) const ( diff --git a/internal/ethapi/api.coreth_test.go b/internal/ethapi/api.coreth_test.go index e23341a3c3..4888e0a364 100644 --- a/internal/ethapi/api.coreth_test.go +++ b/internal/ethapi/api.coreth_test.go @@ -8,8 +8,8 @@ import ( "math/big" "testing" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" "github.com/stretchr/testify/require" ) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 9f261ea362..f99d40be29 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -42,19 +42,19 @@ import ( "github.com/ava-labs/coreth/eth/gasestimator" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" + "github.com/ava-labs/libevm/accounts" + "github.com/ava-labs/libevm/accounts/keystore" + "github.com/ava-labs/libevm/accounts/scwallet" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/common/math" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/eth/tracers/logger" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie" "github.com/davecgh/go-spew/spew" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/accounts/keystore" - "github.com/ethereum/go-ethereum/accounts/scwallet" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/eth/tracers/logger" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" "github.com/holiman/uint256" "github.com/tyler-smith/go-bip39" ) diff --git a/internal/ethapi/api_extra.go b/internal/ethapi/api_extra.go index 44a6fa37cb..5a71fc0789 100644 --- a/internal/ethapi/api_extra.go +++ b/internal/ethapi/api_extra.go @@ -11,9 +11,9 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/rlp" ) // GetChainConfig returns the chain config. diff --git a/internal/ethapi/api_extra_test.go b/internal/ethapi/api_extra_test.go index 5d72617662..45ac7085dd 100644 --- a/internal/ethapi/api_extra_test.go +++ b/internal/ethapi/api_extra_test.go @@ -10,7 +10,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" ) diff --git a/internal/ethapi/api_test.go b/internal/ethapi/api_test.go index 37ab55bc6b..7c93b69d39 100644 --- a/internal/ethapi/api_test.go +++ b/internal/ethapi/api_test.go @@ -52,15 +52,15 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/accounts/keystore" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/crypto/kzg4844" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/event" + "github.com/ava-labs/libevm/accounts" + "github.com/ava-labs/libevm/accounts/keystore" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/crypto/kzg4844" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/event" "github.com/holiman/uint256" "github.com/stretchr/testify/require" "golang.org/x/exp/slices" diff --git a/internal/ethapi/backend.go b/internal/ethapi/backend.go index a94ae30adc..e64aeb75d9 100644 --- a/internal/ethapi/backend.go +++ b/internal/ethapi/backend.go @@ -39,11 +39,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/event" + "github.com/ava-labs/libevm/accounts" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/event" ) // Backend interface provides the common API services (that are provided by diff --git a/internal/ethapi/errors.go b/internal/ethapi/errors.go index 928dded8b7..84a186ecd0 100644 --- a/internal/ethapi/errors.go +++ b/internal/ethapi/errors.go @@ -31,7 +31,7 @@ import ( "github.com/ava-labs/coreth/accounts/abi" "github.com/ava-labs/coreth/vmerrs" - "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ava-labs/libevm/common/hexutil" ) // revertError is an API error that encompasses an EVM revert with JSON error diff --git a/internal/ethapi/mocks_test.go b/internal/ethapi/mocks_test.go index 95b2ca4985..fe81d6a65c 100644 --- a/internal/ethapi/mocks_test.go +++ b/internal/ethapi/mocks_test.go @@ -15,18 +15,18 @@ import ( reflect "reflect" time "time" - accounts "github.com/ava-labs/coreth/accounts" + accounts "github.com/ava-labs/libevm/accounts" consensus "github.com/ava-labs/coreth/consensus" core "github.com/ava-labs/coreth/core" bloombits "github.com/ava-labs/coreth/core/bloombits" state "github.com/ava-labs/coreth/core/state" types "github.com/ava-labs/coreth/core/types" - vm "github.com/ava-labs/coreth/core/vm" + vm "github.com/ava-labs/libevm/core/vm" params "github.com/ava-labs/coreth/params" rpc "github.com/ava-labs/coreth/rpc" - common "github.com/ethereum/go-ethereum/common" - ethdb "github.com/ethereum/go-ethereum/ethdb" - event "github.com/ethereum/go-ethereum/event" + common "github.com/ava-labs/libevm/common" + ethdb "github.com/ava-labs/libevm/ethdb" + event "github.com/ava-labs/libevm/event" gomock "go.uber.org/mock/gomock" ) diff --git a/internal/ethapi/transaction_args.go b/internal/ethapi/transaction_args.go index f79a11367e..85d3804e67 100644 --- a/internal/ethapi/transaction_args.go +++ b/internal/ethapi/transaction_args.go @@ -39,11 +39,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/crypto/kzg4844" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/common/math" + "github.com/ava-labs/libevm/crypto/kzg4844" + "github.com/ava-labs/libevm/log" "github.com/holiman/uint256" ) diff --git a/internal/ethapi/transaction_args_test.go b/internal/ethapi/transaction_args_test.go index 23690fd52d..9cbef3f329 100644 --- a/internal/ethapi/transaction_args_test.go +++ b/internal/ethapi/transaction_args_test.go @@ -35,8 +35,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" ) var _ feeBackend = &backendMock{} diff --git a/internal/shutdowncheck/shutdown_tracker.go b/internal/shutdowncheck/shutdown_tracker.go index 35382305c4..9499a91032 100644 --- a/internal/shutdowncheck/shutdown_tracker.go +++ b/internal/shutdowncheck/shutdown_tracker.go @@ -30,9 +30,9 @@ import ( "time" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" ) // ShutdownTracker is a service that reports previous unclean shutdowns diff --git a/metrics/prometheus/prometheus.go b/metrics/prometheus/prometheus.go index 07c14004ff..cd478e9249 100644 --- a/metrics/prometheus/prometheus.go +++ b/metrics/prometheus/prometheus.go @@ -11,7 +11,7 @@ import ( "github.com/prometheus/client_golang/prometheus" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/metrics" dto "github.com/prometheus/client_model/go" ) diff --git a/metrics/prometheus/prometheus_test.go b/metrics/prometheus/prometheus_test.go index 00cce63c85..5cce784a3f 100644 --- a/metrics/prometheus/prometheus_test.go +++ b/metrics/prometheus/prometheus_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/metrics" ) func TestGatherer_Gather(t *testing.T) { diff --git a/miner/miner.go b/miner/miner.go index 512b99c1bb..a20bb85b14 100644 --- a/miner/miner.go +++ b/miner/miner.go @@ -35,8 +35,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/precompile/precompileconfig" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/event" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/event" ) // Backend wraps all methods required for mining. diff --git a/miner/ordering.go b/miner/ordering.go index 07fa390e4b..2131e2e658 100644 --- a/miner/ordering.go +++ b/miner/ordering.go @@ -32,7 +32,7 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/holiman/uint256" ) diff --git a/miner/ordering_test.go b/miner/ordering_test.go index 27d6b96761..6fa4797700 100644 --- a/miner/ordering_test.go +++ b/miner/ordering_test.go @@ -35,8 +35,8 @@ import ( "github.com/ava-labs/coreth/core/txpool" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" "github.com/holiman/uint256" ) diff --git a/miner/worker.go b/miner/worker.go index d8d6fc3b82..3d2953df8e 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -48,10 +48,10 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/predicate" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/event" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/event" + "github.com/ava-labs/libevm/log" "github.com/holiman/uint256" ) diff --git a/nativeasset/contract.go b/nativeasset/contract.go index 0d6c28337a..523e55b33c 100644 --- a/nativeasset/contract.go +++ b/nativeasset/contract.go @@ -9,9 +9,9 @@ import ( "github.com/ava-labs/coreth/precompile/contract" "github.com/ava-labs/coreth/vmerrs" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/log" "github.com/holiman/uint256" ) diff --git a/nativeasset/contract_test.go b/nativeasset/contract_test.go index 715bd8e222..06e0636687 100644 --- a/nativeasset/contract_test.go +++ b/nativeasset/contract_test.go @@ -12,9 +12,9 @@ import ( . "github.com/ava-labs/coreth/nativeasset" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/vmerrs" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/core/vm" + "github.com/ava-labs/libevm/common" + ethtypes "github.com/ava-labs/libevm/core/types" + "github.com/ava-labs/libevm/core/vm" "github.com/holiman/uint256" "github.com/stretchr/testify/assert" diff --git a/node/api.go b/node/api.go index f0be57313f..1a404b0d10 100644 --- a/node/api.go +++ b/node/api.go @@ -29,8 +29,8 @@ package node import ( "github.com/ava-labs/coreth/internal/debug" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/crypto" ) // apis returns the collection of built-in RPC APIs. diff --git a/node/config.go b/node/config.go index c0b675a45d..c96004e110 100644 --- a/node/config.go +++ b/node/config.go @@ -31,10 +31,10 @@ import ( "os" "path/filepath" - "github.com/ethereum/go-ethereum/accounts" - "github.com/ethereum/go-ethereum/accounts/external" - "github.com/ethereum/go-ethereum/accounts/keystore" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/accounts" + "github.com/ava-labs/libevm/accounts/external" + "github.com/ava-labs/libevm/accounts/keystore" + "github.com/ava-labs/libevm/log" ) // Config represents a small collection of configuration values to fine tune the diff --git a/node/node.go b/node/node.go index 3879e2b299..64ddfe4d8c 100644 --- a/node/node.go +++ b/node/node.go @@ -28,7 +28,7 @@ package node import ( "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/accounts" + "github.com/ava-labs/libevm/accounts" ) // Node is a container on which services can be registered. diff --git a/params/config.go b/params/config.go index 409bfd792b..7a783b9231 100644 --- a/params/config.go +++ b/params/config.go @@ -33,7 +33,7 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/utils" - ethparams "github.com/ethereum/go-ethereum/params" + ethparams "github.com/ava-labs/libevm/params" ) // Avalanche ChainIDs @@ -540,6 +540,44 @@ var ( }, }) + TestFUpgradeChainConfig = WithExtra( + &ChainConfig{ + ChainID: big.NewInt(1), + HomesteadBlock: big.NewInt(0), + DAOForkBlock: big.NewInt(0), + DAOForkSupport: true, + EIP150Block: big.NewInt(0), + EIP155Block: big.NewInt(0), + EIP158Block: big.NewInt(0), + ByzantiumBlock: big.NewInt(0), + ConstantinopleBlock: big.NewInt(0), + PetersburgBlock: big.NewInt(0), + IstanbulBlock: big.NewInt(0), + MuirGlacierBlock: big.NewInt(0), + BerlinBlock: big.NewInt(0), + LondonBlock: big.NewInt(0), + ShanghaiTime: utils.NewUint64(0), + CancunTime: utils.NewUint64(0), + }, + &extras.ChainConfig{ + AvalancheContext: extras.AvalancheContext{SnowCtx: utils.TestSnowContext()}, + NetworkUpgrades: extras.NetworkUpgrades{ + ApricotPhase1BlockTimestamp: utils.NewUint64(0), + ApricotPhase2BlockTimestamp: utils.NewUint64(0), + ApricotPhase3BlockTimestamp: utils.NewUint64(0), + ApricotPhase4BlockTimestamp: utils.NewUint64(0), + ApricotPhase5BlockTimestamp: utils.NewUint64(0), + ApricotPhasePre6BlockTimestamp: utils.NewUint64(0), + ApricotPhase6BlockTimestamp: utils.NewUint64(0), + ApricotPhasePost6BlockTimestamp: utils.NewUint64(0), + BanffBlockTimestamp: utils.NewUint64(0), + CortinaBlockTimestamp: utils.NewUint64(0), + DurangoBlockTimestamp: utils.NewUint64(0), + EtnaTimestamp: utils.NewUint64(0), + FUpgradeTimestamp: utils.NewUint64(0), + }, + }) + TestRules = TestChainConfig.Rules(new(big.Int), IsMergeTODO, 0) ) diff --git a/params/config_libevm.go b/params/config_libevm.go index a9ef2aa5f3..6ab46dbe7e 100644 --- a/params/config_libevm.go +++ b/params/config_libevm.go @@ -9,8 +9,8 @@ import ( "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/precompile/modules" "github.com/ava-labs/coreth/precompile/precompileconfig" - "github.com/ethereum/go-ethereum/common" - ethparams "github.com/ethereum/go-ethereum/params" + "github.com/ava-labs/libevm/common" + ethparams "github.com/ava-labs/libevm/params" ) // libevmInit would ideally be a regular init() function, but it MUST be run diff --git a/params/extras/config.go b/params/extras/config.go index 9037c90f0e..14b17bc56e 100644 --- a/params/extras/config.go +++ b/params/extras/config.go @@ -10,8 +10,8 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - ethparams "github.com/ethereum/go-ethereum/params" + "github.com/ava-labs/libevm/common" + ethparams "github.com/ava-labs/libevm/params" ) // UpgradeConfig includes the following configs that may be specified in upgradeBytes: diff --git a/params/extras/precompile_upgrade.go b/params/extras/precompile_upgrade.go index 42805b2962..6f1522673d 100644 --- a/params/extras/precompile_upgrade.go +++ b/params/extras/precompile_upgrade.go @@ -11,7 +11,7 @@ import ( "github.com/ava-labs/coreth/precompile/modules" "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) var errNoKey = errors.New("PrecompileUpgrade cannot be empty") diff --git a/params/extras/rules.go b/params/extras/rules.go index d5a378739a..40b51a3ba2 100644 --- a/params/extras/rules.go +++ b/params/extras/rules.go @@ -5,7 +5,7 @@ package extras import ( "github.com/ava-labs/coreth/precompile/precompileconfig" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) type Rules struct { diff --git a/params/hooks_libevm.go b/params/hooks_libevm.go index 7bc68dc787..759bd189cb 100644 --- a/params/hooks_libevm.go +++ b/params/hooks_libevm.go @@ -13,10 +13,10 @@ import ( "github.com/ava-labs/coreth/precompile/modules" "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/predicate" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/libevm" - "github.com/ethereum/go-ethereum/libevm/legacy" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/libevm" + "github.com/ava-labs/libevm/libevm/legacy" "github.com/holiman/uint256" "golang.org/x/exp/maps" ) diff --git a/params/protocol_params.go b/params/protocol_params.go index a09de7025c..6bdb5893c1 100644 --- a/params/protocol_params.go +++ b/params/protocol_params.go @@ -29,7 +29,7 @@ package params import ( "math/big" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) const ( diff --git a/peer/network.go b/peer/network.go index a4dfd015f6..7ce1203b45 100644 --- a/peer/network.go +++ b/peer/network.go @@ -12,7 +12,7 @@ import ( "golang.org/x/sync/semaphore" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/ids" diff --git a/peer/peer_tracker.go b/peer/peer_tracker.go index ca11a4faf6..c529dc1e32 100644 --- a/peer/peer_tracker.go +++ b/peer/peer_tracker.go @@ -13,9 +13,9 @@ import ( "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/version" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/metrics" ) const ( diff --git a/peer/stats/stats.go b/peer/stats/stats.go index a23772540c..5a3c2918f4 100644 --- a/peer/stats/stats.go +++ b/peer/stats/stats.go @@ -6,7 +6,7 @@ package stats import ( "time" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/metrics" ) // RequestHandlerStats provides the interface for metrics for app requests. diff --git a/plugin/evm/acp176/acp176_test.go b/plugin/evm/acp176/acp176_test.go index be509292ca..c0d513c4f7 100644 --- a/plugin/evm/acp176/acp176_test.go +++ b/plugin/evm/acp176/acp176_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/ava-labs/avalanchego/vms/components/gas" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/require" ) diff --git a/plugin/evm/admin.go b/plugin/evm/admin.go index 34595a0b0e..bd3308e7ee 100644 --- a/plugin/evm/admin.go +++ b/plugin/evm/admin.go @@ -10,7 +10,7 @@ import ( "github.com/ava-labs/avalanchego/api" "github.com/ava-labs/avalanchego/utils/profiler" "github.com/ava-labs/coreth/plugin/evm/client" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" ) // Admin is the API service for admin API calls diff --git a/plugin/evm/api.go b/plugin/evm/api.go index 12791d4e08..3ed9ed52ee 100644 --- a/plugin/evm/api.go +++ b/plugin/evm/api.go @@ -18,8 +18,8 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/plugin/evm/client" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) // test constants diff --git a/plugin/evm/atomic/export_tx.go b/plugin/evm/atomic/export_tx.go index 7867573385..0b092ee03a 100644 --- a/plugin/evm/atomic/export_tx.go +++ b/plugin/evm/atomic/export_tx.go @@ -24,8 +24,8 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) var ( diff --git a/plugin/evm/atomic/import_tx.go b/plugin/evm/atomic/import_tx.go index e3104d9042..2d98e53fbb 100644 --- a/plugin/evm/atomic/import_tx.go +++ b/plugin/evm/atomic/import_tx.go @@ -23,8 +23,8 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) var ( diff --git a/plugin/evm/atomic/mempool.go b/plugin/evm/atomic/mempool.go index f84dcf1840..4754b070c9 100644 --- a/plugin/evm/atomic/mempool.go +++ b/plugin/evm/atomic/mempool.go @@ -15,8 +15,8 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/ava-labs/coreth/plugin/evm/config" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/metrics" ) const ( diff --git a/plugin/evm/atomic/tx.go b/plugin/evm/atomic/tx.go index 4d670d9c7f..72337a4829 100644 --- a/plugin/evm/atomic/tx.go +++ b/plugin/evm/atomic/tx.go @@ -11,7 +11,7 @@ import ( "math/big" "sort" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/holiman/uint256" "github.com/ava-labs/coreth/params/extras" diff --git a/plugin/evm/atomic_backend.go b/plugin/evm/atomic_backend.go index 45afa707f2..35388b0689 100644 --- a/plugin/evm/atomic_backend.go +++ b/plugin/evm/atomic_backend.go @@ -17,8 +17,8 @@ import ( "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) var _ AtomicBackend = &atomicBackend{} diff --git a/plugin/evm/atomic_state.go b/plugin/evm/atomic_state.go index 911f1afb3a..7647a4cbab 100644 --- a/plugin/evm/atomic_state.go +++ b/plugin/evm/atomic_state.go @@ -10,8 +10,8 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) var _ AtomicState = &atomicState{} diff --git a/plugin/evm/atomic_syncer.go b/plugin/evm/atomic_syncer.go index 083c79a27d..7c25da5539 100644 --- a/plugin/evm/atomic_syncer.go +++ b/plugin/evm/atomic_syncer.go @@ -12,11 +12,11 @@ import ( "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/ava-labs/coreth/plugin/evm/message" syncclient "github.com/ava-labs/coreth/sync/client" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/trie" ) var ( diff --git a/plugin/evm/atomic_syncer_test.go b/plugin/evm/atomic_syncer_test.go index d926152fe5..3da14280a1 100644 --- a/plugin/evm/atomic_syncer_test.go +++ b/plugin/evm/atomic_syncer_test.go @@ -23,9 +23,9 @@ import ( "github.com/ava-labs/coreth/sync/handlers" handlerstats "github.com/ava-labs/coreth/sync/handlers/stats" "github.com/ava-labs/coreth/sync/syncutils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/triedb" ) const commitInterval = 1024 diff --git a/plugin/evm/atomic_trie.go b/plugin/evm/atomic_trie.go index 85b33ca00b..ea961191ee 100644 --- a/plugin/evm/atomic_trie.go +++ b/plugin/evm/atomic_trie.go @@ -19,12 +19,12 @@ import ( "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/plugin/evm/database" "github.com/ava-labs/coreth/triedb/hashdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/trie/trienode" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/trie/trienode" + "github.com/ava-labs/libevm/triedb" ) const ( diff --git a/plugin/evm/atomic_trie_iterator.go b/plugin/evm/atomic_trie_iterator.go index 588fc4e90c..6fd636d744 100644 --- a/plugin/evm/atomic_trie_iterator.go +++ b/plugin/evm/atomic_trie_iterator.go @@ -12,8 +12,8 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/trie" ) const atomicTrieKeyLen = wrappers.LongLen + common.HashLength diff --git a/plugin/evm/atomic_trie_iterator_test.go b/plugin/evm/atomic_trie_iterator_test.go index 21ec9913f9..8da2e03127 100644 --- a/plugin/evm/atomic_trie_iterator_test.go +++ b/plugin/evm/atomic_trie_iterator_test.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/plugin/evm/atomic_trie_test.go b/plugin/evm/atomic_trie_test.go index 1a065d4530..7387374b9b 100644 --- a/plugin/evm/atomic_trie_test.go +++ b/plugin/evm/atomic_trie_test.go @@ -24,10 +24,10 @@ import ( "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ava-labs/coreth/trie/trienode" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie/trienode" ) const testCommitInterval = 100 diff --git a/plugin/evm/atomic_tx_repository.go b/plugin/evm/atomic_tx_repository.go index d1074f60f2..08c4c4d5c4 100644 --- a/plugin/evm/atomic_tx_repository.go +++ b/plugin/evm/atomic_tx_repository.go @@ -8,8 +8,8 @@ import ( "fmt" "time" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/database" diff --git a/plugin/evm/atomic_tx_repository_test.go b/plugin/evm/atomic_tx_repository_test.go index 224f8fa726..9c5616004b 100644 --- a/plugin/evm/atomic_tx_repository_test.go +++ b/plugin/evm/atomic_tx_repository_test.go @@ -13,7 +13,7 @@ import ( "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/utils/set" diff --git a/plugin/evm/block.go b/plugin/evm/block.go index bb7c811494..766167e21f 100644 --- a/plugin/evm/block.go +++ b/plugin/evm/block.go @@ -10,9 +10,9 @@ import ( "fmt" "time" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/core/rawdb" @@ -151,7 +151,7 @@ func (b *Block) Accept(context.Context) error { // Call Accept for relevant precompile logs. Note we do this prior to // calling Accept on the blockChain so any side effects (eg warp signatures) // take place before the accepted log is emitted to subscribers. - rules := b.vm.chainConfig.Rules(b.ethBlock.Number(), params.IsMergeTODO, b.ethBlock.Timestamp()) + rules := b.vm.chainConfig.Rules(b.ethBlock.Number(), params.IsMergeTODO, b.ethBlock.Time()) if err := b.handlePrecompileAccept(*params.GetRulesExtra(rules)); err != nil { return err } diff --git a/plugin/evm/block_builder.go b/plugin/evm/block_builder.go index 721561ff40..c621c7ff1b 100644 --- a/plugin/evm/block_builder.go +++ b/plugin/evm/block_builder.go @@ -16,7 +16,7 @@ import ( "github.com/ava-labs/avalanchego/snow" commonEng "github.com/ava-labs/avalanchego/snow/engine/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" ) const ( diff --git a/plugin/evm/block_verification.go b/plugin/evm/block_verification.go index 580456dcbb..5373cbef4f 100644 --- a/plugin/evm/block_verification.go +++ b/plugin/evm/block_verification.go @@ -8,7 +8,7 @@ import ( "fmt" "math/big" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" safemath "github.com/ava-labs/avalanchego/utils/math" @@ -16,8 +16,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/plugin/evm/header" - "github.com/ava-labs/coreth/trie" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/trie" ) var ( @@ -124,7 +123,7 @@ func (v blockValidator) SyntacticVerify(b *Block, rules params.Rules) error { } // Verify the extra data is well-formed. - if err := header.VerifyExtra(rules.AvalancheRules, ethHeader.Extra); err != nil { + if err := header.VerifyExtra(rulesExtra.AvalancheRules, ethHeader.Extra); err != nil { return err } diff --git a/plugin/evm/client/utils.go b/plugin/evm/client/utils.go index 5ea43f4a20..7d1e35e4ae 100644 --- a/plugin/evm/client/utils.go +++ b/plugin/evm/client/utils.go @@ -3,7 +3,7 @@ package client -import "github.com/ethereum/go-ethereum/common" +import "github.com/ava-labs/libevm/common" func ParseEthAddress(addrStr string) (common.Address, error) { if !common.IsHexAddress(addrStr) { diff --git a/plugin/evm/config/config.go b/plugin/evm/config/config.go index 3104b0faa9..b373b4f292 100644 --- a/plugin/evm/config/config.go +++ b/plugin/evm/config/config.go @@ -9,8 +9,8 @@ import ( "time" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" "github.com/spf13/cast" ) diff --git a/plugin/evm/config/config_test.go b/plugin/evm/config/config_test.go index ad13ebdfed..7b96a11742 100644 --- a/plugin/evm/config/config_test.go +++ b/plugin/evm/config/config_test.go @@ -9,7 +9,7 @@ import ( "testing" "time" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/assert" ) diff --git a/plugin/evm/database/wrapped_database.go b/plugin/evm/database/wrapped_database.go index f8a36913bb..86e3bbd239 100644 --- a/plugin/evm/database/wrapped_database.go +++ b/plugin/evm/database/wrapped_database.go @@ -7,7 +7,7 @@ import ( "errors" "github.com/ava-labs/avalanchego/database" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/ethdb" ) var ( diff --git a/plugin/evm/export_tx_test.go b/plugin/evm/export_tx_test.go index 258762883d..df6103555a 100644 --- a/plugin/evm/export_tx_test.go +++ b/plugin/evm/export_tx_test.go @@ -20,7 +20,7 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/holiman/uint256" ) diff --git a/plugin/evm/ext_data_hashes.go b/plugin/evm/ext_data_hashes.go index 7648c3bcdb..ae2b4612cc 100644 --- a/plugin/evm/ext_data_hashes.go +++ b/plugin/evm/ext_data_hashes.go @@ -4,7 +4,7 @@ import ( _ "embed" "encoding/json" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) var ( diff --git a/plugin/evm/gossip.go b/plugin/evm/gossip.go index e1bf58b0fc..2f0bfb1821 100644 --- a/plugin/evm/gossip.go +++ b/plugin/evm/gossip.go @@ -12,8 +12,8 @@ import ( "sync/atomic" "time" - ethcommon "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + ethcommon "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" "github.com/prometheus/client_golang/prometheus" "github.com/ava-labs/avalanchego/ids" diff --git a/plugin/evm/gossip_test.go b/plugin/evm/gossip_test.go index c690c04add..03bb31431a 100644 --- a/plugin/evm/gossip_test.go +++ b/plugin/evm/gossip_test.go @@ -17,9 +17,9 @@ import ( "github.com/ava-labs/coreth/core/txpool/legacypool" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/core/vm" + "github.com/ava-labs/libevm/crypto" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/plugin/evm/gossiper_eth_gossiping_test.go b/plugin/evm/gossiper_eth_gossiping_test.go index 64c68010e0..e323308a58 100644 --- a/plugin/evm/gossiper_eth_gossiping_test.go +++ b/plugin/evm/gossiper_eth_gossiping_test.go @@ -18,8 +18,8 @@ import ( commonEng "github.com/ava-labs/avalanchego/snow/engine/common" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" "github.com/stretchr/testify/assert" diff --git a/plugin/evm/header/block_gas_cost.go b/plugin/evm/header/block_gas_cost.go index 468c7d0ba5..ad13e7e8df 100644 --- a/plugin/evm/header/block_gas_cost.go +++ b/plugin/evm/header/block_gas_cost.go @@ -7,7 +7,7 @@ import ( "math/big" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/plugin/evm/ap4" ) @@ -20,7 +20,7 @@ const ApricotPhase5BlockGasCostStep = 200_000 // BlockGasCost calculates the required block gas cost based on the parent // header and the timestamp of the new block. func BlockGasCost( - config *params.ChainConfig, + config *extras.ChainConfig, parent *types.Header, timestamp uint64, ) uint64 { diff --git a/plugin/evm/header/block_gas_cost_test.go b/plugin/evm/header/block_gas_cost_test.go index ec67ca1953..4c39ca0019 100644 --- a/plugin/evm/header/block_gas_cost_test.go +++ b/plugin/evm/header/block_gas_cost_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/params/extras" "github.com/ava-labs/coreth/plugin/evm/ap4" "github.com/ava-labs/coreth/utils" "github.com/stretchr/testify/assert" @@ -49,8 +49,8 @@ func TestBlockGasCost(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - config := ¶ms.ChainConfig{ - NetworkUpgrades: params.NetworkUpgrades{ + config := &extras.ChainConfig{ + NetworkUpgrades: extras.NetworkUpgrades{ ApricotPhase5BlockTimestamp: test.apricotPhase5BlockTimestamp, }, } diff --git a/plugin/evm/header/extra.go b/plugin/evm/header/extra.go index abe0bd3f1a..ee86919457 100644 --- a/plugin/evm/header/extra.go +++ b/plugin/evm/header/extra.go @@ -8,13 +8,14 @@ import ( "fmt" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/params/extras" ) var errInvalidExtraLength = errors.New("invalid header.Extra length") // VerifyExtra verifies that the header's Extra field is correctly formatted for // [rules]. -func VerifyExtra(rules params.AvalancheRules, extra []byte) error { +func VerifyExtra(rules extras.AvalancheRules, extra []byte) error { extraLen := len(extra) switch { case rules.IsDurango: diff --git a/plugin/evm/header/extra_test.go b/plugin/evm/header/extra_test.go index f11e5d5780..a2c7224f9b 100644 --- a/plugin/evm/header/extra_test.go +++ b/plugin/evm/header/extra_test.go @@ -7,31 +7,32 @@ import ( "testing" "github.com/ava-labs/coreth/params" + "github.com/ava-labs/coreth/params/extras" "github.com/stretchr/testify/require" ) func TestVerifyExtra(t *testing.T) { tests := []struct { name string - rules params.AvalancheRules + rules extras.AvalancheRules extra []byte expected error }{ { name: "initial_valid", - rules: params.AvalancheRules{}, + rules: extras.AvalancheRules{}, extra: make([]byte, params.MaximumExtraDataSize), expected: nil, }, { name: "initial_invalid", - rules: params.AvalancheRules{}, + rules: extras.AvalancheRules{}, extra: make([]byte, params.MaximumExtraDataSize+1), expected: errInvalidExtraLength, }, { name: "ap1_valid", - rules: params.AvalancheRules{ + rules: extras.AvalancheRules{ IsApricotPhase1: true, }, extra: nil, @@ -39,7 +40,7 @@ func TestVerifyExtra(t *testing.T) { }, { name: "ap1_invalid", - rules: params.AvalancheRules{ + rules: extras.AvalancheRules{ IsApricotPhase1: true, }, extra: make([]byte, 1), @@ -47,7 +48,7 @@ func TestVerifyExtra(t *testing.T) { }, { name: "ap3_valid", - rules: params.AvalancheRules{ + rules: extras.AvalancheRules{ IsApricotPhase3: true, }, extra: make([]byte, params.DynamicFeeExtraDataSize), @@ -55,7 +56,7 @@ func TestVerifyExtra(t *testing.T) { }, { name: "ap3_invalid_less", - rules: params.AvalancheRules{ + rules: extras.AvalancheRules{ IsApricotPhase3: true, }, extra: make([]byte, params.DynamicFeeExtraDataSize-1), @@ -63,7 +64,7 @@ func TestVerifyExtra(t *testing.T) { }, { name: "ap3_invalid_more", - rules: params.AvalancheRules{ + rules: extras.AvalancheRules{ IsApricotPhase3: true, }, extra: make([]byte, params.DynamicFeeExtraDataSize+1), @@ -71,7 +72,7 @@ func TestVerifyExtra(t *testing.T) { }, { name: "durango_valid_min", - rules: params.AvalancheRules{ + rules: extras.AvalancheRules{ IsDurango: true, }, extra: make([]byte, params.DynamicFeeExtraDataSize), @@ -79,7 +80,7 @@ func TestVerifyExtra(t *testing.T) { }, { name: "durango_valid_extra", - rules: params.AvalancheRules{ + rules: extras.AvalancheRules{ IsDurango: true, }, extra: make([]byte, params.DynamicFeeExtraDataSize+1), @@ -87,7 +88,7 @@ func TestVerifyExtra(t *testing.T) { }, { name: "durango_invalid", - rules: params.AvalancheRules{ + rules: extras.AvalancheRules{ IsDurango: true, }, extra: make([]byte, params.DynamicFeeExtraDataSize-1), diff --git a/plugin/evm/import_tx_test.go b/plugin/evm/import_tx_test.go index eaf2b39cf3..bc57aec0d3 100644 --- a/plugin/evm/import_tx_test.go +++ b/plugin/evm/import_tx_test.go @@ -9,7 +9,7 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/plugin/evm/atomic" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/holiman/uint256" avalancheatomic "github.com/ava-labs/avalanchego/chains/atomic" diff --git a/plugin/evm/log.go b/plugin/evm/log.go index fe92f1fb7f..83612ce03c 100644 --- a/plugin/evm/log.go +++ b/plugin/evm/log.go @@ -11,7 +11,7 @@ import ( "strings" "github.com/ava-labs/coreth/log" - ethlog "github.com/ethereum/go-ethereum/log" + ethlog "github.com/ava-labs/libevm/log" "golang.org/x/exp/slog" ) diff --git a/plugin/evm/log_test.go b/plugin/evm/log_test.go index b39fa8cc3c..eb61a4e5e5 100644 --- a/plugin/evm/log_test.go +++ b/plugin/evm/log_test.go @@ -7,7 +7,7 @@ import ( "os" "testing" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" "github.com/stretchr/testify/require" ) diff --git a/plugin/evm/message/block_request.go b/plugin/evm/message/block_request.go index f1f353f2f7..009e6b0155 100644 --- a/plugin/evm/message/block_request.go +++ b/plugin/evm/message/block_request.go @@ -9,7 +9,7 @@ import ( "github.com/ava-labs/avalanchego/ids" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) var ( diff --git a/plugin/evm/message/block_request_test.go b/plugin/evm/message/block_request_test.go index cd9070117d..7d5b286551 100644 --- a/plugin/evm/message/block_request_test.go +++ b/plugin/evm/message/block_request_test.go @@ -8,7 +8,7 @@ import ( "math/rand" "testing" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/assert" ) diff --git a/plugin/evm/message/code_request.go b/plugin/evm/message/code_request.go index cd1ffef844..d1aeb7f2f6 100644 --- a/plugin/evm/message/code_request.go +++ b/plugin/evm/message/code_request.go @@ -9,7 +9,7 @@ import ( "strings" "github.com/ava-labs/avalanchego/ids" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) var _ Request = CodeRequest{} diff --git a/plugin/evm/message/code_request_test.go b/plugin/evm/message/code_request_test.go index 88cedb54d4..3faf12949d 100644 --- a/plugin/evm/message/code_request_test.go +++ b/plugin/evm/message/code_request_test.go @@ -8,7 +8,7 @@ import ( "math/rand" "testing" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/assert" ) diff --git a/plugin/evm/message/leafs_request.go b/plugin/evm/message/leafs_request.go index 22629e62ef..32ae4dc45d 100644 --- a/plugin/evm/message/leafs_request.go +++ b/plugin/evm/message/leafs_request.go @@ -8,8 +8,8 @@ import ( "fmt" "github.com/ava-labs/avalanchego/ids" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) const MaxCodeHashesPerRequest = 5 diff --git a/plugin/evm/message/leafs_request_test.go b/plugin/evm/message/leafs_request_test.go index ab6cab5124..68784fe04c 100644 --- a/plugin/evm/message/leafs_request_test.go +++ b/plugin/evm/message/leafs_request_test.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/avalanchego/ids" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/assert" ) diff --git a/plugin/evm/message/syncable.go b/plugin/evm/message/syncable.go index c8631bbb5e..680a18b421 100644 --- a/plugin/evm/message/syncable.go +++ b/plugin/evm/message/syncable.go @@ -8,8 +8,8 @@ import ( "fmt" "github.com/ava-labs/avalanchego/ids" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" ) diff --git a/plugin/evm/network_handler.go b/plugin/evm/network_handler.go index e428150052..b207bc2ca1 100644 --- a/plugin/evm/network_handler.go +++ b/plugin/evm/network_handler.go @@ -13,9 +13,9 @@ import ( syncStats "github.com/ava-labs/coreth/sync/handlers/stats" "github.com/ava-labs/coreth/warp" warpHandlers "github.com/ava-labs/coreth/warp/handlers" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/metrics" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/metrics" + "github.com/ava-labs/libevm/triedb" ) var _ message.RequestHandler = &networkHandler{} diff --git a/plugin/evm/prestate_tracer_test.go b/plugin/evm/prestate_tracer_test.go index 3b38e52412..8de9762efa 100644 --- a/plugin/evm/prestate_tracer_test.go +++ b/plugin/evm/prestate_tracer_test.go @@ -17,10 +17,10 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/eth/tracers" "github.com/ava-labs/coreth/tests" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/math" - ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/core/vm" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/math" + ethtypes "github.com/ava-labs/libevm/core/types" + "github.com/ava-labs/libevm/core/vm" ) func TestPrestateWithDiffModeANTTracer(t *testing.T) { diff --git a/plugin/evm/syncervm_client.go b/plugin/evm/syncervm_client.go index c25f68c46b..e6efd34a49 100644 --- a/plugin/evm/syncervm_client.go +++ b/plugin/evm/syncervm_client.go @@ -21,9 +21,9 @@ import ( "github.com/ava-labs/coreth/plugin/evm/message" syncclient "github.com/ava-labs/coreth/sync/client" "github.com/ava-labs/coreth/sync/statesync" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" ) const ( diff --git a/plugin/evm/syncervm_server.go b/plugin/evm/syncervm_server.go index 3bf051bf87..f249169193 100644 --- a/plugin/evm/syncervm_server.go +++ b/plugin/evm/syncervm_server.go @@ -12,8 +12,8 @@ import ( "github.com/ava-labs/coreth/core" "github.com/ava-labs/coreth/plugin/evm/message" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) type stateSyncServerConfig struct { diff --git a/plugin/evm/syncervm_test.go b/plugin/evm/syncervm_test.go index 8ee605c20c..931a123f03 100644 --- a/plugin/evm/syncervm_test.go +++ b/plugin/evm/syncervm_test.go @@ -40,12 +40,12 @@ import ( statesyncclient "github.com/ava-labs/coreth/sync/client" "github.com/ava-labs/coreth/sync/statesync" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/triedb" ) func TestSkipStateSync(t *testing.T) { diff --git a/plugin/evm/testutils/metrics.go b/plugin/evm/testutils/metrics.go index aa2ee19037..afb2ea7f43 100644 --- a/plugin/evm/testutils/metrics.go +++ b/plugin/evm/testutils/metrics.go @@ -3,7 +3,7 @@ package testutils import ( "testing" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/metrics" ) // WithMetrics enables go-ethereum metrics globally for the test. diff --git a/plugin/evm/tx_test.go b/plugin/evm/tx_test.go index 4001fa4ebc..5e63eeb090 100644 --- a/plugin/evm/tx_test.go +++ b/plugin/evm/tx_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/params/extras" diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 24c4dd1d58..2ec5e97ca9 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -45,8 +45,8 @@ import ( "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/triedb/hashdb" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/metrics" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/metrics" + "github.com/ava-labs/libevm/triedb" warpcontract "github.com/ava-labs/coreth/precompile/contracts/warp" "github.com/ava-labs/coreth/rpc" @@ -59,17 +59,17 @@ import ( // We must import this package (not referenced elsewhere) so that the native "callTracer" // is added to a map of client-accessible tracers. In geth, this is done // inside of cmd/geth. - _ "github.com/ethereum/go-ethereum/eth/tracers/js" - _ "github.com/ethereum/go-ethereum/eth/tracers/native" + _ "github.com/ava-labs/libevm/eth/tracers/js" + _ "github.com/ava-labs/libevm/eth/tracers/native" "github.com/ava-labs/coreth/precompile/precompileconfig" // Force-load precompiles to trigger registration _ "github.com/ava-labs/coreth/precompile/registry" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" avalancheRPC "github.com/gorilla/rpc/v2" @@ -422,7 +422,7 @@ func (vm *VM) Initialize( // if the chainCtx.NetworkUpgrades is not empty, set the chain config // normally it should not be empty, but some tests may not set it if chainCtx.NetworkUpgrades != (upgrade.Config{}) { - g.Config.NetworkUpgrades = params.GetNetworkUpgrades(chainCtx.NetworkUpgrades) + params.GetExtra(g.Config).NetworkUpgrades = extras.GetNetworkUpgrades(chainCtx.NetworkUpgrades) } // If the Durango is activated, activate the Warp Precompile at the same time @@ -1585,7 +1585,7 @@ func (vm *VM) verifyTxAtTip(tx *atomic.Tx) error { var nextBaseFee *big.Int timestamp := uint64(vm.clock.Time().Unix()) if vm.chainConfigExtra().IsApricotPhase3(timestamp) { - _, nextBaseFee, err = dummy.EstimateNextBaseFee(vm.chainConfig, parentHeader, timestamp) + nextBaseFee, err = dummy.EstimateNextBaseFee(vm.chainConfig, parentHeader, timestamp) if err != nil { // Return extremely detailed error since CalcBaseFee should never encounter an issue here return fmt.Errorf("failed to calculate base fee with parent timestamp (%d), parent ExtraData: (0x%x), and current timestamp (%d): %w", parentHeader.Time, parentHeader.Extra, timestamp, err) diff --git a/plugin/evm/vm_database.go b/plugin/evm/vm_database.go index f2a5b4c344..958f22db57 100644 --- a/plugin/evm/vm_database.go +++ b/plugin/evm/vm_database.go @@ -11,8 +11,8 @@ import ( "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/plugin/evm/database" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) // initializeDBs initializes the databases used by the VM. diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 739ce8a160..4451f966eb 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -16,17 +16,17 @@ import ( "testing" "time" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" "github.com/holiman/uint256" "github.com/ava-labs/coreth/constants" "github.com/ava-labs/coreth/eth/filters" "github.com/ava-labs/coreth/plugin/evm/atomic" "github.com/ava-labs/coreth/plugin/evm/config" -======= - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/coreth/utils" + "github.com/ava-labs/libevm/trie" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -226,7 +226,11 @@ func NewContext() *snow.Context { ctx.WarpSigner = avalancheWarp.NewSigner(blsSecretKey, ctx.NetworkID, ctx.ChainID) ctx.PublicKey = blsSecretKey.PublicKey() return ctx +} + +// setupGenesis sets up the genesis // If [genesisJSON] is empty, defaults to using [genesisJSONLatest] +func setupGenesis( t *testing.T, genesisJSON string, ) (*snow.Context, diff --git a/plugin/evm/vm_warp_test.go b/plugin/evm/vm_warp_test.go index 28618d545e..de9c7281fb 100644 --- a/plugin/evm/vm_warp_test.go +++ b/plugin/evm/vm_warp_test.go @@ -38,8 +38,8 @@ import ( "github.com/ava-labs/coreth/predicate" "github.com/ava-labs/coreth/utils" "github.com/ava-labs/coreth/warp" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" "github.com/stretchr/testify/require" ) diff --git a/precompile/contract/contract.go b/precompile/contract/contract.go index 0be76a8955..b64c8058dc 100644 --- a/precompile/contract/contract.go +++ b/precompile/contract/contract.go @@ -6,7 +6,7 @@ package contract import ( "fmt" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) const ( diff --git a/precompile/contract/interfaces.go b/precompile/contract/interfaces.go index 958283b3c2..a1ae9d5682 100644 --- a/precompile/contract/interfaces.go +++ b/precompile/contract/interfaces.go @@ -9,9 +9,9 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/coreth/precompile/precompileconfig" - "github.com/ethereum/go-ethereum/common" - ethtypes "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/core/vm" + "github.com/ava-labs/libevm/common" + ethtypes "github.com/ava-labs/libevm/core/types" + "github.com/ava-labs/libevm/core/vm" "github.com/holiman/uint256" ) diff --git a/precompile/contract/mocks.go b/precompile/contract/mocks.go index 813296c8e6..f9991cca78 100644 --- a/precompile/contract/mocks.go +++ b/precompile/contract/mocks.go @@ -15,8 +15,8 @@ import ( snow "github.com/ava-labs/avalanchego/snow" precompileconfig "github.com/ava-labs/coreth/precompile/precompileconfig" - common "github.com/ethereum/go-ethereum/common" - vm "github.com/ethereum/go-ethereum/core/vm" + common "github.com/ava-labs/libevm/common" + vm "github.com/ava-labs/libevm/core/vm" uint256 "github.com/holiman/uint256" gomock "go.uber.org/mock/gomock" ) diff --git a/precompile/contract/utils.go b/precompile/contract/utils.go index 6b8ed7c832..8484415397 100644 --- a/precompile/contract/utils.go +++ b/precompile/contract/utils.go @@ -10,7 +10,7 @@ import ( "github.com/ava-labs/coreth/accounts/abi" "github.com/ava-labs/coreth/vmerrs" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/crypto" ) // Gas costs for stateful precompiles diff --git a/precompile/contracts/warp/config.go b/precompile/contracts/warp/config.go index ebcc8977c4..495eeb62e2 100644 --- a/precompile/contracts/warp/config.go +++ b/precompile/contracts/warp/config.go @@ -13,9 +13,9 @@ import ( "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/predicate" warpValidators "github.com/ava-labs/coreth/warp/validators" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/math" + "github.com/ava-labs/libevm/log" ) const ( diff --git a/precompile/contracts/warp/contract.go b/precompile/contracts/warp/contract.go index 932c19ea31..295b154bc8 100644 --- a/precompile/contracts/warp/contract.go +++ b/precompile/contracts/warp/contract.go @@ -15,8 +15,8 @@ import ( _ "embed" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/math" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/math" ) const ( diff --git a/precompile/contracts/warp/contract_test.go b/precompile/contracts/warp/contract_test.go index 8c171baaed..f6d38cbb89 100644 --- a/precompile/contracts/warp/contract_test.go +++ b/precompile/contracts/warp/contract_test.go @@ -20,7 +20,7 @@ import ( "github.com/ava-labs/coreth/predicate" "github.com/ava-labs/coreth/utils" "github.com/ava-labs/coreth/vmerrs" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/require" ) diff --git a/precompile/contracts/warp/contract_warp_handler.go b/precompile/contracts/warp/contract_warp_handler.go index 3dc7191ef1..a28afc9ef1 100644 --- a/precompile/contracts/warp/contract_warp_handler.go +++ b/precompile/contracts/warp/contract_warp_handler.go @@ -12,8 +12,8 @@ import ( "github.com/ava-labs/coreth/precompile/contract" "github.com/ava-labs/coreth/predicate" "github.com/ava-labs/coreth/vmerrs" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/math" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/math" ) var ( diff --git a/precompile/contracts/warp/module.go b/precompile/contracts/warp/module.go index 336100da34..b333d8f7ec 100644 --- a/precompile/contracts/warp/module.go +++ b/precompile/contracts/warp/module.go @@ -10,7 +10,7 @@ import ( "github.com/ava-labs/coreth/precompile/modules" "github.com/ava-labs/coreth/precompile/precompileconfig" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) var _ contract.Configurator = &configurator{} diff --git a/precompile/modules/module.go b/precompile/modules/module.go index fefa9fd2da..a5fca0cc38 100644 --- a/precompile/modules/module.go +++ b/precompile/modules/module.go @@ -7,7 +7,7 @@ import ( "bytes" "github.com/ava-labs/coreth/precompile/contract" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) type Module struct { diff --git a/precompile/modules/registerer.go b/precompile/modules/registerer.go index a7f3b92c60..068170bd2c 100644 --- a/precompile/modules/registerer.go +++ b/precompile/modules/registerer.go @@ -9,7 +9,7 @@ import ( "github.com/ava-labs/coreth/constants" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) var ( diff --git a/precompile/modules/registerer_test.go b/precompile/modules/registerer_test.go index f2519046df..665f1aa860 100644 --- a/precompile/modules/registerer_test.go +++ b/precompile/modules/registerer_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/ava-labs/coreth/constants" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/require" ) diff --git a/precompile/precompileconfig/config.go b/precompile/precompileconfig/config.go index eb741cbc55..7dd027aadc 100644 --- a/precompile/precompileconfig/config.go +++ b/precompile/precompileconfig/config.go @@ -8,7 +8,7 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "github.com/ava-labs/avalanchego/vms/platformvm/warp" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // StatefulPrecompileConfig defines the interface for a stateful precompile to diff --git a/precompile/precompileconfig/mocks.go b/precompile/precompileconfig/mocks.go index cba1ca13a3..6843eaa6b4 100644 --- a/precompile/precompileconfig/mocks.go +++ b/precompile/precompileconfig/mocks.go @@ -12,7 +12,7 @@ package precompileconfig import ( reflect "reflect" - common "github.com/ethereum/go-ethereum/common" + common "github.com/ava-labs/libevm/common" gomock "go.uber.org/mock/gomock" ) diff --git a/precompile/testutils/test_precompile.go b/precompile/testutils/test_precompile.go index a0bc279ff9..86c29c6323 100644 --- a/precompile/testutils/test_precompile.go +++ b/precompile/testutils/test_precompile.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/coreth/precompile/modules" "github.com/ava-labs/coreth/precompile/precompileconfig" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" ) diff --git a/predicate/predicate_bytes.go b/predicate/predicate_bytes.go index 5c93bb5e3b..1d487a99d9 100644 --- a/predicate/predicate_bytes.go +++ b/predicate/predicate_bytes.go @@ -6,7 +6,7 @@ package predicate import ( "fmt" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // DynamicFeeExtraDataSize is defined in the predicate package to avoid a circular dependency. diff --git a/predicate/predicate_results.go b/predicate/predicate_results.go index f28b790821..a79417329c 100644 --- a/predicate/predicate_results.go +++ b/predicate/predicate_results.go @@ -11,7 +11,7 @@ import ( "github.com/ava-labs/avalanchego/codec/linearcodec" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/utils/wrappers" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) const ( diff --git a/predicate/predicate_results_test.go b/predicate/predicate_results_test.go index e3daefa706..45b8efc0d6 100644 --- a/predicate/predicate_results_test.go +++ b/predicate/predicate_results_test.go @@ -6,7 +6,7 @@ package predicate import ( "testing" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/require" ) diff --git a/predicate/predicate_slots.go b/predicate/predicate_slots.go index 5ce3d2f1ea..f71145fbdd 100644 --- a/predicate/predicate_slots.go +++ b/predicate/predicate_slots.go @@ -6,7 +6,7 @@ package predicate import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) type predicaters interface { diff --git a/predicate/predicate_tx.go b/predicate/predicate_tx.go index 76bb3ce6bd..f2b101bb67 100644 --- a/predicate/predicate_tx.go +++ b/predicate/predicate_tx.go @@ -8,7 +8,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // NewPredicateTx returns a transaction with the predicateAddress/predicateBytes tuple diff --git a/rpc/client.go b/rpc/client.go index 6c11365560..ff351485f0 100644 --- a/rpc/client.go +++ b/rpc/client.go @@ -37,7 +37,7 @@ import ( "sync/atomic" "time" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" ) var ( diff --git a/rpc/client_test.go b/rpc/client_test.go index 97bc69e61b..826d1eed48 100644 --- a/rpc/client_test.go +++ b/rpc/client_test.go @@ -42,8 +42,8 @@ import ( "testing" "time" + "github.com/ava-labs/libevm/log" "github.com/davecgh/go-spew/spew" - "github.com/ethereum/go-ethereum/log" ) func TestClientRequest(t *testing.T) { diff --git a/rpc/handler.go b/rpc/handler.go index 82d1235ab1..e589b0292a 100644 --- a/rpc/handler.go +++ b/rpc/handler.go @@ -38,8 +38,8 @@ import ( "sync" "time" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/metrics" "golang.org/x/time/rate" ) diff --git a/rpc/metrics.go b/rpc/metrics.go index bafdcf591c..a4469545d7 100644 --- a/rpc/metrics.go +++ b/rpc/metrics.go @@ -30,7 +30,7 @@ import ( "fmt" "time" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/metrics" ) var ( diff --git a/rpc/server.go b/rpc/server.go index 054bd2de92..d41ce1cc32 100644 --- a/rpc/server.go +++ b/rpc/server.go @@ -33,7 +33,7 @@ import ( "sync/atomic" "time" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" ) const MetadataApi = "rpc" diff --git a/rpc/service.go b/rpc/service.go index eecd70e90e..d8fe238844 100644 --- a/rpc/service.go +++ b/rpc/service.go @@ -35,7 +35,7 @@ import ( "sync" "unicode" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" ) var ( diff --git a/rpc/subscription_test.go b/rpc/subscription_test.go index 5e3143c9fe..06a2bb0660 100644 --- a/rpc/subscription_test.go +++ b/rpc/subscription_test.go @@ -39,7 +39,7 @@ import ( "time" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) func TestNewID(t *testing.T) { diff --git a/rpc/types.go b/rpc/types.go index c96e7bc74f..38123bb430 100644 --- a/rpc/types.go +++ b/rpc/types.go @@ -34,8 +34,8 @@ import ( "math" "strings" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" ) // API describes the set of methods offered over the RPC interface diff --git a/rpc/types_test.go b/rpc/types_test.go index 779b23296f..d37632d62e 100644 --- a/rpc/types_test.go +++ b/rpc/types_test.go @@ -31,8 +31,8 @@ import ( "reflect" "testing" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/math" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/math" ) func TestBlockNumberJSONUnmarshal(t *testing.T) { diff --git a/rpc/websocket.go b/rpc/websocket.go index 1be8364955..6f545477ad 100644 --- a/rpc/websocket.go +++ b/rpc/websocket.go @@ -37,8 +37,8 @@ import ( "sync" "time" + "github.com/ava-labs/libevm/log" mapset "github.com/deckarep/golang-set/v2" - "github.com/ethereum/go-ethereum/log" "github.com/gorilla/websocket" ) diff --git a/scripts/eth-allowed-packages.txt b/scripts/eth-allowed-packages.txt index e85549a225..1b77e90209 100644 --- a/scripts/eth-allowed-packages.txt +++ b/scripts/eth-allowed-packages.txt @@ -1,40 +1,40 @@ -"github.com/ethereum/go-ethereum/accounts" -"github.com/ethereum/go-ethereum/accounts/external" -"github.com/ethereum/go-ethereum/accounts/keystore" -"github.com/ethereum/go-ethereum/accounts/scwallet" -"github.com/ethereum/go-ethereum/common" -"github.com/ethereum/go-ethereum/common/bitutil" -"github.com/ethereum/go-ethereum/common/compiler" -"github.com/ethereum/go-ethereum/common/hexutil" -"github.com/ethereum/go-ethereum/common/lru" -"github.com/ethereum/go-ethereum/common/math" -"github.com/ethereum/go-ethereum/common/prque" -"github.com/ethereum/go-ethereum/core/asm" -"github.com/ethereum/go-ethereum/core/vm" -"github.com/ethereum/go-ethereum/crypto" -"github.com/ethereum/go-ethereum/crypto/blake2b" -"github.com/ethereum/go-ethereum/crypto/bls12381" -"github.com/ethereum/go-ethereum/crypto/bn256" -"github.com/ethereum/go-ethereum/crypto/kzg4844" -"github.com/ethereum/go-ethereum/eth/tracers/js" -"github.com/ethereum/go-ethereum/eth/tracers/logger" -"github.com/ethereum/go-ethereum/eth/tracers/native" -"github.com/ethereum/go-ethereum/ethdb" -"github.com/ethereum/go-ethereum/ethdb/leveldb" -"github.com/ethereum/go-ethereum/ethdb/memorydb" -"github.com/ethereum/go-ethereum/ethdb/pebble" -"github.com/ethereum/go-ethereum/event" -"github.com/ethereum/go-ethereum/libevm" -"github.com/ethereum/go-ethereum/libevm/legacy" -"github.com/ethereum/go-ethereum/libevm/stateconf" -"github.com/ethereum/go-ethereum/log" -"github.com/ethereum/go-ethereum/params" -"github.com/ethereum/go-ethereum/metrics" -"github.com/ethereum/go-ethereum/rlp" -"github.com/ethereum/go-ethereum/trie" -"github.com/ethereum/go-ethereum/trie/testutil" -"github.com/ethereum/go-ethereum/trie/trienode" -"github.com/ethereum/go-ethereum/trie/triestate" -"github.com/ethereum/go-ethereum/trie/utils" -"github.com/ethereum/go-ethereum/triedb" -"github.com/ethereum/go-ethereum/triedb/database" \ No newline at end of file +"github.com/ava-labs/libevm/accounts" +"github.com/ava-labs/libevm/accounts/external" +"github.com/ava-labs/libevm/accounts/keystore" +"github.com/ava-labs/libevm/accounts/scwallet" +"github.com/ava-labs/libevm/common" +"github.com/ava-labs/libevm/common/bitutil" +"github.com/ava-labs/libevm/common/compiler" +"github.com/ava-labs/libevm/common/hexutil" +"github.com/ava-labs/libevm/common/lru" +"github.com/ava-labs/libevm/common/math" +"github.com/ava-labs/libevm/common/prque" +"github.com/ava-labs/libevm/core/asm" +"github.com/ava-labs/libevm/core/vm" +"github.com/ava-labs/libevm/crypto" +"github.com/ava-labs/libevm/crypto/blake2b" +"github.com/ava-labs/libevm/crypto/bls12381" +"github.com/ava-labs/libevm/crypto/bn256" +"github.com/ava-labs/libevm/crypto/kzg4844" +"github.com/ava-labs/libevm/eth/tracers/js" +"github.com/ava-labs/libevm/eth/tracers/logger" +"github.com/ava-labs/libevm/eth/tracers/native" +"github.com/ava-labs/libevm/ethdb" +"github.com/ava-labs/libevm/ethdb/leveldb" +"github.com/ava-labs/libevm/ethdb/memorydb" +"github.com/ava-labs/libevm/ethdb/pebble" +"github.com/ava-labs/libevm/event" +"github.com/ava-labs/libevm/libevm" +"github.com/ava-labs/libevm/libevm/legacy" +"github.com/ava-labs/libevm/libevm/stateconf" +"github.com/ava-labs/libevm/log" +"github.com/ava-labs/libevm/params" +"github.com/ava-labs/libevm/metrics" +"github.com/ava-labs/libevm/rlp" +"github.com/ava-labs/libevm/trie" +"github.com/ava-labs/libevm/trie/testutil" +"github.com/ava-labs/libevm/trie/trienode" +"github.com/ava-labs/libevm/trie/triestate" +"github.com/ava-labs/libevm/trie/utils" +"github.com/ava-labs/libevm/triedb" +"github.com/ava-labs/libevm/triedb/database" \ No newline at end of file diff --git a/scripts/lint_allowed_eth_imports.sh b/scripts/lint_allowed_eth_imports.sh index 4580505b46..b4345363f7 100755 --- a/scripts/lint_allowed_eth_imports.sh +++ b/scripts/lint_allowed_eth_imports.sh @@ -9,9 +9,9 @@ set -o pipefail # 2. Ignore lines that import libevm with a named import starting with "eth" # 3. Sort the unique results # 4. Print out the difference between the search results and the list of specified allowed package imports from libevm. -libevm_regexp='"github.com/ethereum/go-ethereum/.*"' +libevm_regexp='"github.com/ava-labs/libevm/.*"' allow_named_imports='eth\w\+ "' -extra_imports=$(grep -r --include='*.go' --exclude=mocks.go "${libevm_regexp}" -h | grep -v "${allow_named_imports}" | grep -o "${libevm_regexp}" | sort -u | comm -23 - ./scripts/eth-allowed-packages.txt) +extra_imports=$(find . -type f \( -name "*.go" \) ! -path "./core/main_test.go" -exec grep -o -h '"github.com/ava-labs/libevm/.*"' {} + | sort -u | comm -23 - ./scripts/geth-allowed-packages.txt) if [ -n "${extra_imports}" ]; then echo "new ethereum imports should be added to ./scripts/eth-allowed-packages.txt to prevent accidental imports:" echo "${extra_imports}" diff --git a/signer/core/apitypes/types.go b/signer/core/apitypes/types.go index 9f85e9ce7e..8ea190cbb5 100644 --- a/signer/core/apitypes/types.go +++ b/signer/core/apitypes/types.go @@ -33,8 +33,8 @@ import ( "strings" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" ) type ValidationInfo struct { diff --git a/sync/client/client.go b/sync/client/client.go index 1d8b95d64a..6a1348679e 100644 --- a/sync/client/client.go +++ b/sync/client/client.go @@ -19,16 +19,16 @@ import ( "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/version" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/log" "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/peer" "github.com/ava-labs/coreth/plugin/evm/message" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/trie" ) const ( diff --git a/sync/client/client_test.go b/sync/client/client_test.go index efe92d454e..70c7f6f118 100644 --- a/sync/client/client_test.go +++ b/sync/client/client_test.go @@ -25,9 +25,9 @@ import ( "github.com/ava-labs/coreth/sync/handlers" handlerstats "github.com/ava-labs/coreth/sync/handlers/stats" "github.com/ava-labs/coreth/sync/syncutils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/triedb" ) func TestGetCode(t *testing.T) { diff --git a/sync/client/leaf_syncer.go b/sync/client/leaf_syncer.go index 2ca82b7560..db59bb305e 100644 --- a/sync/client/leaf_syncer.go +++ b/sync/client/leaf_syncer.go @@ -11,8 +11,8 @@ import ( "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" "golang.org/x/sync/errgroup" ) diff --git a/sync/client/mock_client.go b/sync/client/mock_client.go index 038bdf73bf..2d2b5180f7 100644 --- a/sync/client/mock_client.go +++ b/sync/client/mock_client.go @@ -13,8 +13,8 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/sync/handlers" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/rlp" ) var ( diff --git a/sync/client/stats/stats.go b/sync/client/stats/stats.go index 0bd47ce96d..2be86a1d16 100644 --- a/sync/client/stats/stats.go +++ b/sync/client/stats/stats.go @@ -8,7 +8,7 @@ import ( "time" "github.com/ava-labs/coreth/plugin/evm/message" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/metrics" ) var ( diff --git a/sync/handlers/block_request.go b/sync/handlers/block_request.go index 2bbb21b012..1bbad650ad 100644 --- a/sync/handlers/block_request.go +++ b/sync/handlers/block_request.go @@ -14,8 +14,8 @@ import ( "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/sync/handlers/stats" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" ) const ( diff --git a/sync/handlers/block_request_test.go b/sync/handlers/block_request_test.go index ed1f6c5dc0..bd9bf8ce4f 100644 --- a/sync/handlers/block_request_test.go +++ b/sync/handlers/block_request_test.go @@ -17,10 +17,10 @@ import ( "github.com/ava-labs/coreth/params" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/sync/handlers/stats" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/triedb" "github.com/stretchr/testify/assert" ) diff --git a/sync/handlers/code_request.go b/sync/handlers/code_request.go index b756507f75..5f0b3ee59d 100644 --- a/sync/handlers/code_request.go +++ b/sync/handlers/code_request.go @@ -13,9 +13,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/sync/handlers/stats" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" ) // CodeRequestHandler is a peer.RequestHandler for message.CodeRequest diff --git a/sync/handlers/code_request_test.go b/sync/handlers/code_request_test.go index 1bf5bd5223..13c9306ac9 100644 --- a/sync/handlers/code_request_test.go +++ b/sync/handlers/code_request_test.go @@ -14,9 +14,9 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/sync/handlers/stats" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb/memorydb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/ethdb/memorydb" "github.com/stretchr/testify/assert" ) diff --git a/sync/handlers/handler.go b/sync/handlers/handler.go index 71bff519de..eece20e4d0 100644 --- a/sync/handlers/handler.go +++ b/sync/handlers/handler.go @@ -6,7 +6,7 @@ package handlers import ( "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) type BlockProvider interface { diff --git a/sync/handlers/leafs_request.go b/sync/handlers/leafs_request.go index b6c1316944..c9df10ef10 100644 --- a/sync/handlers/leafs_request.go +++ b/sync/handlers/leafs_request.go @@ -19,12 +19,12 @@ import ( "github.com/ava-labs/coreth/sync/handlers/stats" "github.com/ava-labs/coreth/sync/syncutils" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethdb/memorydb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/ethdb/memorydb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/triedb" ) const ( diff --git a/sync/handlers/leafs_request_test.go b/sync/handlers/leafs_request_test.go index bc7e19b324..a98f398cb4 100644 --- a/sync/handlers/leafs_request_test.go +++ b/sync/handlers/leafs_request_test.go @@ -16,11 +16,11 @@ import ( "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/sync/handlers/stats" "github.com/ava-labs/coreth/sync/syncutils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/triedb" "github.com/stretchr/testify/assert" ) diff --git a/sync/handlers/stats/stats.go b/sync/handlers/stats/stats.go index d6e3271911..0d1171b82b 100644 --- a/sync/handlers/stats/stats.go +++ b/sync/handlers/stats/stats.go @@ -6,7 +6,7 @@ package stats import ( "time" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/metrics" ) // HandlerStats reports prometheus metrics for the state sync handlers diff --git a/sync/handlers/test_providers.go b/sync/handlers/test_providers.go index 81dafbfd00..a16410d71a 100644 --- a/sync/handlers/test_providers.go +++ b/sync/handlers/test_providers.go @@ -6,7 +6,7 @@ package handlers import ( "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) var ( diff --git a/sync/statesync/code_syncer.go b/sync/statesync/code_syncer.go index 97164b2658..196fefea58 100644 --- a/sync/statesync/code_syncer.go +++ b/sync/statesync/code_syncer.go @@ -14,8 +14,8 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/plugin/evm/message" statesyncclient "github.com/ava-labs/coreth/sync/client" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" ) const ( diff --git a/sync/statesync/code_syncer_test.go b/sync/statesync/code_syncer_test.go index 574290e286..c1741760d4 100644 --- a/sync/statesync/code_syncer_test.go +++ b/sync/statesync/code_syncer_test.go @@ -14,9 +14,9 @@ import ( statesyncclient "github.com/ava-labs/coreth/sync/client" "github.com/ava-labs/coreth/sync/handlers" handlerstats "github.com/ava-labs/coreth/sync/handlers/stats" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb/memorydb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/ethdb/memorydb" "github.com/stretchr/testify/assert" ) diff --git a/sync/statesync/state_syncer.go b/sync/statesync/state_syncer.go index 7f3e70c7a6..d2f3159e27 100644 --- a/sync/statesync/state_syncer.go +++ b/sync/statesync/state_syncer.go @@ -10,9 +10,9 @@ import ( "github.com/ava-labs/coreth/core/state/snapshot" syncclient "github.com/ava-labs/coreth/sync/client" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/triedb" "golang.org/x/sync/errgroup" ) diff --git a/sync/statesync/sync_helpers.go b/sync/statesync/sync_helpers.go index f4590024f6..22874b0017 100644 --- a/sync/statesync/sync_helpers.go +++ b/sync/statesync/sync_helpers.go @@ -6,9 +6,9 @@ package statesync import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/trie" ) // writeAccountSnapshot stores the account represented by [acc] to the snapshot at [accHash], using diff --git a/sync/statesync/sync_test.go b/sync/statesync/sync_test.go index 8a099bc0db..14a096a7fd 100644 --- a/sync/statesync/sync_test.go +++ b/sync/statesync/sync_test.go @@ -21,12 +21,12 @@ import ( "github.com/ava-labs/coreth/sync/handlers" handlerstats "github.com/ava-labs/coreth/sync/handlers/stats" "github.com/ava-labs/coreth/sync/syncutils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/triedb" "github.com/stretchr/testify/assert" ) diff --git a/sync/statesync/test_sync.go b/sync/statesync/test_sync.go index 1495813d2c..e3083e3484 100644 --- a/sync/statesync/test_sync.go +++ b/sync/statesync/test_sync.go @@ -12,11 +12,11 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/sync/syncutils" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/triedb" "github.com/stretchr/testify/assert" ) diff --git a/sync/statesync/trie_queue.go b/sync/statesync/trie_queue.go index 3ec7c87a49..3c8f3abf23 100644 --- a/sync/statesync/trie_queue.go +++ b/sync/statesync/trie_queue.go @@ -5,8 +5,8 @@ package statesync import ( "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" ) // trieQueue persists storage trie roots with their associated diff --git a/sync/statesync/trie_segments.go b/sync/statesync/trie_segments.go index 637d8e66a8..d0665ace9e 100644 --- a/sync/statesync/trie_segments.go +++ b/sync/statesync/trie_segments.go @@ -15,10 +15,10 @@ import ( "github.com/ava-labs/coreth/plugin/evm/message" syncclient "github.com/ava-labs/coreth/sync/client" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/trie" ) var ( diff --git a/sync/statesync/trie_sync_stats.go b/sync/statesync/trie_sync_stats.go index 4cc6a0c5b2..b0e80041f1 100644 --- a/sync/statesync/trie_sync_stats.go +++ b/sync/statesync/trie_sync_stats.go @@ -10,9 +10,9 @@ import ( utils_math "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/timer" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/metrics" ) const ( diff --git a/sync/statesync/trie_sync_stats_test.go b/sync/statesync/trie_sync_stats_test.go index 1d01cd29ec..e2c1b0c340 100644 --- a/sync/statesync/trie_sync_stats_test.go +++ b/sync/statesync/trie_sync_stats_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/metrics" "github.com/stretchr/testify/require" ) diff --git a/sync/statesync/trie_sync_tasks.go b/sync/statesync/trie_sync_tasks.go index c691d82595..a0c4d4845f 100644 --- a/sync/statesync/trie_sync_tasks.go +++ b/sync/statesync/trie_sync_tasks.go @@ -9,11 +9,11 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/sync/syncutils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie" ) var ( diff --git a/sync/syncutils/iterators.go b/sync/syncutils/iterators.go index 2ae6bfcc80..c15409d96e 100644 --- a/sync/syncutils/iterators.go +++ b/sync/syncutils/iterators.go @@ -6,7 +6,7 @@ package syncutils import ( "github.com/ava-labs/coreth/core/state/snapshot" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/ethdb" + "github.com/ava-labs/libevm/ethdb" ) var ( diff --git a/sync/syncutils/test_trie.go b/sync/syncutils/test_trie.go index eb4e2c6a11..c244d7bb1c 100644 --- a/sync/syncutils/test_trie.go +++ b/sync/syncutils/test_trie.go @@ -12,14 +12,14 @@ import ( "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/trie/trienode" - "github.com/ethereum/go-ethereum/triedb" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/trie/trienode" + "github.com/ava-labs/libevm/triedb" "github.com/holiman/uint256" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/rlp" "github.com/stretchr/testify/assert" ) diff --git a/tests/rlp_test_util.go b/tests/rlp_test_util.go index 5af235bc5a..b5df73438e 100644 --- a/tests/rlp_test_util.go +++ b/tests/rlp_test_util.go @@ -34,7 +34,7 @@ import ( "math/big" "strings" - "github.com/ethereum/go-ethereum/rlp" + "github.com/ava-labs/libevm/rlp" ) // RLPTest is the JSON structure of a single RLP test. diff --git a/triedb/hashdb/database.go b/triedb/hashdb/database.go index 28e72deda9..1a2e975074 100644 --- a/triedb/hashdb/database.go +++ b/triedb/hashdb/database.go @@ -35,19 +35,17 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ava-labs/coreth/trie/trienode" - "github.com/ava-labs/coreth/trie/triestate" "github.com/ava-labs/coreth/utils" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/metrics" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" - "github.com/ethereum/go-ethereum/trie/trienode" - "github.com/ethereum/go-ethereum/trie/triestate" - "github.com/ethereum/go-ethereum/triedb" - "github.com/ethereum/go-ethereum/triedb/database" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/metrics" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie" + "github.com/ava-labs/libevm/trie/trienode" + "github.com/ava-labs/libevm/trie/triestate" + "github.com/ava-labs/libevm/triedb" + "github.com/ava-labs/libevm/triedb/database" ) const ( diff --git a/triedb/pathdb/database.go b/triedb/pathdb/database.go index 6743ad1092..c38c54fca8 100644 --- a/triedb/pathdb/database.go +++ b/triedb/pathdb/database.go @@ -35,13 +35,13 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/params" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/trie/trienode" - "github.com/ethereum/go-ethereum/trie/triestate" - "github.com/ethereum/go-ethereum/triedb" - "github.com/ethereum/go-ethereum/triedb/database" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/trie/trienode" + "github.com/ava-labs/libevm/trie/triestate" + "github.com/ava-labs/libevm/triedb" + "github.com/ava-labs/libevm/triedb/database" ) const ( diff --git a/triedb/pathdb/database_test.go b/triedb/pathdb/database_test.go index 750d56ab1a..bf1934c97b 100644 --- a/triedb/pathdb/database_test.go +++ b/triedb/pathdb/database_test.go @@ -35,12 +35,12 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie/testutil" - "github.com/ethereum/go-ethereum/trie/trienode" - "github.com/ethereum/go-ethereum/trie/triestate" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie/testutil" + "github.com/ava-labs/libevm/trie/trienode" + "github.com/ava-labs/libevm/trie/triestate" "github.com/holiman/uint256" "github.com/stretchr/testify/require" ) diff --git a/triedb/pathdb/difflayer.go b/triedb/pathdb/difflayer.go index 47081a29a6..eea8dc4126 100644 --- a/triedb/pathdb/difflayer.go +++ b/triedb/pathdb/difflayer.go @@ -30,10 +30,10 @@ import ( "fmt" "sync" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/trie/trienode" - "github.com/ethereum/go-ethereum/trie/triestate" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/trie/trienode" + "github.com/ava-labs/libevm/trie/triestate" ) // diffLayer represents a collection of modifications made to the in-memory tries diff --git a/triedb/pathdb/difflayer_test.go b/triedb/pathdb/difflayer_test.go index 6f1a648392..d7f975ffad 100644 --- a/triedb/pathdb/difflayer_test.go +++ b/triedb/pathdb/difflayer_test.go @@ -31,9 +31,9 @@ import ( "testing" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/trie/testutil" - "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/trie/testutil" + "github.com/ava-labs/libevm/trie/trienode" ) func emptyLayer() *diskLayer { diff --git a/triedb/pathdb/disklayer.go b/triedb/pathdb/disklayer.go index 53bda1a01f..c13b46e710 100644 --- a/triedb/pathdb/disklayer.go +++ b/triedb/pathdb/disklayer.go @@ -33,11 +33,11 @@ import ( "github.com/VictoriaMetrics/fastcache" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/trie/trienode" - "github.com/ethereum/go-ethereum/trie/triestate" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/trie/trienode" + "github.com/ava-labs/libevm/trie/triestate" "golang.org/x/crypto/sha3" ) diff --git a/triedb/pathdb/errors.go b/triedb/pathdb/errors.go index af6e3464d2..6186091e30 100644 --- a/triedb/pathdb/errors.go +++ b/triedb/pathdb/errors.go @@ -30,8 +30,8 @@ import ( "errors" "fmt" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/common/hexutil" ) var ( diff --git a/triedb/pathdb/history.go b/triedb/pathdb/history.go index 6f937dfb90..14e53383a3 100644 --- a/triedb/pathdb/history.go +++ b/triedb/pathdb/history.go @@ -32,8 +32,8 @@ import ( "errors" "fmt" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/trie/triestate" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/trie/triestate" "golang.org/x/exp/slices" ) diff --git a/triedb/pathdb/history_test.go b/triedb/pathdb/history_test.go index fdeaccd2af..4d30831c81 100644 --- a/triedb/pathdb/history_test.go +++ b/triedb/pathdb/history_test.go @@ -32,10 +32,10 @@ import ( "testing" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie/testutil" - "github.com/ethereum/go-ethereum/trie/triestate" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie/testutil" + "github.com/ava-labs/libevm/trie/triestate" ) // randomStateSet generates a random state change set. diff --git a/triedb/pathdb/journal.go b/triedb/pathdb/journal.go index 9d63de40ab..a245e7f8c3 100644 --- a/triedb/pathdb/journal.go +++ b/triedb/pathdb/journal.go @@ -35,12 +35,12 @@ import ( "github.com/ava-labs/coreth/core/rawdb" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie/trienode" - "github.com/ethereum/go-ethereum/trie/triestate" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/rlp" + "github.com/ava-labs/libevm/trie/trienode" + "github.com/ava-labs/libevm/trie/triestate" ) var ( diff --git a/triedb/pathdb/layertree.go b/triedb/pathdb/layertree.go index f52d879390..a52eded0f6 100644 --- a/triedb/pathdb/layertree.go +++ b/triedb/pathdb/layertree.go @@ -32,9 +32,9 @@ import ( "sync" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/trie/trienode" - "github.com/ethereum/go-ethereum/trie/triestate" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/trie/trienode" + "github.com/ava-labs/libevm/trie/triestate" ) // layerTree is a group of state layers identified by the state root. diff --git a/triedb/pathdb/metrics.go b/triedb/pathdb/metrics.go index e2df1ca156..21038ecfc6 100644 --- a/triedb/pathdb/metrics.go +++ b/triedb/pathdb/metrics.go @@ -26,7 +26,7 @@ package pathdb -import "github.com/ethereum/go-ethereum/metrics" +import "github.com/ava-labs/libevm/metrics" // nolint: unused var ( diff --git a/triedb/pathdb/nodebuffer.go b/triedb/pathdb/nodebuffer.go index cf493ca69c..7a461b60ad 100644 --- a/triedb/pathdb/nodebuffer.go +++ b/triedb/pathdb/nodebuffer.go @@ -32,11 +32,11 @@ import ( "github.com/VictoriaMetrics/fastcache" "github.com/ava-labs/coreth/core/rawdb" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/trie/trienode" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/ethdb" + "github.com/ava-labs/libevm/log" + "github.com/ava-labs/libevm/trie/trienode" ) // nodebuffer is a collection of modified trie nodes to aggregate the disk diff --git a/triedb/pathdb/testutils.go b/triedb/pathdb/testutils.go index a3023e607c..a7ada9947e 100644 --- a/triedb/pathdb/testutils.go +++ b/triedb/pathdb/testutils.go @@ -31,10 +31,10 @@ import ( "fmt" "github.com/ava-labs/coreth/core/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/trie/trienode" - "github.com/ethereum/go-ethereum/trie/triestate" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" + "github.com/ava-labs/libevm/trie/trienode" + "github.com/ava-labs/libevm/trie/triestate" "golang.org/x/exp/slices" ) diff --git a/utils/address_range.go b/utils/address_range.go index 940c39e8a1..a10794f03d 100644 --- a/utils/address_range.go +++ b/utils/address_range.go @@ -6,7 +6,7 @@ package utils import ( "bytes" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" ) // AddressRange represents a continuous range of addresses diff --git a/utils/bytes.go b/utils/bytes.go index 54258b20f4..86382cf156 100644 --- a/utils/bytes.go +++ b/utils/bytes.go @@ -3,7 +3,7 @@ package utils -import "github.com/ethereum/go-ethereum/common" +import "github.com/ava-labs/libevm/common" // IncrOne increments bytes value by one func IncrOne(bytes []byte) { diff --git a/utils/bytes_test.go b/utils/bytes_test.go index b1bbc8fa6b..7b4fc9d05c 100644 --- a/utils/bytes_test.go +++ b/utils/bytes_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/ava-labs/avalanchego/utils" - "github.com/ethereum/go-ethereum/common" + "github.com/ava-labs/libevm/common" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/utils/key.go b/utils/key.go index a6515af062..ab4db85b94 100644 --- a/utils/key.go +++ b/utils/key.go @@ -7,8 +7,8 @@ import ( "crypto/ecdsa" "io" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "github.com/ava-labs/libevm/common" + "github.com/ava-labs/libevm/crypto" ) type Key struct { diff --git a/utils/metered_cache.go b/utils/metered_cache.go index dfaeac7cca..ee1807e36f 100644 --- a/utils/metered_cache.go +++ b/utils/metered_cache.go @@ -9,7 +9,7 @@ import ( "time" "github.com/VictoriaMetrics/fastcache" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/metrics" ) // MeteredCache wraps *fastcache.Cache and periodically pulls stats from it. diff --git a/vmerrs/vmerrs.go b/vmerrs/vmerrs.go index 9f64349f2f..26a3dbd967 100644 --- a/vmerrs/vmerrs.go +++ b/vmerrs/vmerrs.go @@ -29,7 +29,7 @@ package vmerrs import ( "errors" - "github.com/ethereum/go-ethereum/core/vm" + "github.com/ava-labs/libevm/core/vm" ) // List evm execution errors diff --git a/warp/aggregator/aggregator.go b/warp/aggregator/aggregator.go index 9c6c3aa322..9cc66fae38 100644 --- a/warp/aggregator/aggregator.go +++ b/warp/aggregator/aggregator.go @@ -7,7 +7,7 @@ import ( "context" "fmt" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/set" diff --git a/warp/backend.go b/warp/backend.go index d35c96b8fb..77167f3fd8 100644 --- a/warp/backend.go +++ b/warp/backend.go @@ -15,7 +15,7 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowman" avalancheWarp "github.com/ava-labs/avalanchego/vms/platformvm/warp" "github.com/ava-labs/avalanchego/vms/platformvm/warp/payload" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" ) var ( diff --git a/warp/client.go b/warp/client.go index 90633d6b47..55d99621a4 100644 --- a/warp/client.go +++ b/warp/client.go @@ -9,7 +9,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/coreth/rpc" - "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ava-labs/libevm/common/hexutil" ) var _ Client = (*client)(nil) diff --git a/warp/handlers/signature_request.go b/warp/handlers/signature_request.go index bb9c2c7855..9a5dbfd77f 100644 --- a/warp/handlers/signature_request.go +++ b/warp/handlers/signature_request.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/coreth/plugin/evm/message" "github.com/ava-labs/coreth/warp" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/log" ) // SignatureRequestHandler serves warp signature requests. It is a peer.RequestHandler for message.MessageSignatureRequest. diff --git a/warp/handlers/stats.go b/warp/handlers/stats.go index d81bce0e02..6a56d54076 100644 --- a/warp/handlers/stats.go +++ b/warp/handlers/stats.go @@ -6,7 +6,7 @@ package handlers import ( "time" - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/metrics" ) type handlerStats struct { diff --git a/warp/service.go b/warp/service.go index 01123950ff..6b16354a70 100644 --- a/warp/service.go +++ b/warp/service.go @@ -15,8 +15,8 @@ import ( "github.com/ava-labs/coreth/peer" "github.com/ava-labs/coreth/warp/aggregator" warpValidators "github.com/ava-labs/coreth/warp/validators" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/log" + "github.com/ava-labs/libevm/common/hexutil" + "github.com/ava-labs/libevm/log" ) var errNoValidators = errors.New("cannot aggregate signatures from subnet with no validators") diff --git a/warp/verifier_stats.go b/warp/verifier_stats.go index a092751e8b..6a47c31397 100644 --- a/warp/verifier_stats.go +++ b/warp/verifier_stats.go @@ -4,7 +4,7 @@ package warp import ( - "github.com/ethereum/go-ethereum/metrics" + "github.com/ava-labs/libevm/metrics" ) type verifierStats struct { From 57e5037a445eb91bd16af0469df15a7b2f22e039 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 18 Feb 2025 17:59:29 -0800 Subject: [PATCH 62/69] fix leftover --- metrics/json_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/metrics/json_test.go b/metrics/json_test.go index f91fe8cfa5..811bc29f11 100644 --- a/metrics/json_test.go +++ b/metrics/json_test.go @@ -13,7 +13,7 @@ func TestRegistryMarshallJSON(t *testing.T) { r.Register("counter", NewCounter()) enc.Encode(r) if s := b.String(); s != "{\"counter\":{\"count\":0}}\n" { - t.Fatalf(s) + t.Fatal(s) } } From e4b8c7b53a879668fc2910e0402d19762383fcf0 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 18 Feb 2025 18:08:39 -0800 Subject: [PATCH 63/69] bump avalanchego to branch --- go.mod | 4 +--- go.sum | 2 ++ scripts/versions.sh | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 934a689b05..ac07b891e9 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.23.6 require ( github.com/VictoriaMetrics/fastcache v1.12.1 - github.com/ava-labs/avalanchego v1.12.1-0.20250107220127-32f58b4fa9c8 + github.com/ava-labs/avalanchego v1.12.3-0.20250219020546-daac8c8bbd8c github.com/ava-labs/libevm v1.13.14-0.2.0.rc.3 github.com/crate-crypto/go-ipa v0.0.0-20231025140028-3c0104f4b233 github.com/davecgh/go-spew v1.1.1 @@ -134,5 +134,3 @@ require ( gopkg.in/yaml.v3 v3.0.1 // indirect rsc.io/tmplfunc v0.0.3 // indirect ) - -replace github.com/ava-labs/avalanchego => ../avalanchego diff --git a/go.sum b/go.sum index 84ca681ff7..77c1af95c0 100644 --- a/go.sum +++ b/go.sum @@ -56,6 +56,8 @@ github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156 h1:eMwmnE/GDgah4HI848JfFxHt+iPb26b4zyfspmqY0/8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/ava-labs/avalanchego v1.12.3-0.20250219020546-daac8c8bbd8c h1:LAKh2eokSOtM5TRiMtGnl+vaTJa72dL/i/ZitSMR23w= +github.com/ava-labs/avalanchego v1.12.3-0.20250219020546-daac8c8bbd8c/go.mod h1:5e246cVO15EOZp7q3Dx2wRznTXMUgLrbWgnAd1RNgKU= github.com/ava-labs/libevm v1.13.14-0.2.0.rc.3 h1:1CWGo2icnX9dRqGQl7CFywYGIZWxe+ucy0w8NAsVTWE= github.com/ava-labs/libevm v1.13.14-0.2.0.rc.3/go.mod h1:+Iol+sVQ1KyoBsHf3veyrBmHCXr3xXRWq6ZXkgVfNLU= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= diff --git a/scripts/versions.sh b/scripts/versions.sh index 5eed0c55ef..0df617e7e3 100644 --- a/scripts/versions.sh +++ b/scripts/versions.sh @@ -6,4 +6,4 @@ set -euo pipefail # Don't export them as they're used in the context of other calls -AVALANCHE_VERSION=${AVALANCHE_VERSION:-'32f58b4f'} +AVALANCHE_VERSION=${AVALANCHE_VERSION:-'daac8c8b'} From be988762b1424f6b3f6a9cbe19a33eeba3023219 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 18 Feb 2025 18:10:24 -0800 Subject: [PATCH 64/69] fix bad merge --- scripts/lint_allowed_eth_imports.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/lint_allowed_eth_imports.sh b/scripts/lint_allowed_eth_imports.sh index b4345363f7..88a7388760 100755 --- a/scripts/lint_allowed_eth_imports.sh +++ b/scripts/lint_allowed_eth_imports.sh @@ -11,7 +11,7 @@ set -o pipefail # 4. Print out the difference between the search results and the list of specified allowed package imports from libevm. libevm_regexp='"github.com/ava-labs/libevm/.*"' allow_named_imports='eth\w\+ "' -extra_imports=$(find . -type f \( -name "*.go" \) ! -path "./core/main_test.go" -exec grep -o -h '"github.com/ava-labs/libevm/.*"' {} + | sort -u | comm -23 - ./scripts/geth-allowed-packages.txt) +extra_imports=$(find . -type f \( -name "*.go" \) ! -path "./core/main_test.go" -exec grep -o -h '"github.com/ava-labs/libevm/.*"' {} + | sort -u | comm -23 - ./scripts/eth-allowed-packages.txt) if [ -n "${extra_imports}" ]; then echo "new ethereum imports should be added to ./scripts/eth-allowed-packages.txt to prevent accidental imports:" echo "${extra_imports}" From 63c167d2befe8f9b000c0ff437ce685417ca8cde Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 18 Feb 2025 18:11:47 -0800 Subject: [PATCH 65/69] sort eth imports --- scripts/eth-allowed-packages.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/eth-allowed-packages.txt b/scripts/eth-allowed-packages.txt index 1b77e90209..98fb94b34c 100644 --- a/scripts/eth-allowed-packages.txt +++ b/scripts/eth-allowed-packages.txt @@ -28,8 +28,8 @@ "github.com/ava-labs/libevm/libevm/legacy" "github.com/ava-labs/libevm/libevm/stateconf" "github.com/ava-labs/libevm/log" -"github.com/ava-labs/libevm/params" "github.com/ava-labs/libevm/metrics" +"github.com/ava-labs/libevm/params" "github.com/ava-labs/libevm/rlp" "github.com/ava-labs/libevm/trie" "github.com/ava-labs/libevm/trie/testutil" From 104afc2d39f3bc5f8a0c43da789ec24024775d69 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 18 Feb 2025 18:12:41 -0800 Subject: [PATCH 66/69] regen mocks --- internal/ethapi/mocks_test.go | 4 ++-- precompile/contract/mocks.go | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/internal/ethapi/mocks_test.go b/internal/ethapi/mocks_test.go index fe81d6a65c..3d46795f73 100644 --- a/internal/ethapi/mocks_test.go +++ b/internal/ethapi/mocks_test.go @@ -15,16 +15,16 @@ import ( reflect "reflect" time "time" - accounts "github.com/ava-labs/libevm/accounts" consensus "github.com/ava-labs/coreth/consensus" core "github.com/ava-labs/coreth/core" bloombits "github.com/ava-labs/coreth/core/bloombits" state "github.com/ava-labs/coreth/core/state" types "github.com/ava-labs/coreth/core/types" - vm "github.com/ava-labs/libevm/core/vm" params "github.com/ava-labs/coreth/params" rpc "github.com/ava-labs/coreth/rpc" + accounts "github.com/ava-labs/libevm/accounts" common "github.com/ava-labs/libevm/common" + vm "github.com/ava-labs/libevm/core/vm" ethdb "github.com/ava-labs/libevm/ethdb" event "github.com/ava-labs/libevm/event" gomock "go.uber.org/mock/gomock" diff --git a/precompile/contract/mocks.go b/precompile/contract/mocks.go index f9991cca78..6da91cc237 100644 --- a/precompile/contract/mocks.go +++ b/precompile/contract/mocks.go @@ -209,6 +209,7 @@ func (mr *MockStateDBMockRecorder) GetTxHash() *gomock.Call { // RevertToSnapshot mocks base method. func (m *MockStateDB) RevertToSnapshot(arg0 int) { + m.ctrl.T.Helper() m.ctrl.Call(m, "RevertToSnapshot", arg0) } @@ -231,6 +232,18 @@ func (mr *MockStateDBMockRecorder) SetNonce(arg0, arg1 any) *gomock.Call { } // SetPredicateStorageSlots mocks base method. +func (m *MockStateDB) SetPredicateStorageSlots(address common.Address, predicates [][]byte) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetPredicateStorageSlots", address, predicates) +} + +// SetPredicateStorageSlots indicates an expected call of SetPredicateStorageSlots. +func (mr *MockStateDBMockRecorder) SetPredicateStorageSlots(address, predicates any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPredicateStorageSlots", reflect.TypeOf((*MockStateDB)(nil).SetPredicateStorageSlots), address, predicates) +} + +// SetState mocks base method. func (m *MockStateDB) SetState(arg0 common.Address, arg1, arg2 common.Hash) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetState", arg0, arg1, arg2) From 0f5f211acc17d26cf2b09c875e31b1ff031117e9 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 18 Feb 2025 18:40:06 -0800 Subject: [PATCH 67/69] shell scripting --- scripts/lint_allowed_eth_imports.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/lint_allowed_eth_imports.sh b/scripts/lint_allowed_eth_imports.sh index 88a7388760..fa17b2e65f 100755 --- a/scripts/lint_allowed_eth_imports.sh +++ b/scripts/lint_allowed_eth_imports.sh @@ -11,7 +11,9 @@ set -o pipefail # 4. Print out the difference between the search results and the list of specified allowed package imports from libevm. libevm_regexp='"github.com/ava-labs/libevm/.*"' allow_named_imports='eth\w\+ "' -extra_imports=$(find . -type f \( -name "*.go" \) ! -path "./core/main_test.go" -exec grep -o -h '"github.com/ava-labs/libevm/.*"' {} + | sort -u | comm -23 - ./scripts/eth-allowed-packages.txt) +extra_imports=$(find . -type f \( -name "*.go" \) ! -path "./core/main_test.go" \ + -exec sh -c 'grep "$0" -h "$2" | grep -v "$1" | grep -o "$0"' "${libevm_regexp}" "${allow_named_imports}" {} \; | \ + sort -u | comm -23 - ./scripts/eth-allowed-packages.txt) if [ -n "${extra_imports}" ]; then echo "new ethereum imports should be added to ./scripts/eth-allowed-packages.txt to prevent accidental imports:" echo "${extra_imports}" From 0865d964a80092a2c013ce6f2947102e5af57af6 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 18 Feb 2025 19:31:19 -0800 Subject: [PATCH 68/69] patch metrics for Nil types --- metrics/prometheus/prometheus.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/metrics/prometheus/prometheus.go b/metrics/prometheus/prometheus.go index cd478e9249..30e87d81df 100644 --- a/metrics/prometheus/prometheus.go +++ b/metrics/prometheus/prometheus.go @@ -191,6 +191,13 @@ func metricFamily(registry Registry, name string) (mf *dto.MetricFamily, err err }, }}, }, nil + + case metrics.NilCounter, metrics.NilCounterFloat64, metrics.NilEWMA, + metrics.NilGauge, metrics.NilGaugeFloat64, metrics.NilGaugeInfo, + metrics.NilHealthcheck, metrics.NilHistogram, metrics.NilMeter, + metrics.NilResettingTimer, metrics.NilSample, metrics.NilTimer: + return nil, fmt.Errorf("%w: %q metric is nil", errMetricSkip, name) + default: return nil, fmt.Errorf("metric %q: type is not supported: %T", name, metric) } From 0716f4cd31097846ea34bb31a1f13363f3b1696e Mon Sep 17 00:00:00 2001 From: Quentin Mc Gaw Date: Thu, 20 Feb 2025 12:07:51 +0100 Subject: [PATCH 69/69] Move noop metrics types case to top of switch --- metrics/prometheus/prometheus.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/metrics/prometheus/prometheus.go b/metrics/prometheus/prometheus.go index 30e87d81df..7cc4e68536 100644 --- a/metrics/prometheus/prometheus.go +++ b/metrics/prometheus/prometheus.go @@ -67,6 +67,12 @@ func metricFamily(registry Registry, name string) (mf *dto.MetricFamily, err err name = strings.ReplaceAll(name, "/", "_") switch m := metric.(type) { + case metrics.NilCounter, metrics.NilCounterFloat64, metrics.NilEWMA, + metrics.NilGauge, metrics.NilGaugeFloat64, metrics.NilGaugeInfo, + metrics.NilHealthcheck, metrics.NilHistogram, metrics.NilMeter, + metrics.NilResettingTimer, metrics.NilSample, metrics.NilTimer: + return nil, fmt.Errorf("%w: %q metric is nil", errMetricSkip, name) + case metrics.Counter: return &dto.MetricFamily{ Name: &name, @@ -192,12 +198,6 @@ func metricFamily(registry Registry, name string) (mf *dto.MetricFamily, err err }}, }, nil - case metrics.NilCounter, metrics.NilCounterFloat64, metrics.NilEWMA, - metrics.NilGauge, metrics.NilGaugeFloat64, metrics.NilGaugeInfo, - metrics.NilHealthcheck, metrics.NilHistogram, metrics.NilMeter, - metrics.NilResettingTimer, metrics.NilSample, metrics.NilTimer: - return nil, fmt.Errorf("%w: %q metric is nil", errMetricSkip, name) - default: return nil, fmt.Errorf("metric %q: type is not supported: %T", name, metric) }