This repository has been archived by the owner on Apr 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 575
/
Copy pathmsg.go
449 lines (384 loc) · 12.3 KB
/
msg.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// Copyright 2021 Evmos Foundation
// This file is part of Evmos' Ethermint library.
//
// The Ethermint library 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 Ethermint library is 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 Ethermint library. If not, see https://github.com/evmos/ethermint/blob/main/LICENSE
package types
import (
"errors"
"fmt"
"math/big"
sdkmath "cosmossdk.io/math"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/client"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
errortypes "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/auth/ante"
"github.com/cosmos/cosmos-sdk/x/auth/signing"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
"github.com/evmos/ethermint/types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/core"
ethtypes "github.com/ethereum/go-ethereum/core/types"
)
var (
_ sdk.Msg = &MsgEthereumTx{}
_ sdk.Tx = &MsgEthereumTx{}
_ ante.GasTx = &MsgEthereumTx{}
_ sdk.Msg = &MsgUpdateParams{}
_ codectypes.UnpackInterfacesMessage = MsgEthereumTx{}
)
// message type and route constants
const (
// TypeMsgEthereumTx defines the type string of an Ethereum transaction
TypeMsgEthereumTx = "ethereum_tx"
)
// NewTx returns a reference to a new Ethereum transaction message.
func NewTx(
chainID *big.Int, nonce uint64, to *common.Address, amount *big.Int,
gasLimit uint64, gasPrice, gasFeeCap, gasTipCap *big.Int, input []byte, accesses *ethtypes.AccessList,
) *MsgEthereumTx {
return newMsgEthereumTx(chainID, nonce, to, amount, gasLimit, gasPrice, gasFeeCap, gasTipCap, input, accesses)
}
// NewTxContract returns a reference to a new Ethereum transaction
// message designated for contract creation.
func NewTxContract(
chainID *big.Int,
nonce uint64,
amount *big.Int,
gasLimit uint64,
gasPrice, gasFeeCap, gasTipCap *big.Int,
input []byte,
accesses *ethtypes.AccessList,
) *MsgEthereumTx {
return newMsgEthereumTx(chainID, nonce, nil, amount, gasLimit, gasPrice, gasFeeCap, gasTipCap, input, accesses)
}
func newMsgEthereumTx(
chainID *big.Int, nonce uint64, to *common.Address, amount *big.Int,
gasLimit uint64, gasPrice, gasFeeCap, gasTipCap *big.Int, input []byte, accesses *ethtypes.AccessList,
) *MsgEthereumTx {
var (
cid, amt, gp *sdkmath.Int
toAddr string
txData TxData
)
if to != nil {
toAddr = to.Hex()
}
if amount != nil {
amountInt := sdkmath.NewIntFromBigInt(amount)
amt = &amountInt
}
if chainID != nil {
chainIDInt := sdkmath.NewIntFromBigInt(chainID)
cid = &chainIDInt
}
if gasPrice != nil {
gasPriceInt := sdkmath.NewIntFromBigInt(gasPrice)
gp = &gasPriceInt
}
switch {
case accesses == nil:
txData = &LegacyTx{
Nonce: nonce,
To: toAddr,
Amount: amt,
GasLimit: gasLimit,
GasPrice: gp,
Data: input,
}
case accesses != nil && gasFeeCap != nil && gasTipCap != nil:
gtc := sdkmath.NewIntFromBigInt(gasTipCap)
gfc := sdkmath.NewIntFromBigInt(gasFeeCap)
txData = &DynamicFeeTx{
ChainID: cid,
Nonce: nonce,
To: toAddr,
Amount: amt,
GasLimit: gasLimit,
GasTipCap: >c,
GasFeeCap: &gfc,
Data: input,
Accesses: NewAccessList(accesses),
}
case accesses != nil:
txData = &AccessListTx{
ChainID: cid,
Nonce: nonce,
To: toAddr,
Amount: amt,
GasLimit: gasLimit,
GasPrice: gp,
Data: input,
Accesses: NewAccessList(accesses),
}
default:
}
dataAny, err := PackTxData(txData)
if err != nil {
panic(err)
}
msg := MsgEthereumTx{Data: dataAny}
msg.Hash = msg.AsTransaction().Hash().Hex()
return &msg
}
// FromEthereumTx populates the message fields from the given ethereum transaction
func (msg *MsgEthereumTx) FromEthereumTx(tx *ethtypes.Transaction) error {
txData, err := NewTxDataFromTx(tx)
if err != nil {
return err
}
anyTxData, err := PackTxData(txData)
if err != nil {
return err
}
msg.Data = anyTxData
msg.Hash = tx.Hash().Hex()
return nil
}
// Route returns the route value of an MsgEthereumTx.
func (msg MsgEthereumTx) Route() string { return RouterKey }
// Type returns the type value of an MsgEthereumTx.
func (msg MsgEthereumTx) Type() string { return TypeMsgEthereumTx }
// ValidateBasic implements the sdk.Msg interface. It performs basic validation
// checks of a Transaction. If returns an error if validation fails.
func (msg MsgEthereumTx) ValidateBasic() error {
if msg.From != "" {
if err := types.ValidateAddress(msg.From); err != nil {
return errorsmod.Wrap(err, "invalid from address")
}
}
// Validate Size_ field, should be kept empty
if msg.Size_ != 0 {
return errorsmod.Wrapf(errortypes.ErrInvalidRequest, "tx size is deprecated")
}
txData, err := UnpackTxData(msg.Data)
if err != nil {
return errorsmod.Wrap(err, "failed to unpack tx data")
}
// prevent txs with 0 gas to fill up the mempool
if txData.GetGas() == 0 {
return errorsmod.Wrap(ErrInvalidGasLimit, "gas limit must not be zero")
}
if err := txData.Validate(); err != nil {
return err
}
// Validate Hash field after validated txData to avoid panic
txHash := msg.AsTransaction().Hash().Hex()
if msg.Hash != txHash {
return errorsmod.Wrapf(errortypes.ErrInvalidRequest, "invalid tx hash %s, expected: %s", msg.Hash, txHash)
}
return nil
}
// GetMsgs returns a single MsgEthereumTx as an sdk.Msg.
func (msg *MsgEthereumTx) GetMsgs() []sdk.Msg {
return []sdk.Msg{msg}
}
// GetSigners returns the expected signers for an Ethereum transaction message.
// For such a message, there should exist only a single 'signer'.
//
// NOTE: This method panics if 'Sign' hasn't been called first.
func (msg *MsgEthereumTx) GetSigners() []sdk.AccAddress {
data, err := UnpackTxData(msg.Data)
if err != nil {
panic(err)
}
sender, err := msg.GetSender(data.GetChainID())
if err != nil {
panic(err)
}
signer := sdk.AccAddress(sender.Bytes())
return []sdk.AccAddress{signer}
}
// GetSignBytes returns the Amino bytes of an Ethereum transaction message used
// for signing.
//
// NOTE: This method cannot be used as a chain ID is needed to create valid bytes
// to sign over. Use 'RLPSignBytes' instead.
func (msg MsgEthereumTx) GetSignBytes() []byte {
panic("must use 'RLPSignBytes' with a chain ID to get the valid bytes to sign")
}
// Sign calculates a secp256k1 ECDSA signature and signs the transaction. It
// takes a keyring signer and the chainID to sign an Ethereum transaction according to
// EIP155 standard.
// This method mutates the transaction as it populates the V, R, S
// fields of the Transaction's Signature.
// The function will fail if the sender address is not defined for the msg or if
// the sender is not registered on the keyring
func (msg *MsgEthereumTx) Sign(ethSigner ethtypes.Signer, keyringSigner keyring.Signer) error {
from := msg.GetFrom()
if from.Empty() {
return fmt.Errorf("sender address not defined for message")
}
tx := msg.AsTransaction()
txHash := ethSigner.Hash(tx)
sig, _, err := keyringSigner.SignByAddress(from, txHash.Bytes())
if err != nil {
return err
}
tx, err = tx.WithSignature(ethSigner, sig)
if err != nil {
return err
}
return msg.FromEthereumTx(tx)
}
// GetGas implements the GasTx interface. It returns the GasLimit of the transaction.
func (msg MsgEthereumTx) GetGas() uint64 {
txData, err := UnpackTxData(msg.Data)
if err != nil {
return 0
}
return txData.GetGas()
}
// GetFee returns the fee for non dynamic fee tx
func (msg MsgEthereumTx) GetFee() *big.Int {
txData, err := UnpackTxData(msg.Data)
if err != nil {
return nil
}
return txData.Fee()
}
// GetEffectiveFee returns the fee for dynamic fee tx
func (msg MsgEthereumTx) GetEffectiveFee(baseFee *big.Int) *big.Int {
txData, err := UnpackTxData(msg.Data)
if err != nil {
return nil
}
return txData.EffectiveFee(baseFee)
}
// GetFrom loads the ethereum sender address from the sigcache and returns an
// sdk.AccAddress from its bytes
func (msg *MsgEthereumTx) GetFrom() sdk.AccAddress {
if msg.From == "" {
return nil
}
return common.HexToAddress(msg.From).Bytes()
}
// AsTransaction creates an Ethereum Transaction type from the msg fields
func (msg MsgEthereumTx) AsTransaction() *ethtypes.Transaction {
txData, err := UnpackTxData(msg.Data)
if err != nil {
return nil
}
return ethtypes.NewTx(txData.AsEthereumData())
}
// AsMessage creates an Ethereum core.Message from the msg fields
func (msg MsgEthereumTx) AsMessage(signer ethtypes.Signer, baseFee *big.Int) (core.Message, error) {
txData, err := UnpackTxData(msg.Data)
if err != nil {
return nil, err
}
gasPrice, gasFeeCap, gasTipCap := txData.GetGasPrice(), txData.GetGasFeeCap(), txData.GetGasTipCap()
if baseFee != nil {
gasPrice = math.BigMin(gasPrice.Add(gasTipCap, baseFee), gasFeeCap)
}
var from common.Address
if len(msg.From) > 0 {
// user can't set arbitrary value in `From` field in transaction,
// the SigVerify ante handler will verify the signature and recover
// the sender address and populate the `From` field, so the other code can
// use it directly when available.
from = common.HexToAddress(msg.From)
} else {
// heavy path
from, err = signer.Sender(msg.AsTransaction())
if err != nil {
return nil, err
}
}
ethMsg := ethtypes.NewMessage(
from,
txData.GetTo(),
txData.GetNonce(),
txData.GetValue(),
txData.GetGas(),
gasPrice, gasFeeCap, gasTipCap,
txData.GetData(),
txData.GetAccessList(),
false,
)
return ethMsg, nil
}
// GetSender extracts the sender address from the signature values using the latest signer for the given chainID.
func (msg *MsgEthereumTx) GetSender(chainID *big.Int) (common.Address, error) {
signer := ethtypes.LatestSignerForChainID(chainID)
from, err := signer.Sender(msg.AsTransaction())
if err != nil {
return common.Address{}, err
}
msg.From = from.Hex()
return from, nil
}
// UnpackInterfaces implements UnpackInterfacesMesssage.UnpackInterfaces
func (msg MsgEthereumTx) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
return unpacker.UnpackAny(msg.Data, new(TxData))
}
// UnmarshalBinary decodes the canonical encoding of transactions.
func (msg *MsgEthereumTx) UnmarshalBinary(b []byte) error {
tx := ðtypes.Transaction{}
if err := tx.UnmarshalBinary(b); err != nil {
return err
}
return msg.FromEthereumTx(tx)
}
// BuildTx builds the canonical cosmos tx from ethereum msg
func (msg *MsgEthereumTx) BuildTx(b client.TxBuilder, evmDenom string) (signing.Tx, error) {
builder, ok := b.(authtx.ExtensionOptionsTxBuilder)
if !ok {
return nil, errors.New("unsupported builder")
}
option, err := codectypes.NewAnyWithValue(&ExtensionOptionsEthereumTx{})
if err != nil {
return nil, err
}
txData, err := UnpackTxData(msg.Data)
if err != nil {
return nil, err
}
fees := make(sdk.Coins, 0)
feeAmt := sdkmath.NewIntFromBigInt(txData.Fee())
if feeAmt.Sign() > 0 {
fees = append(fees, sdk.NewCoin(evmDenom, feeAmt))
}
builder.SetExtensionOptions(option)
// A valid msg should have empty `From`
msg.From = ""
err = builder.SetMsgs(msg)
if err != nil {
return nil, err
}
builder.SetFeeAmount(fees)
builder.SetGasLimit(msg.GetGas())
tx := builder.GetTx()
return tx, nil
}
// GetSigners returns the expected signers for a MsgUpdateParams message.
func (m MsgUpdateParams) GetSigners() []sdk.AccAddress {
//#nosec G703 -- gosec raises a warning about a non-handled error which we deliberately ignore here
addr, _ := sdk.AccAddressFromBech32(m.Authority)
return []sdk.AccAddress{addr}
}
// ValidateBasic does a sanity check of the provided data
func (m *MsgUpdateParams) ValidateBasic() error {
if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil {
return errorsmod.Wrap(err, "invalid authority address")
}
return m.Params.Validate()
}
// GetSignBytes implements the LegacyMsg interface.
func (m MsgUpdateParams) GetSignBytes() []byte {
return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&m))
}