-
Notifications
You must be signed in to change notification settings - Fork 224
/
api.go
394 lines (344 loc) · 12.8 KB
/
api.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
package rpc
import (
"context"
"fmt"
"math/big"
"strings"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/server"
"github.com/crypto-org-chain/cronos/x/cronos/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"
"github.com/ethereum/go-ethereum/rpc"
evmrpc "github.com/evmos/ethermint/rpc"
"github.com/evmos/ethermint/rpc/backend"
"github.com/evmos/ethermint/rpc/stream"
rpctypes "github.com/evmos/ethermint/rpc/types"
ethermint "github.com/evmos/ethermint/types"
evmtypes "github.com/evmos/ethermint/x/evm/types"
"github.com/tendermint/tendermint/libs/log"
coretypes "github.com/tendermint/tendermint/rpc/core/types"
)
const (
// CronosNamespace is the extension RPC namespace of cronos module.
CronosNamespace = "cronos"
apiVersion = "1.0"
ExceedBlockGasLimitError = "out of gas in location: block gas meter; gasWanted:"
)
func init() {
if err := evmrpc.RegisterAPINamespace(CronosNamespace, CreateCronosRPCAPIs); err != nil {
panic(err)
}
}
// CreateCronosRPCAPIs creates extension json-rpc apis
func CreateCronosRPCAPIs(ctx *server.Context, clientCtx client.Context, _ *stream.RPCStream, allowUnprotectedTxs bool, indexer ethermint.EVMTxIndexer) []rpc.API {
evmBackend := backend.NewBackend(ctx, ctx.Logger, clientCtx, allowUnprotectedTxs, indexer)
return []rpc.API{
{
Namespace: CronosNamespace,
Version: apiVersion,
Service: NewCronosAPI(ctx.Logger, clientCtx, *evmBackend),
Public: true,
},
}
}
// CronosAPI is the extension jsonrpc apis prefixed with cronos_.
type CronosAPI struct {
ctx context.Context
clientCtx client.Context
queryClient *rpctypes.QueryClient
chainIDEpoch *big.Int
logger log.Logger
backend backend.Backend
cronosQueryClient types.QueryClient
}
// NewCronosAPI creates an instance of the cronos web3 extension apis.
func NewCronosAPI(
logger log.Logger,
clientCtx client.Context,
backend backend.Backend,
) *CronosAPI {
eip155ChainID, err := ethermint.ParseChainID(clientCtx.ChainID)
if err != nil {
panic(err)
}
return &CronosAPI{
ctx: context.Background(),
clientCtx: clientCtx,
queryClient: rpctypes.NewQueryClient(clientCtx),
chainIDEpoch: eip155ChainID,
logger: logger.With("client", "json-rpc"),
backend: backend,
cronosQueryClient: types.NewQueryClient(clientCtx),
}
}
func (api *CronosAPI) getBlockDetail(blockNrOrHash rpctypes.BlockNumberOrHash) (
resBlock *coretypes.ResultBlock,
blockNumber int64,
blockHash string,
blockRes *coretypes.ResultBlockResults,
baseFee *big.Int,
err error,
) {
var blockNum rpctypes.BlockNumber
resBlock, err = api.getBlock(blockNrOrHash)
if err != nil {
api.logger.Debug("block not found", "height", blockNrOrHash, "error", err.Error())
return
}
blockNumber = resBlock.Block.Height
blockHash = common.BytesToHash(resBlock.Block.Header.Hash()).Hex()
blockRes, err = api.backend.TendermintBlockResultByNumber(&blockNumber)
if err != nil {
api.logger.Debug("failed to retrieve block results", "height", blockNum, "error", err.Error())
return
}
baseFee, err = api.backend.BaseFee(blockRes)
if err != nil {
return
}
return
}
// GetTransactionReceiptsByBlock returns all the transaction receipts included in the block.
func (api *CronosAPI) GetTransactionReceiptsByBlock(blockNrOrHash rpctypes.BlockNumberOrHash) ([]map[string]interface{}, error) {
api.logger.Debug("cronos_getTransactionReceiptsByBlock", "blockNrOrHash", blockNrOrHash)
resBlock, blockNumber, blockHash, blockRes, baseFee, err := api.getBlockDetail(blockNrOrHash)
if err != nil {
return nil, err
}
var receipts []map[string]interface{}
txIndex := uint64(0)
cumulativeGasUsed := uint64(0)
for i, tx := range resBlock.Block.Txs {
txResult := blockRes.TxsResults[i]
// don't ignore the txs which exceed block gas limit.
if !rpctypes.TxSuccessOrExceedsBlockGasLimit(txResult) {
continue
}
tx, err := api.clientCtx.TxConfig.TxDecoder()(tx)
if err != nil {
api.logger.Debug("decoding failed", "error", err.Error())
return nil, fmt.Errorf("failed to decode tx: %w", err)
}
parsedTxs, err := rpctypes.ParseTxResult(txResult, tx)
if err != nil {
return nil, fmt.Errorf("failed to parse tx events: %d:%d, %v", resBlock.Block.Height, i, err)
}
if len(parsedTxs.Txs) == 0 {
// not an evm tx
cumulativeGasUsed += uint64(txResult.GasUsed)
continue
}
if len(parsedTxs.Txs) != len(tx.GetMsgs()) {
return nil, fmt.Errorf("wrong number of tx events: %d", txIndex)
}
msgCumulativeGasUsed := uint64(0)
for msgIndex, msg := range tx.GetMsgs() {
ethMsg, ok := msg.(*evmtypes.MsgEthereumTx)
if !ok {
api.logger.Debug(fmt.Sprintf("invalid tx type: %T", msg))
return nil, fmt.Errorf("invalid tx type: %T", msg)
}
txData, err := evmtypes.UnpackTxData(ethMsg.Data)
if err != nil {
api.logger.Error("failed to unpack tx data", "error", err.Error())
return nil, err
}
parsedTx := parsedTxs.GetTxByMsgIndex(msgIndex)
// Get the transaction result from the log
var status hexutil.Uint
if txResult.Code != 0 || parsedTx.Failed {
status = hexutil.Uint(ethtypes.ReceiptStatusFailed)
} else {
status = hexutil.Uint(ethtypes.ReceiptStatusSuccessful)
}
from, err := ethMsg.GetSender(api.chainIDEpoch)
if err != nil {
return nil, err
}
logs, err := backend.TxLogsFromEvents(txResult.Events, parsedTx.MsgIndex)
if err != nil {
api.logger.Debug("failed to parse logs", "block", resBlock.Block.Height, "txIndex", txIndex, "msgIndex", msgIndex, "error", err.Error())
}
if logs == nil {
logs = []*ethtypes.Log{}
}
// msgCumulativeGasUsed includes gas used by the current tx
msgCumulativeGasUsed += parsedTx.GasUsed
receipt := map[string]interface{}{
// Consensus fields: These fields are defined by the Yellow Paper
"status": status,
"cumulativeGasUsed": hexutil.Uint64(cumulativeGasUsed + msgCumulativeGasUsed),
"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": ethMsg.Hash,
"contractAddress": nil,
"gasUsed": hexutil.Uint64(parsedTx.GasUsed),
// Inclusion information: These fields provide information about the inclusion of the
// transaction corresponding to this receipt.
"blockHash": blockHash,
"blockNumber": hexutil.Uint64(blockNumber),
"transactionIndex": hexutil.Uint64(txIndex),
// sender and receiver (contract or EOA) addreses
"from": from,
"to": txData.GetTo(),
}
// If the to is empty, assume it is a contract creation
if txData.GetTo() == nil {
receipt["contractAddress"] = crypto.CreateAddress(from, txData.GetNonce())
}
if dynamicTx, ok := txData.(*evmtypes.DynamicFeeTx); ok {
receipt["effectiveGasPrice"] = hexutil.Big(*dynamicTx.EffectiveGasPrice(baseFee))
}
receipts = append(receipts, receipt)
txIndex++
}
cumulativeGasUsed += msgCumulativeGasUsed
msgCumulativeGasUsed = 0
}
return receipts, nil
}
// ReplayBlock return tx receipts by replay all the eth transactions,
// if postUpgrade is true, the tx that exceeded block gas limit is treated as reverted, otherwise as committed.
func (api *CronosAPI) ReplayBlock(blockNrOrHash rpctypes.BlockNumberOrHash, postUpgrade bool) ([]map[string]interface{}, error) {
api.logger.Debug("cronos_replayBlock", "blockNrOrHash", blockNrOrHash)
resBlock, blockNumber, blockHash, blockRes, baseFee, err := api.getBlockDetail(blockNrOrHash)
if err != nil {
return nil, err
}
blockGasLimitExceeded := false
var msgs []*evmtypes.MsgEthereumTx
for i, tx := range resBlock.Block.Txs {
txResult := blockRes.TxsResults[i]
if txResult.Code != 0 {
if strings.Contains(txResult.Log, ExceedBlockGasLimitError) {
// the tx with ExceedBlockGasLimitErrorPrefix error should not be ignored because:
// 1) before the 0.7.0 upgrade, the tx is committed successfully.
// 2) after the upgrade, the tx is failed but fee deducted and nonce increased.
// there's at most one such case in each block, and it should be the last tx in the block.
blockGasLimitExceeded = true
} else {
continue
}
}
tx, err := api.clientCtx.TxConfig.TxDecoder()(tx)
if err != nil {
api.logger.Debug("decoding failed", "error", err.Error())
return nil, fmt.Errorf("failed to decode tx: %w", err)
}
for _, msg := range tx.GetMsgs() {
ethMsg, ok := msg.(*evmtypes.MsgEthereumTx)
if !ok {
continue
}
msgs = append(msgs, ethMsg)
}
}
receipts := make([]map[string]interface{}, 0)
if len(msgs) == 0 {
return receipts, nil
}
req := &types.ReplayBlockRequest{
Msgs: msgs,
BlockNumber: blockNumber,
BlockTime: resBlock.Block.Time,
BlockHash: blockHash,
}
// minus one to get the context of block beginning
contextHeight := blockNumber - 1
if contextHeight < 1 {
// 0 is a special value in `ContextWithHeight`
contextHeight = 1
}
rsp, err := api.cronosQueryClient.ReplayBlock(rpctypes.ContextWithHeight(contextHeight), req)
if err != nil {
return nil, err
}
var cumulativeGasUsed uint64
for txIndex, txResponse := range rsp.Responses {
ethMsg := msgs[txIndex]
txData, err := evmtypes.UnpackTxData(ethMsg.Data)
if err != nil {
api.logger.Error("failed to unpack tx data", "error", err.Error())
return nil, err
}
// Get the transaction result from the log
var status hexutil.Uint
if txResponse.Failed() {
status = hexutil.Uint(ethtypes.ReceiptStatusFailed)
} else {
status = hexutil.Uint(ethtypes.ReceiptStatusSuccessful)
}
from, err := ethMsg.GetSender(api.chainIDEpoch)
if err != nil {
return nil, err
}
logs := evmtypes.LogsToEthereum(txResponse.Logs)
if logs == nil {
logs = []*ethtypes.Log{}
}
// cumulativeGasUsed includes gas used by the current tx
cumulativeGasUsed += txResponse.GasUsed
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": ethMsg.Hash,
"contractAddress": nil,
"gasUsed": hexutil.Uint64(txResponse.GasUsed),
"type": hexutil.Uint(txData.TxType()),
// Inclusion information: These fields provide information about the inclusion of the
// transaction corresponding to this receipt.
"blockHash": blockHash,
"blockNumber": hexutil.Uint64(blockNumber),
"transactionIndex": hexutil.Uint64(txIndex),
// sender and receiver (contract or EOA) addreses
"from": from,
"to": txData.GetTo(),
}
// If the to is nil, assume it is a contract creation
if txData.GetTo() == nil {
receipt["contractAddress"] = crypto.CreateAddress(from, txData.GetNonce())
}
if dynamicTx, ok := txData.(*evmtypes.DynamicFeeTx); ok {
receipt["effectiveGasPrice"] = hexutil.Big(*dynamicTx.EffectiveGasPrice(baseFee))
}
receipts = append(receipts, receipt)
}
if blockGasLimitExceeded && postUpgrade {
// after the 0.7.0 upgrade, the tx is always reverted, fix the last receipt.
idx := len(receipts) - 1
receipts[idx]["status"] = hexutil.Uint(ethtypes.ReceiptStatusFailed)
receipts[idx]["logs"] = []*ethtypes.Log{}
receipts[idx]["logsBloom"] = ethtypes.BytesToBloom(ethtypes.LogsBloom(nil))
receipts[idx]["contractAddress"] = nil
// the fee is deducted by the gas limit, so we patch the gasUsed to gasLimit
refundedGas := msgs[idx].GetGas() - uint64(receipts[idx]["gasUsed"].(hexutil.Uint64))
receipts[idx]["gasUsed"] = hexutil.Uint64(uint64(receipts[idx]["gasUsed"].(hexutil.Uint64)) + refundedGas)
receipts[idx]["cumulativeGasUsed"] = hexutil.Uint64(uint64(receipts[idx]["cumulativeGasUsed"].(hexutil.Uint64)) + refundedGas)
}
return receipts, nil
}
// getBlock returns the block from BlockNumberOrHash
func (api *CronosAPI) getBlock(blockNrOrHash rpctypes.BlockNumberOrHash) (blk *coretypes.ResultBlock, err error) {
if blockNrOrHash.BlockHash != nil {
blk, err = api.backend.TendermintBlockByHash(*blockNrOrHash.BlockHash)
} else {
var blockNumber rpctypes.BlockNumber
if blockNrOrHash.BlockNumber != nil {
blockNumber = *blockNrOrHash.BlockNumber
} else if blockNrOrHash.BlockHash == nil && blockNrOrHash.BlockNumber == nil {
return nil, fmt.Errorf("types BlockHash and BlockNumber cannot be both nil")
}
blk, err = api.backend.TendermintBlockByNumber(blockNumber)
}
return
}