Skip to content

Commit

Permalink
Reduce diff with subnet-evm (ava-labs#475)
Browse files Browse the repository at this point in the history
Co-authored-by: Ceyhun Onur <ceyhun.onur@avalabs.org>
  • Loading branch information
2 people authored and oxbee committed Nov 6, 2024
1 parent d71be11 commit 037132e
Show file tree
Hide file tree
Showing 46 changed files with 236 additions and 203 deletions.
6 changes: 3 additions & 3 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# Security Policy

Avalanche takes the security of the platform and of its users very seriously. We and our community recognize the critical role of external security researchers and developers and welcome
Avalanche takes the security of the platform and of its users very seriously. We and our community recognize the critical role of external security researchers and developers and welcome
responsible disclosures. Valid reports will be eligible for a reward (terms and conditions apply).

## Reporting a Vulnerability

**Please do not file a public ticket** mentioning the vulnerability. To disclose a vulnerability submit it through our [Bug Bounty Program](https://hackenproof.com/avalanche).

Vulnerabilities must be disclosed to us privately with reasonable time to respond, and avoid compromise of other users and accounts, or loss of funds that are not your own. We do not reward spam or
social engineering vulnerabilities.
Vulnerabilities must be disclosed to us privately with reasonable time to respond, and avoid compromise of other users and accounts, or loss of funds that are not your own. We do not reward spam or
social engineering vulnerabilities.

Do not test for or validate any security issues in the live Avalanche networks (Mainnet and Fuji testnet), confirm all exploits in a local private testnet.

Expand Down
87 changes: 44 additions & 43 deletions accounts/abi/bind/bind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1758,6 +1758,7 @@ var bindTests = []struct {
key, _ := crypto.GenerateKey()
addr := crypto.PubkeyToAddress(key.PublicKey)
sim := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(1000000000000000000)}}, 1000000)
defer sim.Close()
Expand Down Expand Up @@ -1879,7 +1880,7 @@ var bindTests = []struct {
if count != 1 {
t.Fatal("Unexpected contract event number")
}
`,
`,
nil,
nil,
nil,
Expand All @@ -1889,51 +1890,51 @@ var bindTests = []struct {
{
`NewErrors`,
`
pragma solidity >0.8.4;
contract NewErrors {
error MyError(uint256);
error MyError1(uint256);
error MyError2(uint256, uint256);
error MyError3(uint256 a, uint256 b, uint256 c);
function Error() public pure {
revert MyError3(1,2,3);
}
pragma solidity >0.8.4;
contract NewErrors {
error MyError(uint256);
error MyError1(uint256);
error MyError2(uint256, uint256);
error MyError3(uint256 a, uint256 b, uint256 c);
function Error() public pure {
revert MyError3(1,2,3);
}
`,
}
`,
[]string{"0x6080604052348015600f57600080fd5b5060998061001e6000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c8063726c638214602d575b600080fd5b60336035565b005b60405163024876cd60e61b815260016004820152600260248201526003604482015260640160405180910390fdfea264697066735822122093f786a1bc60216540cd999fbb4a6109e0fef20abcff6e9107fb2817ca968f3c64736f6c63430008070033"},
[]string{`[{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"MyError","type":"error"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"MyError1","type":"error"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"MyError2","type":"error"},{"inputs":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","name":"b","type":"uint256"},{"internalType":"uint256","name":"c","type":"uint256"}],"name":"MyError3","type":"error"},{"inputs":[],"name":"Error","outputs":[],"stateMutability":"pure","type":"function"}]`},
`
"math/big"
"github.com/ava-labs/coreth/accounts/abi/bind"
"github.com/ava-labs/coreth/accounts/abi/bind/backends"
"github.com/ava-labs/coreth/core"
"github.com/ethereum/go-ethereum/crypto"
`,
`
var (
key, _ = crypto.GenerateKey()
user, _ = bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
sim = backends.NewSimulatedBackend(core.GenesisAlloc{user.From: {Balance: big.NewInt(1000000000000000000)}}, 10000000)
)
defer sim.Close()
_, tx, contract, err := DeployNewErrors(user, sim)
if err != nil {
t.Fatal(err)
}
sim.Commit(true)
_, err = bind.WaitDeployed(nil, sim, tx)
if err != nil {
t.Error(err)
}
if err := contract.Error(new(bind.CallOpts)); err == nil {
t.Fatalf("expected contract to throw error")
}
// TODO (MariusVanDerWijden unpack error using abigen
// once that is implemented
`,
"math/big"
"github.com/ava-labs/coreth/accounts/abi/bind"
"github.com/ava-labs/coreth/accounts/abi/bind/backends"
"github.com/ava-labs/coreth/core"
"github.com/ethereum/go-ethereum/crypto"
`,
`
var (
key, _ = crypto.GenerateKey()
user, _ = bind.NewKeyedTransactorWithChainID(key, big.NewInt(1337))
sim = backends.NewSimulatedBackend(core.GenesisAlloc{user.From: {Balance: big.NewInt(1000000000000000000)}}, 10000000)
)
defer sim.Close()
_, tx, contract, err := DeployNewErrors(user, sim)
if err != nil {
t.Fatal(err)
}
sim.Commit(true)
_, err = bind.WaitDeployed(nil, sim, tx)
if err != nil {
t.Error(err)
}
if err := contract.Error(new(bind.CallOpts)); err == nil {
t.Fatalf("expected contract to throw error")
}
// TODO (MariusVanDerWijden unpack error using abigen
// once that is implemented
`,
nil,
nil,
nil,
Expand Down Expand Up @@ -2172,7 +2173,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)
}
tidier := exec.Command(gocmd, "mod", "tidy", "-compat=1.19")
tidier := exec.Command(gocmd, "mod", "tidy", "-compat=1.20")
tidier.Dir = pkg
if out, err := tidier.CombinedOutput(); err != nil {
t.Fatalf("failed to tidy Go module file: %v\n%s", err, out)
Expand Down
2 changes: 1 addition & 1 deletion accounts/keystore/account_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ var (
}
)

// waitWatcherStarts waits up to 1s for the keystore watcher to start.
// waitWatcherStart waits up to 1s for the keystore watcher to start.
func waitWatcherStart(ks *KeyStore) bool {
// On systems where file watch is not supported, just return "ok".
if !ks.cache.watcher.enabled() {
Expand Down
2 changes: 1 addition & 1 deletion consensus/dummy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ The dummy consensus engine is responsible for performing verification on the hea

As of Apricot Phase 3, the C-Chain includes a dynamic fee algorithm based off of (EIP-1559)[https://eips.ethereum.org/EIPS/eip-1559]. This introduces a field to the block type called `BaseFee`. The Base Fee sets a minimum gas price for any transaction to be included in the block. For example, a transaction with a gas price of 49 gwei, will be invalid to include in a block with a base fee of 50 gwei.

The dynamic fee algorithm aims to adjust the base fee to handle network congestion. Coreth sets a target utilization on the network, and the dynamic fee algorithm adjusts the base fee accordingly. If the network operates above the target utilization, the dynamic fee algorithm will increase the base fee to make utilizing he network more expensive and bring overall utilization down. If the network operates below the target utilization, the dynamic fee algorithm will decrease the base fee to make it cheaper to use the network.
The dynamic fee algorithm aims to adjust the base fee to handle network congestion. Coreth sets a target utilization on the network, and the dynamic fee algorithm adjusts the base fee accordingly. If the network operates above the target utilization, the dynamic fee algorithm will increase the base fee to make utilizing the network more expensive and bring overall utilization down. If the network operates below the target utilization, the dynamic fee algorithm will decrease the base fee to make it cheaper to use the network.

- 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
Expand Down
6 changes: 4 additions & 2 deletions consensus/dummy/consensus.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,16 +206,17 @@ func (self *DummyEngine) verifyHeader(chain consensus.ChainHeaderReader, header
return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
}
}

// Ensure gas-related header fields are correct
if err := self.verifyHeaderGasFields(config, header, parent); err != nil {
return err
}

// Verify the header's timestamp
if header.Time > uint64(time.Now().Add(allowedFutureBlockTime).Unix()) {
return consensus.ErrFutureBlock
}
// if header.Time <= parent.Time {
// Verify the header's timestamp is not earlier than parent's
// it does include equality(==), so multiple blocks per second is ok
if header.Time < parent.Time {
return errInvalidBlockTime
}
Expand Down Expand Up @@ -315,6 +316,7 @@ func (self *DummyEngine) verifyBlockFee(
// Minimum Fee = 10 gwei * 1M gas (minimum fee that would have been accepted for this transaction)
// Fee Premium = 90 gwei
// Total Overpaid = 90 gwei * 1M gas

blockFeeContribution.Mul(txFeePremium, gasUsed.SetUint64(receipt.GasUsed))
totalBlockFee.Add(totalBlockFee, blockFeeContribution)
}
Expand Down
3 changes: 2 additions & 1 deletion consensus/dummy/dynamic_fees_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ type test struct {

func TestDynamicFees(t *testing.T) {
spacedTimestamps := []uint64{1, 1, 2, 5, 15, 120}

var tests []test = []test{
// Test minimal gas usage
{
Expand Down Expand Up @@ -276,7 +277,7 @@ func TestSelectBigWithinBounds(t *testing.T) {
lower, value, upper, expected *big.Int
}

var tests = map[string]test{
tests := map[string]test{
"value within bounds": {
lower: big.NewInt(0),
value: big.NewInt(5),
Expand Down
2 changes: 1 addition & 1 deletion core/bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func genValueTx(nbytes int) func(int, *BlockGen) {
return func(i int, gen *BlockGen) {
toaddr := common.Address{}
data := make([]byte, nbytes)
gas, _ := IntrinsicGas(data, nil, false, params.Rules{})
gas, _ := IntrinsicGas(data, nil, false, params.Rules{}) // Disable Istanbul and EIP-2028 for this test
signer := types.MakeSigner(gen.config, big.NewInt(int64(i)), gen.header.Time)
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(benchRootAddr), toaddr, big.NewInt(1), gas, big.NewInt(225000000000), data), signer, benchRootKey)
gen.AddTx(tx)
Expand Down
4 changes: 2 additions & 2 deletions core/evm.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ func NewEVMBlockContext(header *types.Header, chain ChainContext, author *common
if !ok {
return newEVMBlockContext(header, chain, author, nil)
}
// Prior to the Durango, the VM enforces the extra data is smaller than or
// equal to this size. After the Durango, the VM pre-verifies the extra
// Prior to Durango, the VM enforces the extra data is smaller than or
// equal to this size. After Durango, the VM pre-verifies the extra
// data past the dynamic fee rollup window is valid.
predicateResults, err := predicate.ParseResults(predicateBytes)
if err != nil {
Expand Down
4 changes: 4 additions & 0 deletions core/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@ func (e *GenesisMismatchError) Error() string {
// +------------------------------------------
// db has no genesis | main-net default | genesis
// db has genesis | from DB | genesis (if compatible)

// The argument [genesis] must be specified and must contain a valid chain config.
// If the genesis block has already been set up, then we verify the hash matches the genesis passed in
// and that the chain config contained in genesis is backwards compatible with what is stored in the database.
//
// The stored chain configuration will be updated if it is compatible (i.e. does not
// specify a fork block below the local head block). In case of a conflict, the
Expand Down
1 change: 0 additions & 1 deletion core/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,6 @@ func TestSetupGenesis(t *testing.T) {
// regression test for precompile activation after header block
func TestNetworkUpgradeBetweenHeadAndAcceptedBlock(t *testing.T) {
db := rawdb.NewMemoryDatabase()

customg := Genesis{
Config: params.TestApricotPhase1Config,
Alloc: GenesisAlloc{
Expand Down
4 changes: 1 addition & 3 deletions core/rawdb/freezer_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@

package rawdb

import (
"errors"
)
import "errors"

var (
// errNotSupported is returned if the database doesn't support the required operation.
Expand Down
2 changes: 1 addition & 1 deletion core/txpool/txpool.go
Original file line number Diff line number Diff line change
Expand Up @@ -1127,7 +1127,7 @@ func (pool *TxPool) addTxs(txs []*types.Transaction, local, sync bool) []error {
newErrs, dirtyAddrs := pool.addTxsLocked(news, local)
pool.mu.Unlock()

nilSlot := 0
var nilSlot = 0
for _, err := range newErrs {
for errs[nilSlot] != nil {
nilSlot++
Expand Down
2 changes: 1 addition & 1 deletion core/types/block_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,11 +207,11 @@ func TestEIP2718BlockEncoding(t *testing.T) {
})
sig2 := common.Hex2Bytes("3dbacc8d0259f2508625e97fdfc57cd85fdd16e5821bc2c10bdd1a52649e8335476e10695b183a87b0aa292a7f4b78ef0c3fbe62aa2c42c84e1d9c3da159ef1401")
tx2, _ = tx2.WithSignature(NewEIP2930Signer(big.NewInt(1)), sig2)
check("Transactions[1].Type()", block.Transactions()[1].Type(), uint8(AccessListTxType))

check("len(Transactions)", len(block.Transactions()), 2)
check("Transactions[0].Hash", block.Transactions()[0].Hash(), tx1.Hash())
check("Transactions[1].Hash", block.Transactions()[1].Hash(), tx2.Hash())
check("Transactions[1].Type()", block.Transactions()[1].Type(), uint8(AccessListTxType))

if !bytes.Equal(block.ExtData(), []byte{}) {
t.Errorf("Block ExtraData field mismatch, expected empty byte array, but found 0x%x", block.ExtData())
Expand Down
5 changes: 5 additions & 0 deletions core/vm/evm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,13 @@ func TestIsProhibited(t *testing.T) {
assert.True(t, IsProhibited(common.HexToAddress("0x01000000000000000000000000000000000000f0")))
assert.True(t, IsProhibited(common.HexToAddress("0x01000000000000000000000000000000000000ff")))
assert.True(t, IsProhibited(common.HexToAddress("0x0200000000000000000000000000000000000000")))
assert.True(t, IsProhibited(common.HexToAddress("0x0200000000000000000000000000000000000010")))
assert.True(t, IsProhibited(common.HexToAddress("0x02000000000000000000000000000000000000f0")))
assert.True(t, IsProhibited(common.HexToAddress("0x02000000000000000000000000000000000000ff")))
// reserved addresses (custom precompiles)
assert.True(t, IsProhibited(common.HexToAddress("0x0300000000000000000000000000000000000000")))
assert.True(t, IsProhibited(common.HexToAddress("0x0300000000000000000000000000000000000010")))
assert.True(t, IsProhibited(common.HexToAddress("0x03000000000000000000000000000000000000f0")))
assert.True(t, IsProhibited(common.HexToAddress("0x03000000000000000000000000000000000000ff")))

// allowed for use
Expand Down
2 changes: 2 additions & 0 deletions core/vm/jump_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ func validate(jt JumpTable) JumpTable {
return jt
}

// newDurangoInstructionSet returns the frontier, homestead, byzantium,
// constantinople, istanbul, petersburg, subnet-evm, durango instructions.
func newDurangoInstructionSet() JumpTable {
instructionSet := newApricotPhase3InstructionSet()
enable3855(&instructionSet) // PUSH0 instruction
Expand Down
3 changes: 3 additions & 0 deletions eth/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,9 +358,12 @@ func (s *Ethereum) Stop() error {

// Clean shutdown marker as the last thing before closing db
s.shutdownTracker.Stop()
log.Info("Stopped shutdownTracker")

s.chainDb.Close()
log.Info("Closed chaindb")
s.eventMux.Stop()
log.Info("Stopped EventMux")
return nil
}

Expand Down
2 changes: 1 addition & 1 deletion ethclient/ethclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ func (ec *client) SubscribeNewAcceptedTransactions(ctx context.Context, ch chan<
return sub, nil
}

// SubscribeNewAcceptedTransactions subscribes to notifications about the accepted transaction hashes on the given channel.
// SubscribeNewPendingTransactions subscribes to notifications about the pending transaction hashes on the given channel.
func (ec *client) SubscribeNewPendingTransactions(ctx context.Context, ch chan<- *common.Hash) (interfaces.Subscription, error) {
sub, err := ec.c.EthSubscribe(ctx, ch, "newPendingTransactions")
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion metrics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go-metrics

Go port of Coda Hale's Metrics library: <https://github.com/dropwizard/metrics>.

Documentation: <https://godoc.org/github.com/rcrowley/go-metrics>.
Documentation: <https://pkg.go.dev/github.com/rcrowley/go-metrics>.

Usage
-----
Expand Down
2 changes: 2 additions & 0 deletions miner/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ func (w *worker) commitNewWork(predicateContext *precompileconfig.PredicateConte
Extra: nil,
Time: timestamp,
}

// Set BaseFee and Extra data field if we are post ApricotPhase3
if w.chainConfig.IsApricotPhase3(timestamp) {
var err error
Expand All @@ -165,6 +166,7 @@ func (w *worker) commitNewWork(predicateContext *precompileconfig.PredicateConte
return nil, fmt.Errorf("failed to calculate new base fee: %w", err)
}
}

if w.coinbase == (common.Address{}) {
return nil, errors.New("cannot mine without etherbase")
}
Expand Down
12 changes: 6 additions & 6 deletions params/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -1050,6 +1050,12 @@ type Rules struct {
AccepterPrecompiles map[common.Address]precompileconfig.Accepter
}

// IsPrecompileEnabled returns true if the precompile at [addr] is enabled for this rule set.
func (r *Rules) IsPrecompileEnabled(addr common.Address) bool {
_, ok := r.ActivePrecompiles[addr]
return ok
}

// Rules ensures c's ChainID is not nil.
func (c *ChainConfig) rules(num *big.Int, timestamp uint64) Rules {
chainID := c.ChainID
Expand Down Expand Up @@ -1105,9 +1111,3 @@ func (c *ChainConfig) AvalancheRules(blockNum *big.Int, timestamp uint64) Rules

return rules
}

// IsPrecompileEnabled returns true if the precompile at [addr] is enabled for this rule set.
func (r *Rules) IsPrecompileEnabled(addr common.Address) bool {
_, ok := r.ActivePrecompiles[addr]
return ok
}
1 change: 0 additions & 1 deletion peer/network_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"github.com/prometheus/client_golang/prometheus"

"github.com/ava-labs/coreth/plugin/evm/message"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

Expand Down
Loading

0 comments on commit 037132e

Please sign in to comment.