-
Notifications
You must be signed in to change notification settings - Fork 836
/
tx_info.go
430 lines (376 loc) · 14.1 KB
/
tx_info.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
// Copyright 2022 Evmos Foundation
// This file is part of the Evmos Network packages.
//
// Evmos is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Evmos packages are distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Evmos packages. If not, see https://github.com/evmos/evmos/blob/main/LICENSE
package backend
import (
"fmt"
"math"
"math/big"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
rpctypes "github.com/evmos/evmos/v12/rpc/types"
"github.com/evmos/evmos/v12/types"
evmtypes "github.com/evmos/evmos/v12/x/evm/types"
"github.com/pkg/errors"
tmrpctypes "github.com/tendermint/tendermint/rpc/core/types"
)
// GetTransactionByHash returns the Ethereum format transaction identified by Ethereum transaction hash
func (b *Backend) GetTransactionByHash(txHash common.Hash) (*rpctypes.RPCTransaction, error) {
res, err := b.GetTxByEthHash(txHash)
hexTx := txHash.Hex()
if err != nil {
return b.getTransactionByHashPending(txHash)
}
block, err := b.TendermintBlockByNumber(rpctypes.BlockNumber(res.Height))
if err != nil {
return nil, err
}
tx, err := b.clientCtx.TxConfig.TxDecoder()(block.Block.Txs[res.TxIndex])
if err != nil {
return nil, err
}
// the `res.MsgIndex` is inferred from tx index, should be within the bound.
msg, ok := tx.GetMsgs()[res.MsgIndex].(*evmtypes.MsgEthereumTx)
if !ok {
return nil, errors.New("invalid ethereum tx")
}
blockRes, err := b.TendermintBlockResultByNumber(&block.Block.Height)
if err != nil {
b.logger.Debug("block result not found", "height", block.Block.Height, "error", err.Error())
return nil, nil
}
if res.EthTxIndex == -1 {
// Fallback to find tx index by iterating all valid eth transactions
msgs := b.EthMsgsFromTendermintBlock(block, blockRes)
for i := range msgs {
if msgs[i].Hash == hexTx {
if i > math.MaxInt32 {
return nil, errors.New("tx index overflow")
}
res.EthTxIndex = int32(i) //#nosec G701 -- checked for int overflow already
break
}
}
}
// if we still unable to find the eth tx index, return error, shouldn't happen.
if res.EthTxIndex == -1 {
return nil, errors.New("can't find index of ethereum tx")
}
baseFee, err := b.BaseFee(blockRes)
if err != nil {
// handle the error for pruned node.
b.logger.Error("failed to fetch Base Fee from prunned block. Check node prunning configuration", "height", blockRes.Height, "error", err)
}
height := uint64(res.Height) //#nosec G701 -- checked for int overflow already
index := uint64(res.EthTxIndex) //#nosec G701 -- checked for int overflow already
return rpctypes.NewTransactionFromMsg(
msg,
common.BytesToHash(block.BlockID.Hash.Bytes()),
height,
index,
baseFee,
b.chainID,
)
}
// getTransactionByHashPending find pending tx from mempool
func (b *Backend) getTransactionByHashPending(txHash common.Hash) (*rpctypes.RPCTransaction, error) {
hexTx := txHash.Hex()
// try to find tx in mempool
txs, err := b.PendingTransactions()
if err != nil {
b.logger.Debug("tx not found", "hash", hexTx, "error", err.Error())
return nil, nil
}
for _, tx := range txs {
msg, err := evmtypes.UnwrapEthereumMsg(tx, txHash)
if err != nil {
// not ethereum tx
continue
}
if msg.Hash == hexTx {
// use zero block values since it's not included in a block yet
rpctx, err := rpctypes.NewTransactionFromMsg(
msg,
common.Hash{},
uint64(0),
uint64(0),
nil,
b.chainID,
)
if err != nil {
return nil, err
}
return rpctx, nil
}
}
b.logger.Debug("tx not found", "hash", hexTx)
return nil, nil
}
// GetGasUsed returns gasUsed from transaction
func (b *Backend) GetGasUsed(res *types.TxResult, price *big.Int, gas uint64) uint64 {
// patch gasUsed if tx is reverted and happened before height on which fixed was introduced
// to return real gas charged
// more info at https://github.com/evmos/ethermint/pull/1557
if res.Failed && res.Height < b.cfg.JSONRPC.FixRevertGasRefundHeight {
return new(big.Int).Mul(price, new(big.Int).SetUint64(gas)).Uint64()
}
return res.GasUsed
}
// GetTransactionReceipt returns the transaction receipt identified by hash.
func (b *Backend) GetTransactionReceipt(hash common.Hash) (map[string]interface{}, error) {
hexTx := hash.Hex()
b.logger.Debug("eth_getTransactionReceipt", "hash", hexTx)
res, err := b.GetTxByEthHash(hash)
if err != nil {
b.logger.Debug("tx not found", "hash", hexTx, "error", err.Error())
return nil, nil
}
resBlock, err := b.TendermintBlockByNumber(rpctypes.BlockNumber(res.Height))
if err != nil {
b.logger.Debug("block not found", "height", res.Height, "error", err.Error())
return nil, nil
}
tx, err := b.clientCtx.TxConfig.TxDecoder()(resBlock.Block.Txs[res.TxIndex])
if err != nil {
b.logger.Debug("decoding failed", "error", err.Error())
return nil, fmt.Errorf("failed to decode tx: %w", err)
}
ethMsg := tx.GetMsgs()[res.MsgIndex].(*evmtypes.MsgEthereumTx)
txData, err := evmtypes.UnpackTxData(ethMsg.Data)
if err != nil {
b.logger.Error("failed to unpack tx data", "error", err.Error())
return nil, err
}
cumulativeGasUsed := uint64(0)
blockRes, err := b.TendermintBlockResultByNumber(&res.Height)
if err != nil {
b.logger.Debug("failed to retrieve block results", "height", res.Height, "error", err.Error())
return nil, nil
}
for _, txResult := range blockRes.TxsResults[0:res.TxIndex] {
cumulativeGasUsed += uint64(txResult.GasUsed) // #nosec G701 -- checked for int overflow already
}
cumulativeGasUsed += res.CumulativeGasUsed
var status hexutil.Uint
if res.Failed {
status = hexutil.Uint(ethtypes.ReceiptStatusFailed)
} else {
status = hexutil.Uint(ethtypes.ReceiptStatusSuccessful)
}
chainID, err := b.ChainID()
if err != nil {
return nil, err
}
from, err := ethMsg.GetSender(chainID.ToInt())
if err != nil {
return nil, err
}
// parse tx logs from events
msgIndex := int(res.MsgIndex) // #nosec G701 -- checked for int overflow already
logs, err := TxLogsFromEvents(blockRes.TxsResults[res.TxIndex].Events, msgIndex)
if err != nil {
b.logger.Debug("failed to parse logs", "hash", hexTx, "error", err.Error())
}
if res.EthTxIndex == -1 {
// Fallback to find tx index by iterating all valid eth transactions
msgs := b.EthMsgsFromTendermintBlock(resBlock, blockRes)
for i := range msgs {
if msgs[i].Hash == hexTx {
res.EthTxIndex = int32(i) // #nosec G701
break
}
}
}
// return error if still unable to find the eth tx index
if res.EthTxIndex == -1 {
return nil, errors.New("can't find index of ethereum tx")
}
receipt := map[string]interface{}{
// Consensus fields: These fields are defined by the Yellow Paper
"status": status,
"cumulativeGasUsed": hexutil.Uint64(cumulativeGasUsed),
"logsBloom": ethtypes.BytesToBloom(ethtypes.LogsBloom(logs)),
"logs": logs,
// Implementation fields: These fields are added by geth when processing a transaction.
// They are stored in the chain database.
"transactionHash": hash,
"contractAddress": nil,
"gasUsed": hexutil.Uint64(b.GetGasUsed(res, txData.GetGasPrice(), txData.GetGas())),
// Inclusion information: These fields provide information about the inclusion of the
// transaction corresponding to this receipt.
"blockHash": common.BytesToHash(resBlock.Block.Header.Hash()).Hex(),
"blockNumber": hexutil.Uint64(res.Height),
"transactionIndex": hexutil.Uint64(res.EthTxIndex),
// sender and receiver (contract or EOA) addreses
"from": from,
"to": txData.GetTo(),
"type": hexutil.Uint(ethMsg.AsTransaction().Type()),
}
if logs == nil {
receipt["logs"] = [][]*ethtypes.Log{}
}
// If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
if txData.GetTo() == nil {
receipt["contractAddress"] = crypto.CreateAddress(from, txData.GetNonce())
}
if dynamicTx, ok := txData.(*evmtypes.DynamicFeeTx); ok {
baseFee, err := b.BaseFee(blockRes)
if err != nil {
// tolerate the error for pruned node.
b.logger.Error("fetch basefee failed, node is pruned?", "height", res.Height, "error", err)
} else {
receipt["effectiveGasPrice"] = hexutil.Big(*dynamicTx.EffectiveGasPrice(baseFee))
}
}
return receipt, nil
}
// GetTransactionByBlockHashAndIndex returns the transaction identified by hash and index.
func (b *Backend) GetTransactionByBlockHashAndIndex(hash common.Hash, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) {
b.logger.Debug("eth_getTransactionByBlockHashAndIndex", "hash", hash.Hex(), "index", idx)
block, err := b.clientCtx.Client.BlockByHash(b.ctx, hash.Bytes())
if err != nil {
b.logger.Debug("block not found", "hash", hash.Hex(), "error", err.Error())
return nil, nil
}
if block.Block == nil {
b.logger.Debug("block not found", "hash", hash.Hex())
return nil, nil
}
return b.GetTransactionByBlockAndIndex(block, idx)
}
// GetTransactionByBlockNumberAndIndex returns the transaction identified by number and index.
func (b *Backend) GetTransactionByBlockNumberAndIndex(blockNum rpctypes.BlockNumber, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) {
b.logger.Debug("eth_getTransactionByBlockNumberAndIndex", "number", blockNum, "index", idx)
block, err := b.TendermintBlockByNumber(blockNum)
if err != nil {
b.logger.Debug("block not found", "height", blockNum.Int64(), "error", err.Error())
return nil, nil
}
if block.Block == nil {
b.logger.Debug("block not found", "height", blockNum.Int64())
return nil, nil
}
return b.GetTransactionByBlockAndIndex(block, idx)
}
// GetTxByEthHash uses `/tx_query` to find transaction by ethereum tx hash
// TODO: Don't need to convert once hashing is fixed on Tendermint
// https://github.com/tendermint/tendermint/issues/6539
func (b *Backend) GetTxByEthHash(hash common.Hash) (*types.TxResult, error) {
if b.indexer != nil {
return b.indexer.GetByTxHash(hash)
}
// fallback to tendermint tx indexer
query := fmt.Sprintf("%s.%s='%s'", evmtypes.TypeMsgEthereumTx, evmtypes.AttributeKeyEthereumTxHash, hash.Hex())
txResult, err := b.queryTendermintTxIndexer(query, func(txs *rpctypes.ParsedTxs) *rpctypes.ParsedTx {
return txs.GetTxByHash(hash)
})
if err != nil {
return nil, errorsmod.Wrapf(err, "GetTxByEthHash %s", hash.Hex())
}
return txResult, nil
}
// GetTxByTxIndex uses `/tx_query` to find transaction by tx index of valid ethereum txs
func (b *Backend) GetTxByTxIndex(height int64, index uint) (*types.TxResult, error) {
int32Index := int32(index) // #nosec G701 -- checked for int overflow already
if b.indexer != nil {
return b.indexer.GetByBlockAndIndex(height, int32Index)
}
// fallback to tendermint tx indexer
query := fmt.Sprintf("tx.height=%d AND %s.%s=%d",
height, evmtypes.TypeMsgEthereumTx,
evmtypes.AttributeKeyTxIndex, index,
)
txResult, err := b.queryTendermintTxIndexer(query, func(txs *rpctypes.ParsedTxs) *rpctypes.ParsedTx {
return txs.GetTxByTxIndex(int(index)) // #nosec G701 -- checked for int overflow already
})
if err != nil {
return nil, errorsmod.Wrapf(err, "GetTxByTxIndex %d %d", height, index)
}
return txResult, nil
}
// queryTendermintTxIndexer query tx in tendermint tx indexer
func (b *Backend) queryTendermintTxIndexer(query string, txGetter func(*rpctypes.ParsedTxs) *rpctypes.ParsedTx) (*types.TxResult, error) {
resTxs, err := b.clientCtx.Client.TxSearch(b.ctx, query, false, nil, nil, "")
if err != nil {
return nil, err
}
if len(resTxs.Txs) == 0 {
return nil, errors.New("ethereum tx not found")
}
txResult := resTxs.Txs[0]
if !rpctypes.TxSuccessOrExceedsBlockGasLimit(&txResult.TxResult) {
return nil, errors.New("invalid ethereum tx")
}
var tx sdk.Tx
if txResult.TxResult.Code != 0 {
// it's only needed when the tx exceeds block gas limit
tx, err = b.clientCtx.TxConfig.TxDecoder()(txResult.Tx)
if err != nil {
return nil, fmt.Errorf("invalid ethereum tx")
}
}
return rpctypes.ParseTxIndexerResult(txResult, tx, txGetter)
}
// GetTransactionByBlockAndIndex is the common code shared by `GetTransactionByBlockNumberAndIndex` and `GetTransactionByBlockHashAndIndex`.
func (b *Backend) GetTransactionByBlockAndIndex(block *tmrpctypes.ResultBlock, idx hexutil.Uint) (*rpctypes.RPCTransaction, error) {
blockRes, err := b.TendermintBlockResultByNumber(&block.Block.Height)
if err != nil {
return nil, nil
}
var msg *evmtypes.MsgEthereumTx
// find in tx indexer
res, err := b.GetTxByTxIndex(block.Block.Height, uint(idx))
if err == nil {
tx, err := b.clientCtx.TxConfig.TxDecoder()(block.Block.Txs[res.TxIndex])
if err != nil {
b.logger.Debug("invalid ethereum tx", "height", block.Block.Header, "index", idx)
return nil, nil
}
var ok bool
// msgIndex is inferred from tx events, should be within bound.
msg, ok = tx.GetMsgs()[res.MsgIndex].(*evmtypes.MsgEthereumTx)
if !ok {
b.logger.Debug("invalid ethereum tx", "height", block.Block.Header, "index", idx)
return nil, nil
}
} else {
i := int(idx) // #nosec G701
ethMsgs := b.EthMsgsFromTendermintBlock(block, blockRes)
if i >= len(ethMsgs) {
b.logger.Debug("block txs index out of bound", "index", i)
return nil, nil
}
msg = ethMsgs[i]
}
baseFee, err := b.BaseFee(blockRes)
if err != nil {
// handle the error for pruned node.
b.logger.Error("failed to fetch Base Fee from prunned block. Check node prunning configuration", "height", block.Block.Height, "error", err)
}
height := uint64(block.Block.Height) // #nosec G701 -- checked for int overflow already
index := uint64(idx) // #nosec G701 -- checked for int overflow already
return rpctypes.NewTransactionFromMsg(
msg,
common.BytesToHash(block.Block.Hash()),
height,
index,
baseFee,
b.chainID,
)
}