From ce988459ceca8ec1a84d6e982e9430a166672103 Mon Sep 17 00:00:00 2001 From: envestcc Date: Mon, 25 Nov 2024 09:06:58 +0000 Subject: [PATCH] trace log --- action/protocol/execution/evm/evm.go | 15 ++-- .../execution/evm/evmstatedbadapter.go | 82 +++++++++++-------- actpool/actpool.go | 2 +- api/coreservice.go | 6 +- api/web3server.go | 22 ++--- api/web3server_test.go | 16 ++-- 6 files changed, 77 insertions(+), 66 deletions(-) diff --git a/action/protocol/execution/evm/evm.go b/action/protocol/execution/evm/evm.go index 116e856a96..048cd625cf 100644 --- a/action/protocol/execution/evm/evm.go +++ b/action/protocol/execution/evm/evm.go @@ -245,7 +245,7 @@ func ExecuteContract( if err != nil { return nil, nil, err } - retval, depositGas, remainingGas, contractAddress, statusCode, err := executeInEVM(ps, stateDB) + retval, depositGas, remainingGas, contractAddress, statusCode, err := executeInEVM(ctx, ps, stateDB) if err != nil { return nil, nil, err } @@ -380,6 +380,7 @@ func prepareStateDB(ctx context.Context, sm protocol.StateManager) (*StateDBAdap } if featureCtx.FixRevertSnapshot || actionCtx.ReadOnly { opts = append(opts, FixRevertSnapshotOption()) + opts = append(opts, WithContext(ctx)) } return NewStateDBAdapter( sm, @@ -427,7 +428,7 @@ func getChainConfig(g genesis.Blockchain, height uint64, id uint32, getBlockTime } // Error in executeInEVM is a consensus issue -func executeInEVM(evmParams *Params, stateDB *StateDBAdapter) ([]byte, uint64, uint64, string, iotextypes.ReceiptStatus, error) { +func executeInEVM(ctx context.Context, evmParams *Params, stateDB *StateDBAdapter) ([]byte, uint64, uint64, string, iotextypes.ReceiptStatus, error) { var ( gasLimit = evmParams.blkCtx.GasLimit blockHeight = evmParams.blkCtx.BlockHeight @@ -436,7 +437,7 @@ func executeInEVM(evmParams *Params, stateDB *StateDBAdapter) ([]byte, uint64, u chainConfig = evmParams.chainConfig ) if err := securityDeposit(evmParams, stateDB, gasLimit); err != nil { - log.L().Warn("unexpected error: not enough security deposit", zap.Error(err)) + log.T(ctx).Warn("unexpected error: not enough security deposit", zap.Error(err)) return nil, 0, 0, action.EmptyAddress, iotextypes.ReceiptStatus_Failure, err } var ( @@ -472,7 +473,7 @@ func executeInEVM(evmParams *Params, stateDB *StateDBAdapter) ([]byte, uint64, u // create contract var evmContractAddress common.Address _, evmContractAddress, remainingGas, evmErr = evm.Create(executor, evmParams.data, remainingGas, amount) - log.L().Debug("evm Create.", log.Hex("addrHash", evmContractAddress[:])) + log.T(ctx).Debug("evm Create.", log.Hex("addrHash", evmContractAddress[:])) if evmErr == nil { if contractAddress, err := address.FromBytes(evmContractAddress.Bytes()); err == nil { contractRawAddress = contractAddress.String() @@ -484,7 +485,7 @@ func executeInEVM(evmParams *Params, stateDB *StateDBAdapter) ([]byte, uint64, u ret, remainingGas, evmErr = evm.Call(executor, *evmParams.contract, evmParams.data, remainingGas, amount) } if evmErr != nil { - log.L().Debug("evm error", zap.Error(evmErr)) + log.T(ctx).Debug("evm error", zap.Error(evmErr)) // The only possible consensus-error would be if there wasn't // sufficient balance to make the transfer happen. // Should be a hard fork (Bering) @@ -493,7 +494,7 @@ func executeInEVM(evmParams *Params, stateDB *StateDBAdapter) ([]byte, uint64, u } } if stateDB.Error() != nil { - log.L().Debug("statedb error", zap.Error(stateDB.Error())) + log.T(ctx).Debug("statedb error", zap.Error(stateDB.Error())) } if !rules.IsLondon { // Before EIP-3529: refunds were capped to gasUsed / 2 @@ -532,7 +533,7 @@ func executeInEVM(evmParams *Params, stateDB *StateDBAdapter) ([]byte, uint64, u } else { addr = "contract creation" } - log.L().Warn("evm internal error", zap.Error(evmErr), + log.T(ctx).Warn("evm internal error", zap.Error(evmErr), zap.String("address", addr), log.Hex("calldata", evmParams.data)) } diff --git a/action/protocol/execution/evm/evmstatedbadapter.go b/action/protocol/execution/evm/evmstatedbadapter.go index 851f2407d9..7c38333ae4 100644 --- a/action/protocol/execution/evm/evmstatedbadapter.go +++ b/action/protocol/execution/evm/evmstatedbadapter.go @@ -7,6 +7,7 @@ package evm import ( "bytes" + "context" "encoding/hex" "fmt" "math/big" @@ -46,6 +47,7 @@ type ( // StateDBAdapter represents the state db adapter for evm to access iotx blockchain StateDBAdapter struct { + ctx context.Context sm protocol.StateManager logs []*action.Log transactionLogs []*action.TransactionLog @@ -196,6 +198,13 @@ func FixRevertSnapshotOption() StateDBAdapterOption { } } +func WithContext(ctx context.Context) StateDBAdapterOption { + return func(adapter *StateDBAdapter) error { + adapter.ctx = ctx + return nil + } +} + // NewStateDBAdapter creates a new state db with iotex blockchain func NewStateDBAdapter( sm protocol.StateManager, @@ -221,6 +230,7 @@ func NewStateDBAdapter( accessListSnapshot: make(map[int]*accessList), logsSnapshot: make(map[int]int), txLogsSnapshot: make(map[int]int), + ctx: context.Background(), } for _, opt := range opts { if err := opt(s); err != nil { @@ -251,9 +261,9 @@ func (stateDB *StateDBAdapter) assertError(err error, msg string, fields ...zap. return false } if stateDB.panicUnrecoverableError { - log.L().Panic(msg, fields...) + log.T(stateDB.ctx).Panic(msg, fields...) } - log.L().Error(msg, fields...) + log.T(stateDB.ctx).Error(msg, fields...) stateDB.logError(err) return true } @@ -286,7 +296,7 @@ func (stateDB *StateDBAdapter) CreateAccount(evmAddr common.Address) { if stateDB.enableCancun { stateDB.createdAccount[evmAddr] = struct{}{} } - log.L().Debug("Called CreateAccount.", log.Hex("addrHash", evmAddr[:])) + log.T(stateDB.ctx).Debug("Called CreateAccount.", log.Hex("addrHash", evmAddr[:])) } // SubBalance subtracts balance from account @@ -296,7 +306,7 @@ func (stateDB *StateDBAdapter) SubBalance(evmAddr common.Address, a256 *uint256. return } // stateDB.GetBalance(evmAddr) - log.L().Debug(fmt.Sprintf("SubBalance %v from %s", amount, evmAddr.Hex())) + log.T(stateDB.ctx).Debug(fmt.Sprintf("SubBalance %v from %s", amount, evmAddr.Hex())) addr, err := address.FromBytes(evmAddr.Bytes()) if stateDB.assertError(err, "Failed to convert evm address.", zap.Error(err)) { return @@ -323,7 +333,7 @@ func (stateDB *StateDBAdapter) AddBalance(evmAddr common.Address, a256 *uint256. return } // stateDB.GetBalance(evmAddr) - log.L().Debug(fmt.Sprintf("AddBalance %v to %s", amount, evmAddr.Hex())) + log.T(stateDB.ctx).Debug(fmt.Sprintf("AddBalance %v to %s", amount, evmAddr.Hex())) addr, err := address.FromBytes(evmAddr.Bytes()) if stateDB.assertError(err, "Failed to convert evm address.", zap.Error(err)) { @@ -360,7 +370,7 @@ func (stateDB *StateDBAdapter) GetBalance(evmAddr common.Address) *uint256.Int { if stateDB.assertError(err, "Failed to get balance.", zap.Error(err), zap.String("address", evmAddr.Hex())) { return common.U2560 } - log.L().Debug(fmt.Sprintf("Balance of %s is %v", evmAddr.Hex(), state.Balance)) + log.T(stateDB.ctx).Debug(fmt.Sprintf("Balance of %s is %v", evmAddr.Hex(), state.Balance)) return uint256.MustFromBig(state.Balance) } @@ -386,9 +396,9 @@ func (stateDB *StateDBAdapter) GetNonce(evmAddr common.Address) uint64 { state, err := stateDB.accountState(evmAddr) if err != nil { if stateDB.panicUnrecoverableError { - log.L().Panic("Failed to get nonce.", zap.Error(err)) + log.T(stateDB.ctx).Panic("Failed to get nonce.", zap.Error(err)) } else { - log.L().Error("Failed to get nonce.", zap.Error(err)) + log.T(stateDB.ctx).Error("Failed to get nonce.", zap.Error(err)) stateDB.logError(err) } } else { @@ -404,7 +414,7 @@ func (stateDB *StateDBAdapter) GetNonce(evmAddr common.Address) uint64 { } pendingNonce-- } - log.L().Debug("Called GetNonce.", + log.T(stateDB.ctx).Debug("Called GetNonce.", zap.String("address", evmAddr.Hex()), zap.Uint64("pendingNonce", pendingNonce)) @@ -427,12 +437,12 @@ func (stateDB *StateDBAdapter) SetNonce(evmAddr common.Address, nonce uint64) { } nonce-- } - log.L().Debug("Called SetNonce.", + log.T(stateDB.ctx).Debug("Called SetNonce.", zap.String("address", addr.String()), zap.Uint64("nonce", nonce)) if !s.IsNewbieAccount() || s.AccountType() != 0 || nonce != 0 || stateDB.zeroNonceForFreshAccount { if err := s.SetPendingNonce(nonce + 1); err != nil { - log.L().Panic("Failed to set nonce.", zap.Error(err), zap.String("addr", addr.Hex()), zap.Uint64("pendingNonce", s.PendingNonce()), zap.Uint64("nonce", nonce), zap.String("execution", hex.EncodeToString(stateDB.executionHash[:]))) + log.T(stateDB.ctx).Panic("Failed to set nonce.", zap.Error(err), zap.String("addr", addr.Hex()), zap.Uint64("pendingNonce", s.PendingNonce()), zap.Uint64("nonce", nonce), zap.String("execution", hex.EncodeToString(stateDB.executionHash[:]))) stateDB.logError(err) } } @@ -442,7 +452,7 @@ func (stateDB *StateDBAdapter) SetNonce(evmAddr common.Address, nonce uint64) { // SubRefund subtracts refund func (stateDB *StateDBAdapter) SubRefund(gas uint64) { - log.L().Debug("Called SubRefund.", zap.Uint64("gas", gas)) + log.T(stateDB.ctx).Debug("Called SubRefund.", zap.Uint64("gas", gas)) // stateDB.journal.append(refundChange{prev: self.refund}) if gas > stateDB.refund { panic("Refund counter not enough!") @@ -452,21 +462,21 @@ func (stateDB *StateDBAdapter) SubRefund(gas uint64) { // AddRefund adds refund func (stateDB *StateDBAdapter) AddRefund(gas uint64) { - log.L().Debug("Called AddRefund.", zap.Uint64("gas", gas)) + log.T(stateDB.ctx).Debug("Called AddRefund.", zap.Uint64("gas", gas)) // stateDB.journal.append(refundChange{prev: self.refund}) stateDB.refund += gas } // GetRefund gets refund func (stateDB *StateDBAdapter) GetRefund() uint64 { - log.L().Debug("Called GetRefund.") + log.T(stateDB.ctx).Debug("Called GetRefund.") return stateDB.refund } // SelfDestruct kills the contract func (stateDB *StateDBAdapter) SelfDestruct(evmAddr common.Address) { if !stateDB.Exist(evmAddr) { - log.L().Debug("Account does not exist.", zap.String("address", evmAddr.Hex())) + log.T(stateDB.ctx).Debug("Account does not exist.", zap.String("address", evmAddr.Hex())) return } s, err := stateDB.accountState(evmAddr) @@ -475,7 +485,7 @@ func (stateDB *StateDBAdapter) SelfDestruct(evmAddr common.Address) { } // clears the account balance actBalance := new(big.Int).Set(s.Balance) - log.L().Info("SelfDestruct contract", zap.String("Balance", actBalance.String())) + log.T(stateDB.ctx).Info("SelfDestruct contract", zap.String("Balance", actBalance.String())) err = s.SubBalance(s.Balance) if stateDB.assertError(err, "Failed to clear balance.", zap.Error(err), zap.String("address", evmAddr.Hex())) { return @@ -501,7 +511,7 @@ func (stateDB *StateDBAdapter) HasSelfDestructed(evmAddr common.Address) bool { // Selfdestruct6780 implements EIP-6780 func (stateDB *StateDBAdapter) Selfdestruct6780(evmAddr common.Address) { if !stateDB.Exist(evmAddr) { - log.L().Debug("Account does not exist.", zap.String("address", evmAddr.Hex())) + log.T(stateDB.ctx).Debug("Account does not exist.", zap.String("address", evmAddr.Hex())) return } // opSelfdestruct6780 has already subtracted the contract's balance @@ -534,7 +544,7 @@ func (stateDB *StateDBAdapter) Exist(evmAddr common.Address) bool { if stateDB.assertError(err, "Failed to convert evm address.", zap.Error(err)) { return false } - log.L().Debug("Check existence.", zap.String("address", addr.String()), log.Hex("addrHash", evmAddr[:])) + log.T(stateDB.ctx).Debug("Check existence.", zap.String("address", addr.String()), log.Hex("addrHash", evmAddr[:])) if _, ok := stateDB.cachedContract[evmAddr]; ok { return true } @@ -543,7 +553,7 @@ func (stateDB *StateDBAdapter) Exist(evmAddr common.Address) bool { return false } if !recorded { - log.L().Debug("Account does not exist.", zap.String("address", addr.String())) + log.T(stateDB.ctx).Debug("Account does not exist.", zap.String("address", addr.String())) return false } return true @@ -609,7 +619,7 @@ func (stateDB *StateDBAdapter) AddSlotToAccessList(addr common.Address, slot com // Empty returns true if the the contract is empty func (stateDB *StateDBAdapter) Empty(evmAddr common.Address) bool { - log.L().Debug("Check whether the contract is empty.") + log.T(stateDB.ctx).Debug("Check whether the contract is empty.") s, err := stateDB.accountState(evmAddr) if stateDB.assertError(err, "Failed to get account.", zap.Error(err), zap.String("address", evmAddr.Hex())) { return true @@ -624,7 +634,7 @@ func (stateDB *StateDBAdapter) Empty(evmAddr common.Address) bool { func (stateDB *StateDBAdapter) RevertToSnapshot(snapshot int) { ds, ok := stateDB.selfDestructedSnapshot[snapshot] if !ok && stateDB.panicUnrecoverableError { - log.L().Panic("Failed to revert to snapshot.", zap.Int("snapshot", snapshot)) + log.T(stateDB.ctx).Panic("Failed to revert to snapshot.", zap.Int("snapshot", snapshot)) } err := stateDB.sm.Revert(snapshot) if stateDB.assertError(err, "state manager's Revert() failed.", zap.Error(err), zap.Int("snapshot", snapshot)) { @@ -632,7 +642,7 @@ func (stateDB *StateDBAdapter) RevertToSnapshot(snapshot int) { } if !ok { // this should not happen, b/c we save the SelfDestruct accounts on a successful return of Snapshot(), but check anyway - log.L().Error("Failed to revert to snapshot.", zap.Int("snapshot", snapshot)) + log.T(stateDB.ctx).Error("Failed to revert to snapshot.", zap.Int("snapshot", snapshot)) return } deleteSnapshot := snapshot @@ -720,7 +730,7 @@ func (stateDB *StateDBAdapter) RevertToSnapshot(snapshot int) { for _, addr := range stateDB.cachedContractAddrs() { c := stateDB.cachedContract[addr] if err := c.LoadRoot(); err != nil { - log.L().Error("Failed to load root for contract.", zap.Error(err), log.Hex("addrHash", addr[:])) + log.T(stateDB.ctx).Error("Failed to load root for contract.", zap.Error(err), log.Hex("addrHash", addr[:])) return } } @@ -770,9 +780,9 @@ func (stateDB *StateDBAdapter) Snapshot() int { if _, ok := stateDB.selfDestructedSnapshot[sn]; ok { err := errors.New("unexpected error: duplicate snapshot version") if stateDB.fixSnapshotOrder { - log.L().Panic("Failed to snapshot.", zap.Error(err)) + log.T(stateDB.ctx).Panic("Failed to snapshot.", zap.Error(err)) } else { - log.L().Error("Failed to snapshot.", zap.Error(err)) + log.T(stateDB.ctx).Error("Failed to snapshot.", zap.Error(err)) } // stateDB.err = err return sn @@ -819,7 +829,7 @@ func (stateDB *StateDBAdapter) Snapshot() int { // AddLog adds log whose transaction amount is larger than 0 func (stateDB *StateDBAdapter) AddLog(evmLog *types.Log) { - log.L().Debug("Called AddLog.", zap.Any("log", evmLog)) + log.T(stateDB.ctx).Debug("Called AddLog.", zap.Any("log", evmLog)) addr, err := address.FromBytes(evmLog.Address.Bytes()) if stateDB.assertError(err, "Failed to convert evm address.", zap.Error(err)) { return @@ -929,7 +939,7 @@ func (stateDB *StateDBAdapter) generateSelfDestructTransferLog(sender string, am }) } } else { - log.L().Panic("SelfDestruct contract's balance does not match", + log.T(stateDB.ctx).Panic("SelfDestruct contract's balance does not match", zap.String("beneficiary", stateDB.lastAddBalanceAmount.String())) } } @@ -963,7 +973,7 @@ func (stateDB *StateDBAdapter) GetCode(evmAddr common.Address) []byte { if contract, ok := stateDB.cachedContract[evmAddr]; ok { code, err := contract.GetCode() if err != nil { - log.L().Error("Failed to get code hash.", zap.Error(err)) + log.T(stateDB.ctx).Error("Failed to get code hash.", zap.Error(err)) return nil } return code @@ -984,7 +994,7 @@ func (stateDB *StateDBAdapter) GetCode(evmAddr common.Address) []byte { // GetCodeSize gets the code size saved in hash func (stateDB *StateDBAdapter) GetCodeSize(evmAddr common.Address) int { code := stateDB.GetCode(evmAddr) - log.L().Debug("Called GetCodeSize.", log.Hex("addrHash", evmAddr[:])) + log.T(stateDB.ctx).Debug("Called GetCodeSize.", log.Hex("addrHash", evmAddr[:])) return len(code) } @@ -992,7 +1002,7 @@ func (stateDB *StateDBAdapter) GetCodeSize(evmAddr common.Address) int { func (stateDB *StateDBAdapter) SetCode(evmAddr common.Address, code []byte) { contract, err := stateDB.getContract(evmAddr) if err != nil { - log.L().Error("Failed to get contract.", zap.Error(err), zap.String("address", evmAddr.Hex())) + log.T(stateDB.ctx).Error("Failed to get contract.", zap.Error(err), zap.String("address", evmAddr.Hex())) stateDB.logError(err) return } @@ -1003,13 +1013,13 @@ func (stateDB *StateDBAdapter) SetCode(evmAddr common.Address, code []byte) { func (stateDB *StateDBAdapter) GetCommittedState(evmAddr common.Address, k common.Hash) common.Hash { contract, err := stateDB.getContract(evmAddr) if err != nil { - log.L().Error("Failed to get contract.", zap.Error(err), zap.String("address", evmAddr.Hex())) + log.T(stateDB.ctx).Error("Failed to get contract.", zap.Error(err), zap.String("address", evmAddr.Hex())) stateDB.logError(err) return common.Hash{} } v, err := contract.GetCommittedState(hash.BytesToHash256(k[:])) if err != nil { - log.L().Debug("Failed to get committed state.", zap.Error(err)) + log.T(stateDB.ctx).Debug("Failed to get committed state.", zap.Error(err)) stateDB.logError(err) return common.Hash{} } @@ -1020,13 +1030,13 @@ func (stateDB *StateDBAdapter) GetCommittedState(evmAddr common.Address, k commo func (stateDB *StateDBAdapter) GetState(evmAddr common.Address, k common.Hash) common.Hash { contract, err := stateDB.getContract(evmAddr) if err != nil { - log.L().Error("Failed to get contract.", zap.Error(err), zap.String("address", evmAddr.Hex())) + log.T(stateDB.ctx).Error("Failed to get contract.", zap.Error(err), zap.String("address", evmAddr.Hex())) stateDB.logError(err) return common.Hash{} } v, err := contract.GetState(hash.BytesToHash256(k[:])) if err != nil { - log.L().Debug("Failed to get state.", zap.Error(err)) + log.T(stateDB.ctx).Debug("Failed to get state.", zap.Error(err)) stateDB.logError(err) return common.Hash{} } @@ -1037,11 +1047,11 @@ func (stateDB *StateDBAdapter) GetState(evmAddr common.Address, k common.Hash) c func (stateDB *StateDBAdapter) SetState(evmAddr common.Address, k, v common.Hash) { contract, err := stateDB.getContract(evmAddr) if err != nil { - log.L().Error("Failed to get contract.", zap.Error(err), zap.String("address", evmAddr.Hex())) + log.T(stateDB.ctx).Error("Failed to get contract.", zap.Error(err), zap.String("address", evmAddr.Hex())) stateDB.logError(err) return } - log.L().Debug("Called SetState", log.Hex("addrHash", evmAddr[:]), log.Hex("k", k[:])) + log.T(stateDB.ctx).Debug("Called SetState", log.Hex("addrHash", evmAddr[:]), log.Hex("k", k[:])) err = contract.SetState(hash.BytesToHash256(k[:]), v[:]) stateDB.assertError(err, "Failed to set state.", zap.Error(err), zap.String("address", evmAddr.Hex())) } diff --git a/actpool/actpool.go b/actpool/actpool.go index 5716435a2b..781ea5dbaf 100644 --- a/actpool/actpool.go +++ b/actpool/actpool.go @@ -534,7 +534,7 @@ func (ap *actPool) enqueue(ctx context.Context, act *action.SealedEnvelope, repl for { select { case <-ctx.Done(): - log.L().Error("enqueue actpool fails", zap.Error(ctx.Err())) + log.T(ctx).Error("enqueue actpool fails", zap.Error(ctx.Err())) return ctx.Err() case ret := <-errChan: return ret diff --git a/api/coreservice.go b/api/coreservice.go index e8203aae6b..87768e21a9 100644 --- a/api/coreservice.go +++ b/api/coreservice.go @@ -445,7 +445,7 @@ func (core *coreService) ServerMeta() (packageVersion string, packageCommitID st // SendAction is the API to send an action to blockchain. func (core *coreService) SendAction(ctx context.Context, in *iotextypes.Action) (string, error) { - log.Logger("api").Debug("receive send action request") + log.T(ctx).Debug("receive send action request") selp, err := (&action.Deserializer{}).SetEvmNetworkID(core.EVMNetworkID()).ActionToSealedEnvelope(in) if err != nil { return "", status.Error(codes.InvalidArgument, err.Error()) @@ -470,7 +470,7 @@ func (core *coreService) SendAction(ctx context.Context, in *iotextypes.Action) if err != nil { return "", err } - l := log.Logger("api").With(zap.String("actionHash", hex.EncodeToString(hash[:]))) + l := log.T(ctx).Logger().With(zap.String("actionHash", hex.EncodeToString(hash[:]))) if err = core.ap.Add(ctx, selp); err != nil { txBytes, serErr := proto.Marshal(in) if serErr != nil { @@ -489,7 +489,7 @@ func (core *coreService) SendAction(ctx context.Context, in *iotextypes.Action) } st, err := st.WithDetails(br) if err != nil { - log.Logger("api").Panic("Unexpected error attaching metadata", zap.Error(err)) + log.T(ctx).Panic("Unexpected error attaching metadata", zap.Error(err)) } return "", st.Err() } diff --git a/api/web3server.go b/api/web3server.go index b7d8eefbf9..015b80ba51 100644 --- a/api/web3server.go +++ b/api/web3server.go @@ -150,7 +150,7 @@ func (svr *web3Handler) handleWeb3Req(ctx context.Context, web3Req *gjson.Result ) defer func(start time.Time) { svr.coreService.Track(ctx, start, method.(string), int64(size), err == nil) }(time.Now()) - log.T(ctx).Debug("handleWeb3Req", zap.String("method", method.(string)), zap.String("requestParams", fmt.Sprintf("%+v", web3Req))) + log.T(ctx).Info("handleWeb3Req", zap.String("method", method.(string)), zap.String("requestParams", fmt.Sprintf("%+v", web3Req))) _web3ServerMtc.WithLabelValues(method.(string)).Inc() _web3ServerMtc.WithLabelValues("requests_total").Inc() switch method { @@ -171,7 +171,7 @@ func (svr *web3Handler) handleWeb3Req(ctx context.Context, web3Req *gjson.Result case "eth_getTransactionCount": res, err = svr.getTransactionCount(web3Req) case "eth_call": - res, err = svr.call(web3Req) + res, err = svr.call(ctx, web3Req) case "eth_getCode": res, err = svr.getCode(web3Req) case "eth_protocolVersion": @@ -201,9 +201,9 @@ func (svr *web3Handler) handleWeb3Req(ctx context.Context, web3Req *gjson.Result case "eth_getBlockByNumber": res, err = svr.getBlockByNumber(web3Req) case "eth_estimateGas": - res, err = svr.estimateGas(web3Req) + res, err = svr.estimateGas(ctx, web3Req) case "eth_sendRawTransaction": - res, err = svr.sendRawTransaction(web3Req) + res, err = svr.sendRawTransaction(ctx, web3Req) case "eth_getTransactionByHash": res, err = svr.getTransactionByHash(web3Req) case "eth_getTransactionByBlockNumberAndIndex": @@ -381,7 +381,7 @@ func (svr *web3Handler) getTransactionCount(in *gjson.Result) (interface{}, erro return uint64ToHex(pendingNonce), nil } -func (svr *web3Handler) call(in *gjson.Result) (interface{}, error) { +func (svr *web3Handler) call(ctx context.Context, in *gjson.Result) (interface{}, error) { callerAddr, to, gasLimit, _, value, data, err := parseCallObject(in) if err != nil { return nil, err @@ -421,7 +421,7 @@ func (svr *web3Handler) call(in *gjson.Result) (interface{}, error) { } elp := (&action.EnvelopeBuilder{}).SetAction(action.NewExecution(to, value, data)). SetGasLimit(gasLimit).Build() - ret, receipt, err := svr.coreService.ReadContract(context.Background(), callerAddr, elp) + ret, receipt, err := svr.coreService.ReadContract(ctx, callerAddr, elp) if err != nil { return nil, err } @@ -434,7 +434,7 @@ func (svr *web3Handler) call(in *gjson.Result) (interface{}, error) { return "0x" + ret, nil } -func (svr *web3Handler) estimateGas(in *gjson.Result) (interface{}, error) { +func (svr *web3Handler) estimateGas(ctx context.Context, in *gjson.Result) (interface{}, error) { from, to, gasLimit, _, value, data, err := parseCallObject(in) if err != nil { return nil, err @@ -467,9 +467,9 @@ func (svr *web3Handler) estimateGas(in *gjson.Result) (interface{}, error) { var estimatedGas uint64 switch act := elp.Action().(type) { case *action.Execution: - estimatedGas, err = svr.coreService.EstimateExecutionGasConsumption(context.Background(), elp, from) + estimatedGas, err = svr.coreService.EstimateExecutionGasConsumption(ctx, elp, from) case *action.MigrateStake: - estimatedGas, err = svr.coreService.EstimateMigrateStakeGasConsumption(context.Background(), act, from) + estimatedGas, err = svr.coreService.EstimateMigrateStakeGasConsumption(ctx, act, from) default: estimatedGas, err = svr.coreService.EstimateGasForNonExecution(act) } @@ -482,7 +482,7 @@ func (svr *web3Handler) estimateGas(in *gjson.Result) (interface{}, error) { return uint64ToHex(estimatedGas), nil } -func (svr *web3Handler) sendRawTransaction(in *gjson.Result) (interface{}, error) { +func (svr *web3Handler) sendRawTransaction(ctx context.Context, in *gjson.Result) (interface{}, error) { dataStr := in.Get("params.0") if !dataStr.Exists() { return nil, errInvalidFormat @@ -546,7 +546,7 @@ func (svr *web3Handler) sendRawTransaction(in *gjson.Result) (interface{}, error Encoding: encoding, } } - actionHash, err := cs.SendAction(context.Background(), req) + actionHash, err := cs.SendAction(ctx, req) if err != nil { return nil, err } diff --git a/api/web3server_test.go b/api/web3server_test.go index 1ad7ea524c..e8d333b3c1 100644 --- a/api/web3server_test.go +++ b/api/web3server_test.go @@ -317,7 +317,7 @@ func TestCall(t *testing.T) { "data": "d201114a" }, 1]}`) - ret, err := web3svr.call(&in) + ret, err := web3svr.call(context.Background(), &in) require.NoError(err) require.Equal("0x0000000000000000000000000000000000000000000000056bc75e2d63100000", ret.(string)) }) @@ -336,7 +336,7 @@ func TestCall(t *testing.T) { "data": "ad7a672f" }, 1]}`) - ret, err := web3svr.call(&in) + ret, err := web3svr.call(context.Background(), &in) require.NoError(err) require.Equal("0x0000000000000000000000000000000000000000000000000000000000002710", ret.(string)) }) @@ -352,7 +352,7 @@ func TestCall(t *testing.T) { "data": "0x1" }, 1]}`) - ret, err := web3svr.call(&in) + ret, err := web3svr.call(context.Background(), &in) require.NoError(err) require.Equal("0x111111", ret.(string)) }) @@ -378,7 +378,7 @@ func TestCall(t *testing.T) { "data": "0x1" }, 1]}`) - _, err := web3svr.call(&in) + _, err := web3svr.call(context.Background(), &in) require.EqualError(err, "rpc error: code = InvalidArgument desc = execution reverted: "+receipt.GetExecutionRevertMsg()) }) } @@ -404,7 +404,7 @@ func TestEstimateGas(t *testing.T) { "data": "0x6d4ce63c" }, 1]}`) - ret, err := web3svr.estimateGas(&in) + ret, err := web3svr.estimateGas(context.Background(), &in) require.NoError(err) require.Equal(uint64ToHex(uint64(21000)), ret.(string)) }) @@ -422,7 +422,7 @@ func TestEstimateGas(t *testing.T) { "data": "0x1123123c" }, 1]}`) - ret, err := web3svr.estimateGas(&in) + ret, err := web3svr.estimateGas(context.Background(), &in) require.NoError(err) require.Equal(uint64ToHex(uint64(36000)), ret.(string)) }) @@ -443,13 +443,13 @@ func TestSendRawTransaction(t *testing.T) { t.Run("nil params", func(t *testing.T) { inNil := gjson.Parse(`{"params":[]}`) - _, err := web3svr.sendRawTransaction(&inNil) + _, err := web3svr.sendRawTransaction(context.Background(), &inNil) require.EqualError(err, errInvalidFormat.Error()) }) t.Run("send tx", func(t *testing.T) { in := gjson.Parse(`{"params":["f8600180830186a09412745fec82b585f239c01090882eb40702c32b04808025a0b0e1aab5b64d744ae01fc9f1c3e9919844a799e90c23129d611f7efe6aec8a29a0195e28d22d9b280e00d501ff63525bb76f5c87b8646c89d5d9c5485edcb1b498"]}`) - ret, err := web3svr.sendRawTransaction(&in) + ret, err := web3svr.sendRawTransaction(context.Background(), &in) require.NoError(err) require.Equal("0x111111111111111", ret.(string)) })