diff --git a/.github/workflows/build-pr.yml b/.github/workflows/build-pr.yml index cd0d567edc..4d0fe8f8b8 100644 --- a/.github/workflows/build-pr.yml +++ b/.github/workflows/build-pr.yml @@ -41,6 +41,10 @@ jobs: integration/.build/noderunner/noderunner-*.txt integration/.build/wallet_extension/wal-ext-*.txt integration/.build/eth2/* + integration/.build/faucet/* + integration/.build/obscuroscan/* + integration/.build/tengateway/* + integration/.build/smartcontracts/* retention-days: 1 diff --git a/contracts/deployment_scripts/core/001_deploy_management_contract.ts b/contracts/deployment_scripts/core/001_deploy_management_contract.ts index 3e862202fd..38571f958a 100644 --- a/contracts/deployment_scripts/core/001_deploy_management_contract.ts +++ b/contracts/deployment_scripts/core/001_deploy_management_contract.ts @@ -43,7 +43,7 @@ const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) { // This is required in CI/CD - look at testnet-deploy-contracts.sh for more information. // depends on grep -e MessageBusAddress and a positional cut of the address console.log(`MessageBusAddress= ${busAddress}`); - console.log(`L1Start=${mgmtContractDeployment.receipt.blockHash}`) + console.log(`L1Start= ${mgmtContractDeployment.receipt.blockHash}`) }; export default func; diff --git a/contracts/deployment_scripts/testnet/layer2/001_whitelist_tokens.ts b/contracts/deployment_scripts/testnet/layer2/001_whitelist_tokens.ts index 397e11db8a..371bea2a10 100644 --- a/contracts/deployment_scripts/testnet/layer2/001_whitelist_tokens.ts +++ b/contracts/deployment_scripts/testnet/layer2/001_whitelist_tokens.ts @@ -122,7 +122,7 @@ const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) { return l2Network.deployments.execute("CrossChainMessenger", { from: l2Accounts.deployer, log: true, - gasLimit: 1024_000_000 + gasLimit: 5_000_000 }, "relayMessage", msg); }; diff --git a/go/config/enclave_cli_flags.go b/go/config/enclave_cli_flags.go index 030ddd1c87..586a9e7c2a 100644 --- a/go/config/enclave_cli_flags.go +++ b/go/config/enclave_cli_flags.go @@ -31,7 +31,8 @@ const ( MaxRollupSizeFlag = "maxRollupSize" L2BaseFeeFlag = "l2BaseFee" L2CoinbaseFlag = "l2Coinbase" - L2GasLimitFlag = "l2GasLimit" + GasBatchExecutionLimit = "gasBatchExecutionLimit" + GasLocalExecutionCapFlag = "gasLocalExecutionCap" ) // EnclaveFlags are the flags that the enclave can receive @@ -54,13 +55,14 @@ var EnclaveFlags = map[string]*flag.TenFlag{ MaxRollupSizeFlag: flag.NewUint64Flag(MaxRollupSizeFlag, 1024*64, "The maximum size a rollup is allowed to reach"), L2BaseFeeFlag: flag.NewUint64Flag(L2BaseFeeFlag, 1, ""), L2CoinbaseFlag: flag.NewStringFlag(L2CoinbaseFlag, "0xd6C9230053f45F873Cb66D8A02439380a37A4fbF", ""), - L2GasLimitFlag: flag.NewUint64Flag(L2GasLimitFlag, 9e18, ""), + GasBatchExecutionLimit: flag.NewUint64Flag(GasBatchExecutionLimit, 30_000_000, "Max gas that can be executed in a single batch"), ObscuroGenesisFlag: flag.NewStringFlag(ObscuroGenesisFlag, "", "The json string with the obscuro genesis"), L1ChainIDFlag: flag.NewInt64Flag(L1ChainIDFlag, 1337, "An integer representing the unique chain id of the Ethereum chain used as an L1 (default 1337)"), ObscuroChainIDFlag: flag.NewInt64Flag(ObscuroChainIDFlag, 443, "An integer representing the unique chain id of the Obscuro chain (default 443)"), UseInMemoryDBFlag: flag.NewBoolFlag(UseInMemoryDBFlag, true, "Whether the enclave will use an in-memory DB rather than persist data"), ProfilerEnabledFlag: flag.NewBoolFlag(ProfilerEnabledFlag, false, "Runs a profiler instance (Defaults to false)"), DebugNamespaceEnabledFlag: flag.NewBoolFlag(DebugNamespaceEnabledFlag, false, "Whether the debug namespace is enabled"), + GasLocalExecutionCapFlag: flag.NewUint64Flag(GasLocalExecutionCapFlag, 40_000_000, "Max gas usage when executing local transactions"), } // enclaveRestrictedFlags are the flags that the enclave can receive ONLY over the Ego signed enclave.json diff --git a/go/config/enclave_config.go b/go/config/enclave_config.go index 30c7fe6aca..68f92524f0 100644 --- a/go/config/enclave_config.go +++ b/go/config/enclave_config.go @@ -65,9 +65,10 @@ type EnclaveConfig struct { // to include a transaction if it goes above it MaxRollupSize uint64 - GasPaymentAddress gethcommon.Address - BaseFee *big.Int - GasLimit *big.Int + GasPaymentAddress gethcommon.Address + BaseFee *big.Int + GasBatchExecutionLimit uint64 + GasLocalExecutionCapFlag uint64 } func NewConfigFromFlags(cliFlags map[string]*flag.TenFlag) (*EnclaveConfig, error) { @@ -184,7 +185,8 @@ func newConfig(flags map[string]*flag.TenFlag) (*EnclaveConfig, error) { cfg.MaxRollupSize = flags[MaxRollupSizeFlag].Uint64() cfg.BaseFee = big.NewInt(0).SetUint64(flags[L2BaseFeeFlag].Uint64()) cfg.GasPaymentAddress = gethcommon.HexToAddress(flags[L2CoinbaseFlag].String()) - cfg.GasLimit = big.NewInt(0).SetUint64(flags[L2GasLimitFlag].Uint64()) + cfg.GasBatchExecutionLimit = flags[GasBatchExecutionLimit].Uint64() + cfg.GasLocalExecutionCapFlag = flags[GasLocalExecutionCapFlag].Uint64() return cfg, nil } diff --git a/go/config/enclave_config_test.go b/go/config/enclave_config_test.go index 79cd1361d8..c587572e91 100644 --- a/go/config/enclave_config_test.go +++ b/go/config/enclave_config_test.go @@ -41,7 +41,7 @@ func TestCLIFlagTypes(t *testing.T) { err = flag.CommandLine.Set(MinGasPriceFlag, "3333") require.NoError(t, err) - err = flag.CommandLine.Set(L2GasLimitFlag, "222222") + err = flag.CommandLine.Set(GasBatchExecutionLimit, "222222") require.NoError(t, err) flag.Parse() @@ -50,7 +50,7 @@ func TestCLIFlagTypes(t *testing.T) { require.Equal(t, true, flags[WillAttestFlag].Bool()) require.Equal(t, 123, flags[LogLevelFlag].Int()) require.Equal(t, int64(3333), flags[MinGasPriceFlag].Int64()) - require.Equal(t, uint64(222222), flags[L2GasLimitFlag].Uint64()) + require.Equal(t, uint64(222222), flags[GasBatchExecutionLimit].Uint64()) enclaveConfig, err := newConfig(flags) require.NoError(t, err) @@ -59,7 +59,7 @@ func TestCLIFlagTypes(t *testing.T) { require.Equal(t, true, enclaveConfig.WillAttest) require.Equal(t, 123, enclaveConfig.LogLevel) require.Equal(t, big.NewInt(3333), enclaveConfig.MinGasPrice) - require.Equal(t, big.NewInt(222222), enclaveConfig.GasLimit) + require.Equal(t, uint64(222222), enclaveConfig.GasBatchExecutionLimit) } func TestRestrictedMode(t *testing.T) { diff --git a/go/enclave/components/batch_executor.go b/go/enclave/components/batch_executor.go index 226486461d..da37326c22 100644 --- a/go/enclave/components/batch_executor.go +++ b/go/enclave/components/batch_executor.go @@ -42,6 +42,8 @@ type batchExecutor struct { // stateDBMutex - used to protect calls to stateDB.Commit as it is not safe for async access. stateDBMutex sync.Mutex + + batchGasLimit uint64 // max execution gas allowed in a batch } func NewBatchExecutor( @@ -50,6 +52,7 @@ func NewBatchExecutor( genesis *genesis.Genesis, gasOracle gas.Oracle, chainConfig *params.ChainConfig, + batchGasLimit uint64, logger gethlog.Logger, ) BatchExecutor { return &batchExecutor{ @@ -60,6 +63,7 @@ func NewBatchExecutor( logger: logger, gasOracle: gasOracle, stateDBMutex: sync.Mutex{}, + batchGasLimit: batchGasLimit, } } @@ -168,6 +172,7 @@ func (executor *batchExecutor) ComputeBatch(context *BatchExecutionContext, fail if err != nil { return nil, fmt.Errorf("could not create stateDB. Cause: %w", err) } + snap := stateDB.Snapshot() var messages common.CrossChainMessages var transfers common.ValueTransferEvents @@ -217,6 +222,8 @@ func (executor *batchExecutor) ComputeBatch(context *BatchExecutionContext, fail len(crossChainTransactions) == 0 && len(messages) == 0 && len(transfers) == 0 { + // revert any unexpected mutation to the statedb + stateDB.RevertToSnapshot(snap) return nil, ErrNoTransactionsToProcess } @@ -298,18 +305,12 @@ func (executor *batchExecutor) CreateGenesisState( timeNow uint64, coinbase gethcommon.Address, baseFee *big.Int, - gasLimit *big.Int, ) (*core.Batch, *types.Transaction, error) { preFundGenesisState, err := executor.genesis.GetGenesisRoot(executor.storage) if err != nil { return nil, nil, err } - limit := params.MaxGasLimit / 6 - if gasLimit != nil { - limit = gasLimit.Uint64() - } - genesisBatch := &core.Batch{ Header: &common.BatchHeader{ ParentHash: common.L2BatchHash{}, @@ -323,7 +324,7 @@ func (executor *batchExecutor) CreateGenesisState( Time: timeNow, Coinbase: coinbase, BaseFee: baseFee, - GasLimit: limit, // todo (@siliev) - does the batch header need uint64? + GasLimit: executor.batchGasLimit, }, Transactions: []*common.L2Tx{}, } @@ -408,8 +409,17 @@ func (executor *batchExecutor) processTransactions( var executedTransactions []*common.L2Tx var excludedTransactions []*common.L2Tx var txReceipts []*types.Receipt - - txResults := evm.ExecuteTransactions(txs, stateDB, batch.Header, executor.storage, cc, tCount, noBaseFee, executor.logger) + txResults := evm.ExecuteTransactions( + txs, + stateDB, + batch.Header, + executor.storage, + cc, + tCount, + noBaseFee, + executor.batchGasLimit, + executor.logger, + ) for _, tx := range txs { result, f := txResults[tx.Hash()] if !f { diff --git a/go/enclave/components/interfaces.go b/go/enclave/components/interfaces.go index 12b696ce97..6ed7e7a750 100644 --- a/go/enclave/components/interfaces.go +++ b/go/enclave/components/interfaces.go @@ -76,7 +76,7 @@ type BatchExecutor interface { // CreateGenesisState - will create and commit the genesis state in the stateDB for the given block hash, // and uint64 timestamp representing the time now. In this genesis state is where one can // find preallocated funds for faucet. TODO - make this an option - CreateGenesisState(common.L1BlockHash, uint64, gethcommon.Address, *big.Int, *big.Int) (*core.Batch, *types.Transaction, error) + CreateGenesisState(common.L1BlockHash, uint64, gethcommon.Address, *big.Int) (*core.Batch, *types.Transaction, error) } type BatchRegistry interface { diff --git a/go/enclave/components/rollup_compression.go b/go/enclave/components/rollup_compression.go index 0034d48cc7..f8801f70f4 100644 --- a/go/enclave/components/rollup_compression.go +++ b/go/enclave/components/rollup_compression.go @@ -436,7 +436,6 @@ func (rc *RollupCompression) executeAndSaveIncompleteBatches(calldataRollupHeade incompleteBatch.time, calldataRollupHeader.Coinbase, calldataRollupHeader.BaseFee, - big.NewInt(0).SetUint64(calldataRollupHeader.GasLimit), ) if err != nil { return err diff --git a/go/enclave/enclave.go b/go/enclave/enclave.go index 88025246f3..303ac77fa3 100644 --- a/go/enclave/enclave.go +++ b/go/enclave/enclave.go @@ -81,10 +81,6 @@ type enclaveImpl struct { service nodetype.NodeType registry components.BatchRegistry - // todo (#627) - use the ethconfig.Config instead - GlobalGasCap uint64 // 5_000_000_000, // todo (#627) - make config - BaseFee *big.Int // gethcommon.Big0, - mgmtContractLib mgmtcontractlib.MgmtContractLib attestationProvider components.AttestationProvider // interface for producing attestation reports and verifying them @@ -184,7 +180,7 @@ func NewEnclave( gasOracle := gas.NewGasOracle() blockProcessor := components.NewBlockProcessor(storage, crossChainProcessors, gasOracle, logger) - batchExecutor := components.NewBatchExecutor(storage, crossChainProcessors, genesis, gasOracle, chainConfig, logger) + batchExecutor := components.NewBatchExecutor(storage, crossChainProcessors, genesis, gasOracle, chainConfig, config.GasBatchExecutionLimit, logger) sigVerifier, err := components.NewSignatureValidator(config.SequencerID, storage) registry := components.NewBatchRegistry(storage, logger) rProducer := components.NewRollupProducer(config.SequencerID, storage, registry, logger) @@ -222,7 +218,7 @@ func NewEnclave( MaxBatchSize: config.MaxBatchSize, MaxRollupSize: config.MaxRollupSize, GasPaymentAddress: config.GasPaymentAddress, - BatchGasLimit: config.GasLimit, + BatchGasLimit: config.GasBatchExecutionLimit, BaseFee: config.BaseFee, }, blockchain, @@ -237,6 +233,7 @@ func NewEnclave( genesis, logger, registry, + config.GasLocalExecutionCapFlag, ) // ensure cached chain state data is up-to-date using the persisted batch data @@ -275,9 +272,6 @@ func NewEnclave( registry: registry, service: service, - GlobalGasCap: 5_000_000_000, // todo (#627) - make config - BaseFee: gethcommon.Big0, - mainMutex: sync.Mutex{}, } } @@ -691,15 +685,18 @@ func (e *enclaveImpl) GetTransactionCount(encryptedParams common.EncryptedParams } var nonce uint64 - l2Head, err := e.storage.FetchBatchBySeqNo(e.registry.HeadBatchSeq().Uint64()) - if err == nil { - // todo - we should return an error when head state is not available, but for current test situations with race - // conditions we allow it to return zero while head state is uninitialized - s, err := e.storage.CreateStateDB(l2Head.Hash()) - if err != nil { - return nil, responses.ToInternalError(err) + headBatch := e.registry.HeadBatchSeq() + if headBatch != nil { + l2Head, err := e.storage.FetchBatchBySeqNo(headBatch.Uint64()) + if err == nil { + // todo - we should return an error when head state is not available, but for current test situations with race + // conditions we allow it to return zero while head state is uninitialized + s, err := e.storage.CreateStateDB(l2Head.Hash()) + if err != nil { + return nil, responses.ToInternalError(err) + } + nonce = s.GetNonce(address) } - nonce = s.GetNonce(address) } encoded := hexutil.EncodeUint64(nonce) @@ -1028,7 +1025,7 @@ func (e *enclaveImpl) EstimateGas(encryptedParams common.EncryptedParamsEstimate return responses.AsEncryptedError(err, vkHandler), nil } - executionGasEstimate, err := e.DoEstimateGas(callMsg, blockNumber, e.GlobalGasCap) + executionGasEstimate, err := e.DoEstimateGas(callMsg, blockNumber, e.config.GasLocalExecutionCapFlag) if err != nil { err = fmt.Errorf("unable to estimate transaction - %w", err) @@ -1155,7 +1152,7 @@ func (e *enclaveImpl) DoEstimateGas(args *gethapi.TransactionArgs, blkNumber *ge } hi = block.GasLimit() */ - hi = e.GlobalGasCap + hi = e.config.GasLocalExecutionCapFlag } // Normalize the max fee per gas the call is willing to spend. var feeCap *big.Int diff --git a/go/enclave/evm/evm_facade.go b/go/enclave/evm/evm_facade.go index cb841a5311..31560d705c 100644 --- a/go/enclave/evm/evm_facade.go +++ b/go/enclave/evm/evm_facade.go @@ -3,7 +3,6 @@ package evm import ( "errors" "fmt" - "math" "math/big" "github.com/ethereum/go-ethereum/accounts/abi" @@ -38,9 +37,11 @@ func ExecuteTransactions( chainConfig *params.ChainConfig, fromTxIndex int, noBaseFee bool, + batchGasLimit uint64, logger gethlog.Logger, ) map[common.TxHash]interface{} { - chain, vmCfg, gp := initParams(storage, noBaseFee, logger) + chain, vmCfg := initParams(storage, noBaseFee, logger) + gp := gethcore.GasPool(batchGasLimit) zero := uint64(0) usedGas := &zero result := map[common.TxHash]interface{}{} @@ -57,7 +58,7 @@ func ExecuteTransactions( s, chainConfig, chain, - gp, + &gp, ethHeader, t, usedGas, @@ -157,6 +158,7 @@ func ExecuteObsCall( header *common.BatchHeader, storage storage.Storage, chainConfig *params.ChainConfig, + gasEstimationCap uint64, logger gethlog.Logger, ) (*gethcore.ExecutionResult, error) { noBaseFee := true @@ -166,7 +168,9 @@ func ExecuteObsCall( defer core.LogMethodDuration(logger, measure.NewStopwatch(), "evm_facade.go:ObsCall()") - chain, vmCfg, gp := initParams(storage, noBaseFee, nil) + gp := gethcore.GasPool(gasEstimationCap) + gp.SetGas(gasEstimationCap) + chain, vmCfg := initParams(storage, noBaseFee, nil) ethHeader, err := gethencoding.CreateEthHeaderForBatch(header, secret(storage)) if err != nil { return nil, err @@ -177,7 +181,7 @@ func ExecuteObsCall( txContext := gethcore.NewEVMTxContext(msg) vmenv := vm.NewEVM(blockContext, txContext, s, chainConfig, vmCfg) - result, err := gethcore.ApplyMessage(vmenv, msg, gp) + result, err := gethcore.ApplyMessage(vmenv, msg, &gp) // Follow the same error check structure as in geth // 1 - vmError / stateDB err check // 2 - evm.Cancelled() todo (#1576) - support the ability to cancel function call if it takes too long @@ -202,12 +206,11 @@ func ExecuteObsCall( return result, nil } -func initParams(storage storage.Storage, noBaseFee bool, l gethlog.Logger) (*ObscuroChainContext, vm.Config, *gethcore.GasPool) { +func initParams(storage storage.Storage, noBaseFee bool, l gethlog.Logger) (*ObscuroChainContext, vm.Config) { vmCfg := vm.Config{ NoBaseFee: noBaseFee, } - gp := gethcore.GasPool(math.MaxUint64) - return NewObscuroChainContext(storage, l), vmCfg, &gp + return NewObscuroChainContext(storage, l), vmCfg } // todo (#1053) - this is currently just returning the shared secret diff --git a/go/enclave/l2chain/l2_chain.go b/go/enclave/l2chain/l2_chain.go index ac35554645..7f56e0fde6 100644 --- a/go/enclave/l2chain/l2_chain.go +++ b/go/enclave/l2chain/l2_chain.go @@ -34,7 +34,8 @@ type obscuroChain struct { logger gethlog.Logger - Registry components.BatchRegistry + Registry components.BatchRegistry + gasEstimationCap uint64 } func NewChain( @@ -43,13 +44,15 @@ func NewChain( genesis *genesis.Genesis, logger gethlog.Logger, registry components.BatchRegistry, + gasEstimationCap uint64, ) ObscuroChain { return &obscuroChain{ - storage: storage, - chainConfig: chainConfig, - logger: logger, - genesis: genesis, - Registry: registry, + storage: storage, + chainConfig: chainConfig, + logger: logger, + genesis: genesis, + Registry: registry, + gasEstimationCap: gasEstimationCap, } } @@ -144,7 +147,7 @@ func (oc *obscuroChain) ObsCallAtBlock(apiArgs *gethapi.TransactionArgs, blockNu batch.Header.Root.Hex()) }}) - result, err := evm.ExecuteObsCall(callMsg, blockState, batch.Header, oc.storage, oc.chainConfig, oc.logger) + result, err := evm.ExecuteObsCall(callMsg, blockState, batch.Header, oc.storage, oc.chainConfig, oc.gasEstimationCap, oc.logger) if err != nil { // also return the result as the result can be evaluated on some errors like ErrIntrinsicGas return result, err diff --git a/go/enclave/nodetype/sequencer.go b/go/enclave/nodetype/sequencer.go index 71fdec925e..1b70086372 100644 --- a/go/enclave/nodetype/sequencer.go +++ b/go/enclave/nodetype/sequencer.go @@ -35,7 +35,7 @@ type SequencerSettings struct { MaxBatchSize uint64 MaxRollupSize uint64 GasPaymentAddress gethcommon.Address - BatchGasLimit *big.Int + BatchGasLimit uint64 BaseFee *big.Int } @@ -138,7 +138,6 @@ func (s *sequencer) createGenesisBatch(block *common.L1Block) error { uint64(time.Now().Unix()), s.settings.GasPaymentAddress, s.settings.BaseFee, - s.settings.BatchGasLimit, ) if err != nil { return err @@ -164,6 +163,7 @@ func (s *sequencer) createGenesisBatch(block *common.L1Block) error { return err } + time.Sleep(time.Second) // produce batch #2 which has the message bus and any other system contracts cb, err := s.produceBatch( big.NewInt(0).Add(batch.Header.SequencerOrderNo, big.NewInt(1)), diff --git a/go/enclave/nodetype/validator.go b/go/enclave/nodetype/validator.go index fae31d6df6..4997fa3297 100644 --- a/go/enclave/nodetype/validator.go +++ b/go/enclave/nodetype/validator.go @@ -133,7 +133,7 @@ func (val *obsValidator) executionPrerequisites(batch *core.Batch) (bool, error) } func (val *obsValidator) handleGenesis(batch *core.Batch) error { - genBatch, _, err := val.batchExecutor.CreateGenesisState(batch.Header.L1Proof, batch.Header.Time, batch.Header.Coinbase, batch.Header.BaseFee, big.NewInt(0).SetUint64(batch.Header.GasLimit)) + genBatch, _, err := val.batchExecutor.CreateGenesisState(batch.Header.L1Proof, batch.Header.Time, batch.Header.Coinbase, batch.Header.BaseFee) if err != nil { return err } diff --git a/integration/common/constants.go b/integration/common/constants.go index 63e4ab993c..80d68b5446 100644 --- a/integration/common/constants.go +++ b/integration/common/constants.go @@ -4,7 +4,6 @@ import ( "math/big" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/params" "github.com/ten-protocol/go-ten/go/common" "github.com/ten-protocol/go-ten/go/common/log" "github.com/ten-protocol/go-ten/go/config" @@ -84,6 +83,7 @@ func DefaultEnclaveConfig() *config.EnclaveConfig { MaxRollupSize: 1024 * 64, GasPaymentAddress: gethcommon.HexToAddress("0xd6C9230053f45F873Cb66D8A02439380a37A4fbF"), BaseFee: new(big.Int).SetUint64(1), - GasLimit: new(big.Int).SetUint64(params.MaxGasLimit / 6), + GasBatchExecutionLimit: 30_000_000, + GasLocalExecutionCapFlag: 40_000_000, } } diff --git a/integration/common/utils.go b/integration/common/utils.go index 676e6db689..aabfea5804 100644 --- a/integration/common/utils.go +++ b/integration/common/utils.go @@ -99,7 +99,7 @@ func PrefundWallets(ctx context.Context, faucetWallet wallet.Wallet, faucetClien tx := &types.LegacyTx{ Nonce: startingNonce + uint64(idx), Value: alloc, - Gas: uint64(1_000_000), + Gas: uint64(100_000), GasPrice: gethcommon.Big1, To: &destAddr, } diff --git a/integration/constants.go b/integration/constants.go index 37dee9b2f0..6191b4f932 100644 --- a/integration/constants.go +++ b/integration/constants.go @@ -2,18 +2,18 @@ package integration // Tracks the start ports handed out to different tests, in a bid to minimise conflicts. const ( - StartPortEth2NetworkTests = 31000 - StartPortNodeRunnerTest = 32000 - StartPortSimulationGethInMem = 34000 - StartPortSimulationInMem = 35000 - StartPortSimulationFullNetwork = 37000 - StartPortSmartContractTests = 38000 - StartPortContractDeployerTest = 39000 - StartPortWalletExtensionUnitTest = 40000 - StartPortFaucetUnitTest = 41000 - StartPortFaucetHTTPUnitTest = 42000 - StartPortTenscanUnitTest = 43000 - StartPortTenGatewayUnitTest = 44000 + StartPortEth2NetworkTests = 10000 + StartPortNodeRunnerTest = 14000 + StartPortSimulationGethInMem = 18000 + StartPortSimulationInMem = 22000 + StartPortSimulationFullNetwork = 26000 + StartPortSmartContractTests = 30000 + StartPortContractDeployerTest = 34000 + StartPortWalletExtensionUnitTest = 38000 + StartPortFaucetUnitTest = 42000 + StartPortFaucetHTTPUnitTest = 48000 + StartPortTenscanUnitTest = 52000 + StartPortTenGatewayUnitTest = 56000 DefaultGethWSPortOffset = 100 DefaultGethAUTHPortOffset = 200 @@ -24,9 +24,9 @@ const ( DefaultEnclaveOffset = 700 // The default offset between a Geth nodes port and the enclave ports. Used in Socket Simulations. DefaultHostRPCHTTPOffset = 800 // The default offset for the host's RPC HTTP port DefaultHostRPCWSOffset = 900 // The default offset for the host's RPC websocket port - DefaultTenscanHTTPPortOffset = 910 - DefaultTenGatewayHTTPPortOffset = 930 - DefaultTenGatewayWSPortOffset = 940 + DefaultTenscanHTTPPortOffset = 1000 + DefaultTenGatewayHTTPPortOffset = 1001 + DefaultTenGatewayWSPortOffset = 1002 ) const ( diff --git a/integration/datagenerator/common.go b/integration/datagenerator/common.go index a0d61e5656..22018e8611 100644 --- a/integration/datagenerator/common.go +++ b/integration/datagenerator/common.go @@ -49,7 +49,7 @@ func CreateL2TxData() *types.LegacyTx { nonce, _ := rand.Int(rand.Reader, big.NewInt(math.MaxInt64)) encodedTxData := make([]byte, 0) return &types.LegacyTx{ - Nonce: nonce.Uint64(), Value: big.NewInt(1), Gas: 1, GasPrice: big.NewInt(1), Data: encodedTxData, + Nonce: nonce.Uint64(), Value: big.NewInt(1), Gas: 1, GasPrice: gethcommon.Big1, Data: encodedTxData, } } diff --git a/integration/eth2network/eth2_network.go b/integration/eth2network/eth2_network.go index bc85341365..19bee3d939 100644 --- a/integration/eth2network/eth2_network.go +++ b/integration/eth2network/eth2_network.go @@ -18,6 +18,8 @@ import ( "github.com/ethereum/go-ethereum/ethclient" "github.com/ten-protocol/go-ten/integration/datagenerator" "golang.org/x/sync/errgroup" + + gethcommon "github.com/ethereum/go-ethereum/common" ) const ( @@ -206,6 +208,10 @@ func (n *Impl) Start() error { startTime := time.Now() var eg errgroup.Group + if err := n.ensureNoDuplicatedNetwork(); err != nil { + return err + } + // initialize the genesis data on the nodes for _, nodeDataDir := range n.dataDirs { dataDir := nodeDataDir @@ -506,6 +512,11 @@ func (n *Impl) waitForMergeEvent(startTime time.Time) error { } fmt.Printf("Reached the merge block after %s\n", time.Since(startTime)) + + if err = n.prefundedBalancesActive(dial); err != nil { + fmt.Printf("Error prefunding accounts %s\n", err.Error()) + return err + } return nil } @@ -589,6 +600,31 @@ func (n *Impl) gethImportEnodes(enodes []string) error { return nil } +func (n *Impl) prefundedBalancesActive(client *ethclient.Client) error { + for _, addr := range n.preFundedMinerAddrs { + balance, err := client.BalanceAt(context.Background(), gethcommon.HexToAddress(addr), nil) + if err != nil { + return fmt.Errorf("unable to check balance for account %s - %w", addr, err) + } + if balance.Cmp(gethcommon.Big0) == 0 { + return fmt.Errorf("unexpected %s balance for account %s", balance.String(), addr) + } + fmt.Printf("Account %s prefunded with %s\n", addr, balance.String()) + } + + return nil +} + +func (n *Impl) ensureNoDuplicatedNetwork() error { + for nodeIdx, port := range n.gethWSPorts { + _, err := ethclient.Dial(fmt.Sprintf("ws://127.0.0.1:%d", port)) + if err == nil { + return fmt.Errorf("unexpected geth node %d is active before the network is started", nodeIdx) + } + } + return nil +} + func min(a, b int) int { if a < b { return a diff --git a/integration/simulation/devnetwork/node.go b/integration/simulation/devnetwork/node.go index f2922b6f31..e49a734c21 100644 --- a/integration/simulation/devnetwork/node.go +++ b/integration/simulation/devnetwork/node.go @@ -2,7 +2,6 @@ package devnetwork import ( "fmt" - "math/big" "os" gethcommon "github.com/ethereum/go-ethereum/common" @@ -175,14 +174,15 @@ func (n *InMemNodeOperator) createEnclaveContainer() *enclavecontainer.EnclaveCo GenesisJSON: nil, UseInMemoryDB: false, ManagementContractAddress: n.l1Data.MgmtContractAddress, - MinGasPrice: big.NewInt(1), + MinGasPrice: gethcommon.Big1, MessageBusAddress: n.l1Data.MessageBusAddr, SqliteDBPath: n.enclaveDBFilepath, DebugNamespaceEnabled: true, MaxBatchSize: 1024 * 25, MaxRollupSize: 1024 * 64, BaseFee: defaultCfg.BaseFee, // todo @siliev:: fix test transaction builders so this can be different - GasLimit: defaultCfg.GasLimit, + GasBatchExecutionLimit: defaultCfg.GasBatchExecutionLimit, + GasLocalExecutionCapFlag: defaultCfg.GasLocalExecutionCapFlag, GasPaymentAddress: defaultCfg.GasPaymentAddress, } return enclavecontainer.NewEnclaveContainerWithLogger(enclaveConfig, enclaveLogger) diff --git a/integration/simulation/network/network_utils.go b/integration/simulation/network/network_utils.go index 4633975fea..e640cced8a 100644 --- a/integration/simulation/network/network_utils.go +++ b/integration/simulation/network/network_utils.go @@ -6,9 +6,9 @@ import ( "math/big" "time" - "github.com/ten-protocol/go-ten/go/host/l1" - + "github.com/ethereum/go-ethereum/params" "github.com/ten-protocol/go-ten/go/host" + "github.com/ten-protocol/go-ten/go/host/l1" "github.com/ten-protocol/go-ten/go/common" "github.com/ten-protocol/go-ten/go/common/log" @@ -88,13 +88,14 @@ func createInMemObscuroNode( ValidateL1Blocks: validateBlocks, GenesisJSON: genesisJSON, UseInMemoryDB: true, - MinGasPrice: big.NewInt(1), + MinGasPrice: gethcommon.Big1, MessageBusAddress: l1BusAddress, ManagementContractAddress: *mgtContractAddress, MaxBatchSize: 1024 * 25, MaxRollupSize: 1024 * 64, BaseFee: big.NewInt(1), // todo @siliev:: fix test transaction builders so this can be different - GasLimit: big.NewInt(1_000_000_000_000_000_000), + GasLocalExecutionCapFlag: params.MaxGasLimit / 2, + GasBatchExecutionLimit: params.MaxGasLimit / 2, } enclaveLogger := testlog.Logger().New(log.NodeIDKey, id, log.CmpKey, log.EnclaveCmp) diff --git a/integration/simulation/network/socket.go b/integration/simulation/network/socket.go index 874e5c8125..323ddb2fac 100644 --- a/integration/simulation/network/socket.go +++ b/integration/simulation/network/socket.go @@ -1,7 +1,11 @@ package network import ( + "bufio" "fmt" + "os/exec" + "regexp" + "strings" "time" "github.com/ten-protocol/go-ten/integration/noderunner" @@ -112,6 +116,10 @@ func (n *networkOfSocketNodes) Create(simParams *params.SimParams, _ *stats.Stat // start the nodes err = nodes[i].Start() if err != nil { + errCheck := checkProcessPort(err.Error()) + if errCheck != nil { + testlog.Logger().Warn("no port found on error", log.ErrKey, err) + } testlog.Logger().Crit("unable to start obscuro node ", log.ErrKey, err) } } @@ -181,3 +189,35 @@ func (n *networkOfSocketNodes) createConnections(simParams *params.SimParams) er } return nil } + +// getProcessesUsingPort returns a slice of process details using the specified port. +func checkProcessPort(errPort string) error { + re := regexp.MustCompile(`:(\d+):`) + matches := re.FindStringSubmatch(errPort) + + if len(matches) < 2 { + return fmt.Errorf("no port found in string") + } + + port := matches[1] + + cmd := exec.Command("lsof", "-i", fmt.Sprintf(":%s", port)) //nolint:gosec + + output, err := cmd.Output() + if err != nil { + return err + } + + var processes []string + scanner := bufio.NewScanner(strings.NewReader(string(output))) + for scanner.Scan() { + line := scanner.Text() + if strings.Contains(line, "LISTEN") || strings.Contains(line, "ESTABLISHED") { + processes = append(processes, line) + } + } + + fmt.Printf("Found processes still opened on port %s - %+v\n", port, processes) + + return nil +} diff --git a/integration/simulation/simulation.go b/integration/simulation/simulation.go index e8c697afd2..4a3a814320 100644 --- a/integration/simulation/simulation.go +++ b/integration/simulation/simulation.go @@ -227,7 +227,7 @@ func (s *Simulation) deployObscuroERC20s() { deployContractTx := types.DynamicFeeTx{ Nonce: NextNonce(s.ctx, s.RPCHandles, owner), - Gas: 1025_000_000, + Gas: 5_000_000, GasFeeCap: gethcommon.Big1, // This field is used to derive the gas price for dynamic fee transactions. Data: contractBytes, GasTipCap: gethcommon.Big1, diff --git a/integration/smartcontract/smartcontracts_test.go b/integration/smartcontract/smartcontracts_test.go index 1f04054db7..16b99183fc 100644 --- a/integration/smartcontract/smartcontracts_test.go +++ b/integration/smartcontract/smartcontracts_test.go @@ -38,7 +38,7 @@ var testLogs = "../.build/noderunner/" func init() { //nolint:gochecknoinits testlog.Setup(&testlog.Cfg{ LogDir: testLogs, - TestType: "noderunner", + TestType: "smartcontracts", TestSubtype: "test", LogLevel: log.LvlInfo, }) diff --git a/testnet/launcher/cmd/cli.go b/testnet/launcher/cmd/cli.go index 0db6b2838b..351379f5b0 100644 --- a/testnet/launcher/cmd/cli.go +++ b/testnet/launcher/cmd/cli.go @@ -10,6 +10,8 @@ type TestnetConfigCLI struct { validatorEnclaveDebug bool sequencerEnclaveDockerImage string sequencerEnclaveDebug bool + contractDeployerDockerImage string + contractDeployerDebug bool isSGXEnabled bool } @@ -22,6 +24,8 @@ func ParseConfigCLI() *TestnetConfigCLI { validatorEnclaveDebug := flag.Bool(validatorEnclaveDebugFlag, false, flagUsageMap[validatorEnclaveDebugFlag]) sequencerEnclaveDockerImage := flag.String(sequencerEnclaveDockerImageFlag, "testnetobscuronet.azurecr.io/obscuronet/enclave:latest", flagUsageMap[sequencerEnclaveDockerImageFlag]) sequencerEnclaveDebug := flag.Bool(sequencerEnclaveDebugFlag, false, flagUsageMap[sequencerEnclaveDebugFlag]) + contractDeployerDockerImage := flag.String(contractDeployerDockerImageFlag, "testnetobscuronet.azurecr.io/obscuronet/hardhatdeployer:latest", flagUsageMap[contractDeployerDockerImageFlag]) + contractDeployerDebug := flag.Bool(contractDeployerDebugFlag, false, flagUsageMap[contractDeployerDebugFlag]) isSGXEnabled := flag.Bool(isSGXEnabledFlag, false, flagUsageMap[isSGXEnabledFlag]) flag.Parse() @@ -29,6 +33,8 @@ func ParseConfigCLI() *TestnetConfigCLI { cfg.sequencerEnclaveDockerImage = *sequencerEnclaveDockerImage cfg.validatorEnclaveDebug = *validatorEnclaveDebug cfg.sequencerEnclaveDebug = *sequencerEnclaveDebug + cfg.contractDeployerDebug = *contractDeployerDebug + cfg.contractDeployerDockerImage = *contractDeployerDockerImage cfg.isSGXEnabled = *isSGXEnabled return cfg diff --git a/testnet/launcher/cmd/cli_flags.go b/testnet/launcher/cmd/cli_flags.go index 0d56afa952..5f5c5cc980 100644 --- a/testnet/launcher/cmd/cli_flags.go +++ b/testnet/launcher/cmd/cli_flags.go @@ -6,6 +6,8 @@ const ( validatorEnclaveDebugFlag = "validator-enclave-debug" sequencerEnclaveDockerImageFlag = "sequencer-enclave-docker-image" sequencerEnclaveDebugFlag = "sequencer-enclave-debug" + contractDeployerDockerImageFlag = "contract-deployer-docker-image" + contractDeployerDebugFlag = "contract-deployer-debug" isSGXEnabledFlag = "is-sgx-enabled" ) @@ -17,6 +19,8 @@ func getFlagUsageMap() map[string]string { validatorEnclaveDebugFlag: "Enables the use of DLV to debug the validator enclave", sequencerEnclaveDockerImageFlag: "The docker image that runs the sequencer enclave", sequencerEnclaveDebugFlag: "Enables the use of DLV to debug the sequencer enclave", + contractDeployerDockerImageFlag: "The docker image that runs the contract deployer", + contractDeployerDebugFlag: "Enables the use of node inspector to debug the contract deployer", isSGXEnabledFlag: "Enables the SGX usage", } } diff --git a/testnet/launcher/cmd/main.go b/testnet/launcher/cmd/main.go index 4671e6a289..576679d504 100644 --- a/testnet/launcher/cmd/main.go +++ b/testnet/launcher/cmd/main.go @@ -17,6 +17,8 @@ func main() { launcher.WithValidatorEnclaveDebug(cliConfig.validatorEnclaveDebug), launcher.WithSequencerEnclaveDockerImage(cliConfig.sequencerEnclaveDockerImage), launcher.WithSequencerEnclaveDebug(cliConfig.sequencerEnclaveDebug), + launcher.WithContractDeployerDebug(cliConfig.contractDeployerDebug), + launcher.WithContractDeployerDockerImage(cliConfig.contractDeployerDockerImage), launcher.WithSGXEnabled(cliConfig.isSGXEnabled), ), ) diff --git a/testnet/launcher/config.go b/testnet/launcher/config.go index 75305b916b..aba2ee3f39 100644 --- a/testnet/launcher/config.go +++ b/testnet/launcher/config.go @@ -10,7 +10,11 @@ type Config struct { validatorEnclaveDockerImage string validatorEnclaveDebug bool - isSGXEnabled bool + + contractDeployerDockerImage string + contractDeployerDebug bool + + isSGXEnabled bool } func NewTestnetConfig(opts ...Option) *Config { @@ -52,3 +56,15 @@ func WithSGXEnabled(b bool) Option { c.isSGXEnabled = b } } + +func WithContractDeployerDockerImage(s string) Option { + return func(c *Config) { + c.contractDeployerDockerImage = s + } +} + +func WithContractDeployerDebug(b bool) Option { + return func(c *Config) { + c.contractDeployerDebug = b + } +} diff --git a/testnet/launcher/docker.go b/testnet/launcher/docker.go index ce936a0542..2f254307e1 100644 --- a/testnet/launcher/docker.go +++ b/testnet/launcher/docker.go @@ -33,7 +33,7 @@ func (t *Testnet) Start() error { return fmt.Errorf("unable to start eth2network - %w", err) } - networkConfig, err := deployL1Contracts() + networkConfig, err := t.deployL1Contracts() if err != nil { return fmt.Errorf("unable to deploy l1 contracts - %w", err) } @@ -129,7 +129,8 @@ func (t *Testnet) Start() error { l2cd.WithL2PrivateKey("8dfb8083da6275ae3e4f41e3e8a8c19d028d32c9247e24530933782f2a05035b"), l2cd.WithHocPKString("6e384a07a01263518a09a5424c7b6bbfc3604ba7d93f47e3a455cbdd7f9f0682"), l2cd.WithPocPKString("4bfe14725e685901c062ccd4e220c61cf9c189897b6c78bd18d7f51291b2b8f8"), - l2cd.WithDockerImage("testnetobscuronet.azurecr.io/obscuronet/hardhatdeployer:latest"), + l2cd.WithDockerImage(t.cfg.contractDeployerDockerImage), + l2cd.WithDebugEnabled(t.cfg.contractDeployerDebug), l2cd.WithFaucetFunds("10000"), ), ) @@ -183,12 +184,13 @@ func startEth2Network() error { return nil } -func deployL1Contracts() (*node.NetworkConfig, error) { +func (t *Testnet) deployL1Contracts() (*node.NetworkConfig, error) { l1ContractDeployer, err := l1cd.NewDockerContractDeployer( l1cd.NewContractDeployerConfig( l1cd.WithL1HTTPURL("http://eth2network:8025"), l1cd.WithPrivateKey("f52e5418e349dccdda29b6ac8b0abe6576bb7713886aa85abea6181ba731f9bb"), - l1cd.WithDockerImage("testnetobscuronet.azurecr.io/obscuronet/hardhatdeployer:latest"), + l1cd.WithDockerImage(t.cfg.contractDeployerDockerImage), + l1cd.WithDebugEnabled(t.cfg.contractDeployerDebug), ), ) if err != nil { diff --git a/testnet/launcher/l1contractdeployer/config.go b/testnet/launcher/l1contractdeployer/config.go index 0a6a6315cd..dd762482f5 100644 --- a/testnet/launcher/l1contractdeployer/config.go +++ b/testnet/launcher/l1contractdeployer/config.go @@ -5,9 +5,10 @@ type Option = func(c *Config) // Config holds the properties that configure the package type Config struct { - l1HTTPURL string - privateKey string - dockerImage string + l1HTTPURL string + privateKey string + dockerImage string + debugEnabled bool } func NewContractDeployerConfig(opts ...Option) *Config { @@ -37,3 +38,9 @@ func WithDockerImage(s string) Option { c.dockerImage = s } } + +func WithDebugEnabled(b bool) Option { + return func(c *Config) { + c.debugEnabled = b + } +} diff --git a/testnet/launcher/l1contractdeployer/docker.go b/testnet/launcher/l1contractdeployer/docker.go index 1a8478c209..071a889351 100644 --- a/testnet/launcher/l1contractdeployer/docker.go +++ b/testnet/launcher/l1contractdeployer/docker.go @@ -31,11 +31,17 @@ func NewDockerContractDeployer(cfg *Config) (*ContractDeployer, error) { func (n *ContractDeployer) Start() error { fmt.Printf("Starting L1 contract deployer with config: \n%s\n\n", litter.Sdump(*n.cfg)) - cmds := []string{ - "npx", "hardhat", "deploy", - "--network", "layer1", + cmds := []string{"npx"} + var ports []int + + // inspect stops operation until debugger is hooked on port 9229 if debug is enabled + if n.cfg.debugEnabled { + cmds = append(cmds, "--node-options=\"--inspect-brk=0.0.0.0:9229\"") + ports = append(ports, 9229) } + cmds = append(cmds, "hardhat", "deploy", "--network", "layer1") + envs := map[string]string{ "NETWORK_JSON": fmt.Sprintf(` { @@ -52,7 +58,7 @@ func (n *ContractDeployer) Start() error { `, n.cfg.l1HTTPURL, n.cfg.privateKey), } - containerID, err := docker.StartNewContainer("hh-l1-deployer", n.cfg.dockerImage, cmds, nil, envs, nil, nil) + containerID, err := docker.StartNewContainer("hh-l1-deployer", n.cfg.dockerImage, cmds, ports, envs, nil, nil) if err != nil { return err } @@ -73,10 +79,15 @@ func (n *ContractDeployer) RetrieveL1ContractAddresses() (*node.NetworkConfig, e return nil, err } + tailSize := "3" + if n.cfg.debugEnabled { + tailSize = "4" + } + logsOptions := types.ContainerLogsOptions{ ShowStdout: true, ShowStderr: true, - Tail: "3", + Tail: tailSize, } // Read the container logs @@ -93,12 +104,17 @@ func (n *ContractDeployer) RetrieveL1ContractAddresses() (*node.NetworkConfig, e return nil, err } - // Get the last three lines + // Get the last lines output := buf.String() fmt.Printf("L2 Deployer output %s\n", output) lines := strings.Split(output, "\n") + if n.cfg.debugEnabled { + // remove debugger lines + lines = lines[:len(lines)-2] + } + managementAddr, err := findAddress(lines[0]) if err != nil { return nil, err diff --git a/testnet/launcher/l2contractdeployer/config.go b/testnet/launcher/l2contractdeployer/config.go index 044081517b..753e7319aa 100644 --- a/testnet/launcher/l2contractdeployer/config.go +++ b/testnet/launcher/l2contractdeployer/config.go @@ -16,6 +16,7 @@ type Config struct { messageBusAddress string dockerImage string faucetPrefundAmount string + debugEnabled bool } func NewContractDeployerConfig(opts ...Option) *Config { @@ -95,3 +96,9 @@ func WithFaucetFunds(f string) Option { c.faucetPrefundAmount = f } } + +func WithDebugEnabled(b bool) Option { + return func(c *Config) { + c.debugEnabled = b + } +} diff --git a/testnet/launcher/l2contractdeployer/docker.go b/testnet/launcher/l2contractdeployer/docker.go index e7532de5a6..c1b0c2bcff 100644 --- a/testnet/launcher/l2contractdeployer/docker.go +++ b/testnet/launcher/l2contractdeployer/docker.go @@ -27,11 +27,17 @@ func NewDockerContractDeployer(cfg *Config) (*ContractDeployer, error) { func (n *ContractDeployer) Start() error { fmt.Printf("Starting L2 contract deployer with config: \n%s\n\n", litter.Sdump(*n.cfg)) - cmds := []string{ - "npx", "hardhat", "obscuro:deploy", - "--network", "layer2", + cmds := []string{"npx"} + var ports []int + + // inspect stops operation until debugger is hooked on port 9229 if debug is enabled + if n.cfg.debugEnabled { + cmds = append(cmds, "--node-options=\"--inspect-brk=0.0.0.0:9229\"") + ports = append(ports, 9229) } + cmds = append(cmds, "hardhat", "obscuro:deploy", "--network", "layer2") + envs := map[string]string{ "PREFUND_FAUCET_AMOUNT": n.cfg.faucetPrefundAmount, "MGMT_CONTRACT_ADDRESS": n.cfg.managementContractAddress, @@ -73,7 +79,7 @@ func (n *ContractDeployer) Start() error { `, n.cfg.l1HTTPURL, n.cfg.l1privateKey, n.cfg.l2Host, n.cfg.l2Port, n.cfg.l2PrivateKey, n.cfg.hocPKString, n.cfg.pocPKString), } - containerID, err := docker.StartNewContainer("hh-l2-deployer", n.cfg.dockerImage, cmds, nil, envs, nil, nil) + containerID, err := docker.StartNewContainer("hh-l2-deployer", n.cfg.dockerImage, cmds, ports, envs, nil, nil) if err != nil { return err } diff --git a/tools/hardhatdeployer/contract_deployer.go b/tools/hardhatdeployer/contract_deployer.go index d9a5839e95..bc5c9b921b 100644 --- a/tools/hardhatdeployer/contract_deployer.go +++ b/tools/hardhatdeployer/contract_deployer.go @@ -91,8 +91,8 @@ func (cd *contractDeployer) run() (string, error) { deployContractTx := types.LegacyTx{ Nonce: cd.wallet.GetNonceAndIncrement(), - GasPrice: big.NewInt(2000000000), - Gas: uint64(1025_000_000), + GasPrice: big.NewInt(1), + Gas: uint64(5_000_000), Data: cd.contractCode, } diff --git a/tools/walletextension/api/routes.go b/tools/walletextension/api/routes.go index 00f1745adb..2489511b12 100644 --- a/tools/walletextension/api/routes.go +++ b/tools/walletextension/api/routes.go @@ -160,6 +160,7 @@ func ethRequestHandler(walletExt *walletextension.WalletExtension, conn userconn } // Get userID + // TODO: @ziga - after removing old wallet extension endpoints we should prevent users doing anything without valid encryption token hexUserID, err := getUserID(conn, 1) if err != nil || !walletExt.UserExists(hexUserID) { walletExt.Logger().Info("user not found in the query params: %w. Using the default user", log.ErrKey, err) diff --git a/tools/walletextension/api/utils.go b/tools/walletextension/api/utils.go index 96f14038fa..fd9883843d 100644 --- a/tools/walletextension/api/utils.go +++ b/tools/walletextension/api/utils.go @@ -25,14 +25,14 @@ func parseRequest(body []byte) (*common.RPCRequest, error) { var method string err = json.Unmarshal(reqJSONMap[common.JSONKeyMethod], &method) if err != nil { - return nil, fmt.Errorf("could not unmarshal method string from JSON-RPC request body: %w", err) + return nil, fmt.Errorf("could not unmarshal method string from JSON-RPC request body: %s ; %w", string(body), err) } // we extract the params into a JSON list var params []interface{} err = json.Unmarshal(reqJSONMap[common.JSONKeyParams], ¶ms) if err != nil { - return nil, fmt.Errorf("could not unmarshal params list from JSON-RPC request body: %w", err) + return nil, fmt.Errorf("could not unmarshal params list from JSON-RPC request body: %s ; %w", string(body), err) } return &common.RPCRequest{ @@ -138,7 +138,7 @@ func handleEthError(req *common.RPCRequest, conn userconn.UserConn, logger gethl } func handleError(conn userconn.UserConn, logger gethlog.Logger, err error) { - logger.Error("error processing request - Forwarding response to user", log.ErrKey, err) + logger.Warn("error processing request - Forwarding response to user", log.ErrKey, err) if err = conn.WriteResponse([]byte(err.Error())); err != nil { logger.Error("unable to write response back", log.ErrKey, err) diff --git a/tools/walletextension/wallet_extension.go b/tools/walletextension/wallet_extension.go index eb71816728..55ee12fe98 100644 --- a/tools/walletextension/wallet_extension.go +++ b/tools/walletextension/wallet_extension.go @@ -309,9 +309,11 @@ func (w *WalletExtension) UserExists(hexUserID string) bool { return false } + // Check if user exists and don't log error if user doesn't exist, because we expect this to happen in case of + // user revoking encryption token or using different testnet. + // todo add a counter here in the future key, err := w.storage.GetUserPrivateKey(userIDBytes) if err != nil { - w.Logger().Error(fmt.Errorf("error getting user's private key (%s), %w", hexUserID, err).Error()) return false }