-
Notifications
You must be signed in to change notification settings - Fork 12
/
grpc_query.go
433 lines (373 loc) · 13 KB
/
grpc_query.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
package keeper
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/big"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/eth/tracers"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
ethparams "github.com/ethereum/go-ethereum/params"
etherminttypes "github.com/evmos/ethermint/types"
evmkeeper "github.com/evmos/ethermint/x/evm/keeper"
"github.com/evmos/ethermint/x/evm/statedb"
"github.com/evmos/ethermint/x/evm/types"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
defaultTraceTimeout = 5 * time.Second
)
// EthCall implements eth_call rpc api.
func (k *Keeper) EthCall(c context.Context, req *types.EthCallRequest) (*types.MsgEthereumTxResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
ctx := sdk.UnwrapSDKContext(c)
var args types.TransactionArgs
err := json.Unmarshal(req.Args, &args)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
chainID, err := getChainID(ctx, req.ChainId)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
cfg, err := k.EVMConfig(ctx, evmkeeper.GetProposerAddress(ctx, req.ProposerAddress), chainID)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
// ApplyMessageWithConfig expect correct nonce set in msg
nonce := k.GetNonce(ctx, args.GetFrom())
args.Nonce = (*hexutil.Uint64)(&nonce)
msg, err := args.ToMessage(req.GasCap, cfg.BaseFee)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
txConfig := statedb.NewEmptyTxConfig(common.BytesToHash(ctx.HeaderHash()))
// pass false to not commit StateDB
res, err := k.ApplyMessageWithConfig(ctx, msg, nil, false, cfg, txConfig)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return res, nil
}
// EstimateGas implements eth_estimateGas rpc api with enable hook flag.
//
//gocyclo:ignore
func (k *Keeper) EstimateGas(c context.Context, req *types.EthCallRequest) (*types.EstimateGasResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
ctx := sdk.UnwrapSDKContext(c)
chainID, err := getChainID(ctx, req.ChainId)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
if req.GasCap < ethparams.TxGas {
return nil, status.Error(codes.InvalidArgument, "gas gasCap cannot be lower than 21,000")
}
var args types.TransactionArgs
err = json.Unmarshal(req.Args, &args)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
// Binary search the gas requirement, as it may be higher than the amount used
var (
lo = ethparams.TxGas - 1
hi uint64
gasCap uint64
)
// Determine the highest gas limit can be used during the estimation.
if args.Gas != nil && uint64(*args.Gas) >= ethparams.TxGas {
hi = uint64(*args.Gas)
} else {
// Query block gas limit
params := ctx.ConsensusParams()
if params != nil && params.Block != nil && params.Block.MaxGas > 0 {
hi = uint64(params.Block.MaxGas)
} else {
hi = req.GasCap
}
}
// TODO: Recap the highest gas limit with account's available balance.
// Recap the highest gas allowance with specified gasCap.
if req.GasCap != 0 && hi > req.GasCap {
hi = req.GasCap
}
gasCap = hi
cfg, err := k.EVMConfig(ctx, evmkeeper.GetProposerAddress(ctx, req.ProposerAddress), chainID)
if err != nil {
return nil, status.Error(codes.Internal, "failed to load evm config")
}
// ApplyMessageWithConfig expect correct nonce set in msg
nonce := k.GetNonce(ctx, args.GetFrom())
args.Nonce = (*hexutil.Uint64)(&nonce)
txConfig := statedb.NewEmptyTxConfig(common.BytesToHash(ctx.HeaderHash().Bytes()))
// convert the tx args to an ethereum message
msg, err := args.ToMessage(req.GasCap, cfg.BaseFee)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
// NOTE: the errors from the executable below should be consistent with go-ethereum,
// so we don't wrap them with the gRPC status code
// Create a helper to check if a gas allowance results in an executable transaction
executable := func(gas uint64) (vmError bool, rsp *types.MsgEthereumTxResponse, err error) {
// update the message with the new gas value
msg = ethtypes.NewMessage(
msg.From(),
msg.To(),
msg.Nonce(),
msg.Value(),
gas,
msg.GasPrice(),
msg.GasFeeCap(),
msg.GasTipCap(),
msg.Data(),
msg.AccessList(),
msg.IsFake(),
)
cacheCtx, _ := ctx.CacheContext()
// use cache context and pass true to commit StateDB
rsp, err = k.ApplyMessageWithConfig(cacheCtx, msg, nil, true, cfg, txConfig)
if err != nil {
if errors.Is(err, core.ErrIntrinsicGas) {
return true, nil, nil // Special case, raise gas limit
}
return true, nil, err // Bail out
}
return len(rsp.VmError) > 0, rsp, nil
}
// Execute the binary search and hone in on an executable gas limit
hi, err = types.BinSearch(lo, hi, executable)
if err != nil {
return nil, err
}
// Reject the transaction as invalid if it still fails at the highest allowance
if hi == gasCap {
failed, result, err := executable(hi)
if err != nil {
return nil, err
}
if failed {
if result != nil && result.VmError != vm.ErrOutOfGas.Error() {
if result.VmError == vm.ErrExecutionReverted.Error() {
return nil, types.NewExecErrorWithReason(result.Ret)
}
return nil, errors.New(result.VmError)
}
// Otherwise, the specified gas cap is too low
return nil, fmt.Errorf("gas required exceeds allowance (%d)", gasCap)
}
}
return &types.EstimateGasResponse{Gas: hi}, nil
}
// TraceTx configures a new tracer according to the provided configuration, and
// executes the given message in the provided environment. The return value will
// be tracer dependent.
func (k *Keeper) TraceTx(c context.Context, req *types.QueryTraceTxRequest) (*types.QueryTraceTxResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if req.TraceConfig != nil && req.TraceConfig.Limit < 0 {
return nil, status.Errorf(codes.InvalidArgument, "output limit cannot be negative, got %d", req.TraceConfig.Limit)
}
// get the context of block beginning
contextHeight := req.BlockNumber
if contextHeight < 1 {
// 0 is a special value in `ContextWithHeight`
contextHeight = 1
}
ctx := sdk.UnwrapSDKContext(c)
ctx = ctx.WithBlockHeight(contextHeight)
ctx = ctx.WithBlockTime(req.BlockTime)
ctx = ctx.WithHeaderHash(common.Hex2Bytes(req.BlockHash))
chainID, err := getChainID(ctx, req.ChainId)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
cfg, err := k.EVMConfig(ctx, evmkeeper.GetProposerAddress(ctx, req.ProposerAddress), chainID)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to load evm config: %s", err.Error())
}
signer := ethtypes.MakeSigner(cfg.ChainConfig, big.NewInt(ctx.BlockHeight()))
txConfig := statedb.NewEmptyTxConfig(common.BytesToHash(ctx.HeaderHash().Bytes()))
for i, tx := range req.Predecessors {
ethTx := tx.AsTransaction()
msg, err := ethTx.AsMessage(signer, cfg.BaseFee)
if err != nil {
continue
}
txConfig.TxHash = ethTx.Hash()
txConfig.TxIndex = uint(i)
rsp, err := k.ApplyMessageWithConfig(ctx, msg, types.NewNoOpTracer(), true, cfg, txConfig)
if err != nil {
continue
}
txConfig.LogIndex += uint(len(rsp.Logs))
}
tx := req.Msg.AsTransaction()
txConfig.TxHash = tx.Hash()
if len(req.Predecessors) > 0 {
txConfig.TxIndex++
}
var tracerConfig json.RawMessage
if req.TraceConfig != nil && req.TraceConfig.TracerJsonConfig != "" {
// ignore error. default to no traceConfig
_ = json.Unmarshal([]byte(req.TraceConfig.TracerJsonConfig), &tracerConfig)
}
result, _, err := k.traceTx(ctx, cfg, txConfig, signer, tx, req.TraceConfig, false, tracerConfig)
if err != nil {
// error will be returned with detail status from traceTx
return nil, err
}
resultData, err := json.Marshal(result)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QueryTraceTxResponse{
Data: resultData,
}, nil
}
// TraceBlock configures a new tracer according to the provided configuration, and
// executes the given message in the provided environment for all the transactions in the queried block.
// The return value will be tracer dependent.
func (k *Keeper) TraceBlock(c context.Context, req *types.QueryTraceBlockRequest) (*types.QueryTraceBlockResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "empty request")
}
if req.TraceConfig != nil && req.TraceConfig.Limit < 0 {
return nil, status.Errorf(codes.InvalidArgument, "output limit cannot be negative, got %d", req.TraceConfig.Limit)
}
// get the context of block beginning
contextHeight := req.BlockNumber
if contextHeight < 1 {
// 0 is a special value in `ContextWithHeight`
contextHeight = 1
}
ctx := sdk.UnwrapSDKContext(c)
ctx = ctx.WithBlockHeight(contextHeight)
ctx = ctx.WithBlockTime(req.BlockTime)
ctx = ctx.WithHeaderHash(common.Hex2Bytes(req.BlockHash))
chainID, err := getChainID(ctx, req.ChainId)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
cfg, err := k.EVMConfig(ctx, evmkeeper.GetProposerAddress(ctx, req.ProposerAddress), chainID)
if err != nil {
return nil, status.Error(codes.Internal, "failed to load evm config")
}
signer := ethtypes.MakeSigner(cfg.ChainConfig, big.NewInt(ctx.BlockHeight()))
txsLength := len(req.Txs)
results := make([]*types.TxTraceResult, 0, txsLength)
txConfig := statedb.NewEmptyTxConfig(common.BytesToHash(ctx.HeaderHash().Bytes()))
for i, tx := range req.Txs {
result := types.TxTraceResult{}
ethTx := tx.AsTransaction()
txConfig.TxHash = ethTx.Hash()
txConfig.TxIndex = uint(i)
traceResult, logIndex, err := k.traceTx(ctx, cfg, txConfig, signer, ethTx, req.TraceConfig, true, nil)
if err != nil {
result.Error = err.Error()
} else {
txConfig.LogIndex = logIndex
result.Result = traceResult
}
results = append(results, &result)
}
resultData, err := json.Marshal(results)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &types.QueryTraceBlockResponse{
Data: resultData,
}, nil
}
// traceTx do trace on one transaction, it returns a tuple: (traceResult, nextLogIndex, error).
func (k *Keeper) traceTx(
ctx sdk.Context,
cfg *statedb.EVMConfig,
txConfig statedb.TxConfig,
signer ethtypes.Signer,
tx *ethtypes.Transaction,
traceConfig *types.TraceConfig,
commitMessage bool,
tracerJSONConfig json.RawMessage,
) (*interface{}, uint, error) {
// Assemble the structured logger or the JavaScript tracer
var (
tracer tracers.Tracer
overrides *ethparams.ChainConfig
err error
timeout = defaultTraceTimeout
)
msg, err := tx.AsMessage(signer, cfg.BaseFee)
if err != nil {
return nil, 0, status.Error(codes.Internal, err.Error())
}
if traceConfig == nil {
traceConfig = &types.TraceConfig{}
}
if traceConfig.Overrides != nil {
overrides = traceConfig.Overrides.EthereumConfig(cfg.ChainConfig.ChainID)
}
logConfig := logger.Config{
EnableMemory: traceConfig.EnableMemory,
DisableStorage: traceConfig.DisableStorage,
DisableStack: traceConfig.DisableStack,
EnableReturnData: traceConfig.EnableReturnData,
Debug: traceConfig.Debug,
Limit: int(traceConfig.Limit),
Overrides: overrides,
}
tracer = logger.NewStructLogger(&logConfig)
tCtx := &tracers.Context{
BlockHash: txConfig.BlockHash,
TxIndex: int(txConfig.TxIndex),
TxHash: txConfig.TxHash,
}
if traceConfig.Tracer != "" {
if tracer, err = tracers.New(traceConfig.Tracer, tCtx, tracerJSONConfig); err != nil {
return nil, 0, status.Error(codes.Internal, err.Error())
}
}
// Define a meaningful timeout of a single transaction trace
if traceConfig.Timeout != "" {
if timeout, err = time.ParseDuration(traceConfig.Timeout); err != nil {
return nil, 0, status.Errorf(codes.InvalidArgument, "timeout value: %s", err.Error())
}
}
// Handle timeouts and RPC cancellations
deadlineCtx, cancel := context.WithTimeout(ctx.Context(), timeout)
defer cancel()
go func() {
<-deadlineCtx.Done()
if errors.Is(deadlineCtx.Err(), context.DeadlineExceeded) {
tracer.Stop(errors.New("execution timeout"))
}
}()
res, err := k.ApplyMessageWithConfig(ctx, msg, tracer, commitMessage, cfg, txConfig)
if err != nil {
return nil, 0, status.Error(codes.Internal, err.Error())
}
var result interface{}
result, err = tracer.GetResult()
if err != nil {
return nil, 0, status.Error(codes.Internal, err.Error())
}
return &result, txConfig.LogIndex + uint(len(res.Logs)), nil
}
// getChainID parse chainID from current context if not provided
func getChainID(ctx sdk.Context, chainID int64) (*big.Int, error) {
if chainID == 0 {
return etherminttypes.ParseChainID(ctx.ChainID())
}
return big.NewInt(chainID), nil
}