forked from EscanBE/evermint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
381 lines (340 loc) · 12.1 KB
/
utils.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
package types
import (
"context"
"fmt"
"github.com/cometbft/cometbft/libs/log"
tmrpcclient "github.com/cometbft/cometbft/rpc/client"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/trie"
"github.com/pkg/errors"
"math/big"
"strings"
abci "github.com/cometbft/cometbft/abci/types"
tmtypes "github.com/cometbft/cometbft/types"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/client"
errortypes "github.com/cosmos/cosmos-sdk/types/errors"
evmtypes "github.com/servprotocolorg/serv/v12/x/evm/types"
feemarkettypes "github.com/servprotocolorg/serv/v12/x/feemarket/types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/math"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
)
// ExceedBlockGasLimitError defines the error message when tx execution exceeds the block gas limit.
// The tx fee is deducted in ante handler, so it shouldn't be ignored in JSON-RPC API.
const ExceedBlockGasLimitError = "out of gas in location: block gas meter; gasWanted:"
// RawTxToEthTx returns a evm MsgEthereum transaction from raw tx bytes.
func RawTxToEthTx(clientCtx client.Context, txBz tmtypes.Tx) ([]*evmtypes.MsgEthereumTx, error) {
tx, err := clientCtx.TxConfig.TxDecoder()(txBz)
if err != nil {
return nil, errorsmod.Wrap(errortypes.ErrJSONUnmarshal, err.Error())
}
ethTxs := make([]*evmtypes.MsgEthereumTx, len(tx.GetMsgs()))
for i, msg := range tx.GetMsgs() {
ethTx, ok := msg.(*evmtypes.MsgEthereumTx)
if !ok {
return nil, fmt.Errorf("invalid message type %T, expected %T", msg, &evmtypes.MsgEthereumTx{})
}
ethTx.Hash = ethTx.AsTransaction().Hash().Hex()
ethTxs[i] = ethTx
}
return ethTxs, nil
}
// EthHeaderFromTendermint is an util function that returns an Ethereum Header
// from a tendermint Header.
func EthHeaderFromTendermint(header tmtypes.Header, bloom ethtypes.Bloom, baseFee *big.Int) *ethtypes.Header {
txHash := ethtypes.EmptyRootHash
if len(header.DataHash) == 0 {
txHash = common.BytesToHash(header.DataHash)
}
time := uint64(header.Time.UTC().Unix()) // #nosec G701
return ðtypes.Header{
ParentHash: common.BytesToHash(header.LastBlockID.Hash.Bytes()),
UncleHash: ethtypes.EmptyUncleHash,
Coinbase: common.BytesToAddress(header.ProposerAddress),
Root: common.BytesToHash(header.AppHash),
TxHash: txHash,
ReceiptHash: ethtypes.EmptyRootHash,
Bloom: bloom,
Difficulty: big.NewInt(0),
Number: big.NewInt(header.Height),
GasLimit: 0,
GasUsed: 0,
Time: time,
Extra: []byte{},
MixDigest: common.Hash{},
Nonce: ethtypes.BlockNonce{},
BaseFee: baseFee,
}
}
// BlockMaxGasFromConsensusParams returns the gas limit for the current block from the chain consensus params.
func BlockMaxGasFromConsensusParams(goCtx context.Context, clientCtx client.Context, blockHeight int64) (int64, error) {
tmrpcClient, ok := clientCtx.Client.(tmrpcclient.Client)
if !ok {
panic("incorrect tm rpc client")
}
resConsParams, err := tmrpcClient.ConsensusParams(goCtx, &blockHeight)
defaultGasLimit := int64(^uint32(0)) // #nosec G701
if err != nil {
return defaultGasLimit, err
}
gasLimit := resConsParams.ConsensusParams.Block.MaxGas
if gasLimit == -1 {
// Sets gas limit to max uint32 to not error with javascript dev tooling
// This -1 value indicating no block gas limit is set to max uint64 with geth hexutils
// which errors certain javascript dev tooling which only supports up to 53 bits
gasLimit = defaultGasLimit
}
return gasLimit, nil
}
// FormatBlock creates an ethereum block from a tendermint header and ethereum-formatted
// transactions.
func FormatBlock(
header tmtypes.Header,
chainID *big.Int,
size int,
gasLimit int64, gasUsed *big.Int, baseFee *big.Int,
transactions ethtypes.Transactions, fullTx bool,
receipts ethtypes.Receipts,
bloom ethtypes.Bloom,
validatorAddr common.Address,
logger log.Logger,
) map[string]interface{} {
var transactionsRoot common.Hash
if len(transactions) == 0 {
transactionsRoot = ethtypes.EmptyRootHash
} else {
transactionsRoot = ethtypes.DeriveSha(transactions, trie.NewStackTrie(nil))
}
var receiptsRoot common.Hash
if len(receipts) == 0 {
receiptsRoot = ethtypes.EmptyRootHash
} else {
receiptsRoot = ethtypes.DeriveSha(receipts, trie.NewStackTrie(nil))
}
var txsList []interface{}
for txIndex, tx := range transactions {
if !fullTx {
txsList = append(txsList, tx.Hash())
continue
}
height := uint64(header.Height) //#nosec G701 -- checked for int overflow already
index := uint64(txIndex) //#nosec G701 -- checked for int overflow already
rpcTx, err := NewRPCTransaction(
tx,
common.BytesToHash(header.Hash()),
height,
index,
baseFee,
chainID,
)
if err != nil {
logger.Error("NewRPCTransaction failed", "hash", tx.Hash().Hex(), "error", err.Error())
continue
}
txsList = append(txsList, rpcTx)
}
result := map[string]interface{}{
"number": hexutil.Uint64(header.Height),
"hash": hexutil.Bytes(header.Hash()),
"parentHash": common.BytesToHash(header.LastBlockID.Hash.Bytes()),
"nonce": ethtypes.BlockNonce{}, // PoW specific
"sha3Uncles": ethtypes.EmptyUncleHash, // No uncles in Tendermint
"logsBloom": bloom,
"stateRoot": hexutil.Bytes(header.AppHash),
"miner": validatorAddr,
"mixHash": common.Hash{},
"difficulty": (*hexutil.Big)(big.NewInt(0)),
"extraData": "0x",
"size": hexutil.Uint64(size),
"gasLimit": hexutil.Uint64(gasLimit), // Static gas limit
"gasUsed": (*hexutil.Big)(gasUsed),
"timestamp": hexutil.Uint64(header.Time.Unix()),
"transactionsRoot": transactionsRoot,
"receiptsRoot": receiptsRoot,
"uncles": []common.Hash{},
"transactions": txsList,
"totalDifficulty": (*hexutil.Big)(big.NewInt(0)),
}
if baseFee != nil {
result["baseFeePerGas"] = (*hexutil.Big)(baseFee)
}
return result
}
// NewTransactionFromMsg returns a transaction that will serialize to the RPC
// representation, with the given location metadata set (if available).
func NewTransactionFromMsg(
msg *evmtypes.MsgEthereumTx,
blockHash common.Hash,
blockNumber, index uint64,
baseFee *big.Int,
chainID *big.Int,
) (*RPCTransaction, error) {
tx := msg.AsTransaction()
return NewRPCTransaction(tx, blockHash, blockNumber, index, baseFee, chainID)
}
// NewRPCTransaction returns a transaction that will serialize to the RPC
// representation, with the given location metadata set (if available).
func NewRPCTransaction(
tx *ethtypes.Transaction, blockHash common.Hash, blockNumber, index uint64, baseFee *big.Int,
chainID *big.Int,
) (*RPCTransaction, error) {
// Determine the signer. For replay-protected transactions, use the most permissive
// signer, because we assume that signers are backwards-compatible with old
// transactions. For non-protected transactions, the homestead signer signer is used
// because the return value of ChainId is zero for those transactions.
var signer ethtypes.Signer
if tx.Protected() {
signer = ethtypes.LatestSignerForChainID(tx.ChainId())
} else {
signer = ethtypes.HomesteadSigner{}
}
from, _ := ethtypes.Sender(signer, tx) // #nosec G703
v, r, s := tx.RawSignatureValues()
result := &RPCTransaction{
Type: hexutil.Uint64(tx.Type()),
From: from,
Gas: hexutil.Uint64(tx.Gas()),
GasPrice: (*hexutil.Big)(tx.GasPrice()),
Hash: tx.Hash(),
Input: hexutil.Bytes(tx.Data()),
Nonce: hexutil.Uint64(tx.Nonce()),
To: tx.To(),
Value: (*hexutil.Big)(tx.Value()),
V: (*hexutil.Big)(v),
R: (*hexutil.Big)(r),
S: (*hexutil.Big)(s),
ChainID: (*hexutil.Big)(chainID),
}
if blockHash != (common.Hash{}) {
result.BlockHash = &blockHash
result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
result.TransactionIndex = (*hexutil.Uint64)(&index)
}
switch tx.Type() {
case ethtypes.AccessListTxType:
al := tx.AccessList()
result.Accesses = &al
result.ChainID = (*hexutil.Big)(tx.ChainId())
case ethtypes.DynamicFeeTxType:
al := tx.AccessList()
result.Accesses = &al
result.ChainID = (*hexutil.Big)(tx.ChainId())
result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap())
result.GasTipCap = (*hexutil.Big)(tx.GasTipCap())
// if the transaction has been mined, compute the effective gas price
if baseFee != nil && blockHash != (common.Hash{}) {
// price = min(tip, gasFeeCap - baseFee) + baseFee
price := math.BigMin(new(big.Int).Add(tx.GasTipCap(), baseFee), tx.GasFeeCap())
result.GasPrice = (*hexutil.Big)(price)
} else {
result.GasPrice = (*hexutil.Big)(tx.GasFeeCap())
}
}
return result, nil
}
func NewRPCReceipt(
ethMsg *evmtypes.MsgEthereumTx,
transactionIndex hexutil.Uint64,
success bool,
gasUsed hexutil.Uint64,
cumulativeGasUsed hexutil.Uint64,
baseFee *big.Int,
logs []*ethtypes.Log,
blockHash common.Hash,
blockNumber hexutil.Uint64,
chainID *big.Int,
) (receipt *RPCReceipt, err error) {
var status hexutil.Uint
if success {
status = hexutil.Uint(ethtypes.ReceiptStatusSuccessful)
} else {
status = hexutil.Uint(ethtypes.ReceiptStatusFailed)
}
if logs == nil {
logs = []*ethtypes.Log{}
}
from, err := ethMsg.GetSender(chainID)
if err != nil {
return nil, errors.Wrap(err, "failed to get sender")
}
txData, err := evmtypes.UnpackTxData(ethMsg.Data)
if err != nil {
return nil, errors.Wrap(err, "failed to unpack tx data")
}
rpcReceipt := RPCReceipt{
Status: status,
CumulativeGasUsed: cumulativeGasUsed,
Bloom: ethtypes.BytesToBloom(ethtypes.LogsBloom(logs)),
Logs: logs,
TransactionHash: ethMsg.AsTransaction().Hash(),
ContractAddress: nil,
GasUsed: gasUsed,
BlockHash: blockHash,
BlockNumber: blockNumber,
TransactionIndex: transactionIndex,
Type: hexutil.Uint(ethMsg.AsTransaction().Type()),
From: from,
To: txData.GetTo(),
EffectiveGasPrice: nil,
}
if rpcReceipt.To == nil {
newContractAddress := crypto.CreateAddress(from, txData.GetNonce())
rpcReceipt.ContractAddress = &newContractAddress
}
if baseFee != nil {
if dynamicTx, ok := txData.(*evmtypes.DynamicFeeTx); ok {
effectiveGasPrice := hexutil.Big(*dynamicTx.EffectiveGasPrice(baseFee))
rpcReceipt.EffectiveGasPrice = &effectiveGasPrice
}
}
return &rpcReceipt, nil
}
// BaseFeeFromEvents parses the feemarket basefee from cosmos events
func BaseFeeFromEvents(events []abci.Event) *big.Int {
for _, event := range events {
if event.Type != feemarkettypes.EventTypeFeeMarket {
continue
}
for _, attr := range event.Attributes {
if attr.Key == feemarkettypes.AttributeKeyBaseFee {
result, success := new(big.Int).SetString(attr.Value, 10)
if success {
return result
}
return nil
}
}
}
return nil
}
// CheckTxFee is an internal function used to check whether the fee of
// the given transaction is _reasonable_(under the cap).
func CheckTxFee(gasPrice *big.Int, gas uint64, cap float64) error {
// Short circuit if there is no cap for transaction fee at all.
if cap == 0 {
return nil
}
totalfee := new(big.Float).SetInt(new(big.Int).Mul(gasPrice, new(big.Int).SetUint64(gas)))
// 1 ETH = 10^18 aservo
oneToken := new(big.Float).SetInt(big.NewInt(params.Ether))
// quo = rounded(x/y)
feeEth := new(big.Float).Quo(totalfee, oneToken)
// no need to check error from parsing
feeFloat, _ := feeEth.Float64()
if feeFloat > cap {
return fmt.Errorf("tx fee (%.2f ether) exceeds the configured cap (%.2f ether)", feeFloat, cap)
}
return nil
}
// TxExceedBlockGasLimit returns true if the tx exceeds block gas limit.
func TxExceedBlockGasLimit(res *abci.ResponseDeliverTx) bool {
return strings.Contains(res.Log, ExceedBlockGasLimitError)
}
// TxSuccessOrExceedsBlockGasLimit returnsrue if the transaction was successful
// or if it failed with an ExceedBlockGasLimit error
func TxSuccessOrExceedsBlockGasLimit(res *abci.ResponseDeliverTx) bool {
return res.Code == 0 || TxExceedBlockGasLimit(res)
}