-
Notifications
You must be signed in to change notification settings - Fork 86
/
tx_utils.go
286 lines (240 loc) · 8.21 KB
/
tx_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
package txs
import (
"fmt"
"math/big"
"github.com/artela-network/artela/x/evm/txs/support"
//"github.com/artela-network/artela/x/evm/txs"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
errortypes "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/msgservice"
"github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/gogoproto/proto"
errorsmod "cosmossdk.io/errors"
cosmos "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/crypto"
)
const (
// Amino names
updateParamsName = "artela/MsgUpdateParams"
)
var (
amino = codec.NewLegacyAmino()
// ModuleCdc references the global evm module codec. Note, the codec should
// ONLY be used in certain instances of tests and for JSON encoding.
ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry())
// AminoCdc is a amino codec created to support amino JSON compatible msgs.
AminoCdc = codec.NewAminoCodec(amino)
// DefaultPriorityReduction is the default amount of price values required for 1 unit of priority.
// Because priority is `int64` while price is `big.Int`, it's necessary to scale down the range to keep it more practical.
// The default value is the same as the `cosmos.DefaultPowerReduction`.
DefaultPriorityReduction = cosmos.DefaultPowerReduction
EmptyCodeHash = crypto.Keccak256(nil)
)
// This is required for the GetSignBytes function
func init() {
RegisterLegacyAminoCodec(amino)
amino.Seal()
}
// RegisterInterfaces registers the client interfaces to protobuf Any.
func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
registry.RegisterImplementations(
(*tx.TxExtensionOptionI)(nil),
&ExtensionOptionsEthereumTx{},
)
registry.RegisterImplementations(
(*cosmos.Msg)(nil),
&MsgEthereumTx{},
&MsgUpdateParams{},
)
registry.RegisterInterface(
"artela.evm.v1.TxData",
(*TxData)(nil),
&DynamicFeeTx{},
&AccessListTx{},
&LegacyTx{},
)
msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc)
}
// ===============================================================
// Pack and UnPack
// ===============================================================
// PackTxData constructs a new Any packed with the given txs data value. It returns
// an error if the client states can't be casted to a protobuf message or if the concrete
// implementation is not registered to the protobuf codec.
func PackTxData(txData TxData) (*codectypes.Any, error) {
msg, ok := txData.(proto.Message)
if !ok {
return nil, errorsmod.Wrapf(errortypes.ErrPackAny, "cannot proto marshal %T", txData)
}
anyTxData, err := codectypes.NewAnyWithValue(msg)
if err != nil {
return nil, errorsmod.Wrap(errortypes.ErrPackAny, err.Error())
}
return anyTxData, nil
}
// UnpackTxData unpacks an Any into a TxData. It returns an error if the
// client states can't be unpacked into a TxData.
func UnpackTxData(any *codectypes.Any) (TxData, error) {
if any == nil {
return nil, errorsmod.Wrap(errortypes.ErrUnpackAny, "protobuf Any message cannot be nil")
}
txData, ok := any.GetCachedValue().(TxData)
if !ok {
return nil, errorsmod.Wrapf(errortypes.ErrUnpackAny, "cannot unpack Any into TxData %T", any)
}
return txData, nil
}
// ===============================================================
// Codec
// ===============================================================
// RegisterLegacyAminoCodec required for EIP-712
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterConcrete(&MsgUpdateParams{}, updateParamsName, nil)
}
// DecodeTxResponse decodes an protobuf-encoded byte slice into TxResponse
func DecodeTxResponse(in []byte) (*MsgEthereumTxResponse, error) {
var txMsgData cosmos.TxMsgData
if err := proto.Unmarshal(in, &txMsgData); err != nil {
return nil, err
}
if len(txMsgData.MsgResponses) == 0 {
return &MsgEthereumTxResponse{}, nil
}
var res MsgEthereumTxResponse
if err := proto.Unmarshal(txMsgData.MsgResponses[0].Value, &res); err != nil {
return nil, errorsmod.Wrap(err, "failed to unmarshal txs response message data")
}
return &res, nil
}
// EncodeTransactionLogs encodes TransactionLogs slice into a protobuf-encoded byte slice.
func EncodeTransactionLogs(res *support.TransactionLogs) ([]byte, error) {
return proto.Marshal(res)
}
// DecodeTransactionLogs decodes an protobuf-encoded byte slice into TransactionLogs
func DecodeTransactionLogs(data []byte) (support.TransactionLogs, error) {
var logs support.TransactionLogs
err := proto.Unmarshal(data, &logs)
if err != nil {
return support.TransactionLogs{}, err
}
return logs, nil
}
// UnwrapEthereumMsg extract MsgEthereumTx from wrapping cosmos.Tx
func UnwrapEthereumMsg(tx *cosmos.Tx, ethHash common.Hash) (*MsgEthereumTx, error) {
if tx == nil {
return nil, fmt.Errorf("invalid txs: nil")
}
for _, msg := range (*tx).GetMsgs() {
ethMsg, ok := msg.(*MsgEthereumTx)
if !ok {
return nil, fmt.Errorf("invalid txs type: %T", tx)
}
txHash := ethMsg.AsTransaction().Hash()
ethMsg.Hash = txHash.Hex()
if txHash == ethHash {
return ethMsg, nil
}
}
return nil, fmt.Errorf("eth txs not found: %s", ethHash)
}
// ===============================================================
// For Gas
// ===============================================================
// BinSearch execute the binary search and hone in on an executable gas limit
func BinSearch(lo, hi uint64, executable func(uint64) (bool, *MsgEthereumTxResponse, error)) (uint64, error) {
for lo+1 < hi {
mid := (hi + lo) / 2
failed, _, err := executable(mid)
// If the error is not nil(consensus error), it means the provided message
// call or txs will never be accepted no matter how much gas it is
// assigned. Return the error directly, don't struggle any more.
if err != nil {
return 0, err
}
if failed {
lo = mid
} else {
hi = mid
}
}
return hi, nil
}
// EffectiveGasPrice compute the effective gas price based on eip-1159 rules
// `effectiveGasPrice = min(baseFee + tipCap, feeCap)`
func EffectiveGasPrice(baseFee, feeCap, tipCap *big.Int) *big.Int {
return math.BigMin(new(big.Int).Add(tipCap, baseFee), feeCap)
}
// GetTxPriority returns the priority of a given Ethereum txs. It relies of the
// priority reduction global variable to calculate the txs priority given the txs
// tip price:
//
// tx_priority = tip_price / priority_reduction
func GetTxPriority(txData TxData, baseFee *big.Int) (priority int64) {
// calculate priority based on effective gas price
tipPrice := txData.EffectiveGasPrice(baseFee)
// if london hard fork is not enabled, tipPrice is the gasPrice
if baseFee != nil {
tipPrice = new(big.Int).Sub(tipPrice, baseFee)
}
priority = math.MaxInt64
priorityBig := new(big.Int).Quo(tipPrice, DefaultPriorityReduction.BigInt())
// safety check
if priorityBig.IsInt64() {
priority = priorityBig.Int64()
}
return priority
}
// ===============================================================
// Others
// ===============================================================
// DeriveChainID derives the chain id from the given v parameter.
//
// CONTRACT: v value is either:
//
// - {0,1} + CHAIN_ID * 2 + 35, if EIP155 is used
// - {0,1} + 27, otherwise
//
// Ref: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
func DeriveChainID(v *big.Int) *big.Int {
if v == nil || v.Sign() < 1 {
return nil
}
if v.BitLen() <= 64 {
v := v.Uint64()
if v == 27 || v == 28 {
return new(big.Int)
}
if v < 35 {
return nil
}
// V MUST be of the form {0,1} + CHAIN_ID * 2 + 35
return new(big.Int).SetUint64((v - 35) / 2)
}
v = new(big.Int).Sub(v, big.NewInt(35))
return v.Div(v, big.NewInt(2))
}
func rawSignatureValues(vBz, rBz, sBz []byte) (v, r, s *big.Int) {
if len(vBz) > 0 {
v = new(big.Int).SetBytes(vBz)
}
if len(rBz) > 0 {
r = new(big.Int).SetBytes(rBz)
}
if len(sBz) > 0 {
s = new(big.Int).SetBytes(sBz)
}
return v, r, s
}
func fee(gasPrice *big.Int, gas uint64) *big.Int {
gasLimit := new(big.Int).SetUint64(gas)
return new(big.Int).Mul(gasPrice, gasLimit)
}
func cost(fee, value *big.Int) *big.Int {
if value != nil {
return new(big.Int).Add(fee, value)
}
return fee
}