forked from ava-labs/coreth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
export_tx.go
390 lines (354 loc) · 10.6 KB
/
export_tx.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
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package evm
import (
"fmt"
"math/big"
"github.com/haowang0402/coreth/core/state"
"github.com/haowang0402/coreth/params"
"github.com/haowang0402/avalanchego/chains/atomic"
"github.com/haowang0402/avalanchego/ids"
"github.com/haowang0402/avalanchego/snow"
"github.com/haowang0402/avalanchego/utils/constants"
"github.com/haowang0402/avalanchego/utils/crypto"
"github.com/haowang0402/avalanchego/utils/math"
"github.com/haowang0402/avalanchego/utils/wrappers"
"github.com/haowang0402/avalanchego/vms/components/avax"
"github.com/haowang0402/avalanchego/vms/components/verify"
"github.com/haowang0402/avalanchego/vms/secp256k1fx"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/log"
)
// UnsignedExportTx is an unsigned ExportTx
type UnsignedExportTx struct {
avax.Metadata
// ID of the network on which this tx was issued
NetworkID uint32 `serialize:"true" json:"networkID"`
// ID of this blockchain.
BlockchainID ids.ID `serialize:"true" json:"blockchainID"`
// Which chain to send the funds to
DestinationChain ids.ID `serialize:"true" json:"destinationChain"`
// Inputs
Ins []EVMInput `serialize:"true" json:"inputs"`
// Outputs that are exported to the chain
ExportedOutputs []*avax.TransferableOutput `serialize:"true" json:"exportedOutputs"`
}
// InputUTXOs returns a set of all the hash(address:nonce) exporting funds.
func (tx *UnsignedExportTx) InputUTXOs() ids.Set {
set := ids.NewSet(len(tx.Ins))
for _, in := range tx.Ins {
// Total populated bytes is 20 (Address) + 8 (Nonce), however, we allocate
// 32 bytes to make ids.ID casting easier.
var rawID [32]byte
packer := wrappers.Packer{Bytes: rawID[:]}
packer.PackLong(in.Nonce)
packer.PackBytes(in.Address.Bytes())
set.Add(ids.ID(rawID))
}
return set
}
// Verify this transaction is well-formed
func (tx *UnsignedExportTx) Verify(
ctx *snow.Context,
rules params.Rules,
) error {
switch {
case tx == nil:
return errNilTx
case len(tx.ExportedOutputs) == 0:
return errNoExportOutputs
case tx.NetworkID != ctx.NetworkID:
return errWrongNetworkID
case ctx.ChainID != tx.BlockchainID:
return errWrongBlockchainID
}
// Make sure that the tx has a valid peer chain ID
if rules.IsApricotPhase5 {
// Note that SameSubnet verifies that [tx.DestinationChain] isn't this
// chain's ID
if err := verify.SameSubnet(ctx, tx.DestinationChain); err != nil {
return errWrongChainID
}
} else {
if tx.DestinationChain != ctx.XChainID {
return errWrongChainID
}
}
for _, in := range tx.Ins {
if err := in.Verify(); err != nil {
return err
}
}
for _, out := range tx.ExportedOutputs {
if err := out.Verify(); err != nil {
return err
}
assetID := out.AssetID()
if assetID != ctx.AVAXAssetID && tx.DestinationChain == constants.PlatformChainID {
return errWrongChainID
}
}
if !avax.IsSortedTransferableOutputs(tx.ExportedOutputs, Codec) {
return errOutputsNotSorted
}
if rules.IsApricotPhase1 && !IsSortedAndUniqueEVMInputs(tx.Ins) {
return errInputsNotSortedUnique
}
return nil
}
func (tx *UnsignedExportTx) GasUsed(fixedFee bool) (uint64, error) {
byteCost := calcBytesCost(len(tx.UnsignedBytes()))
numSigs := uint64(len(tx.Ins))
sigCost, err := math.Mul64(numSigs, secp256k1fx.CostPerSignature)
if err != nil {
return 0, err
}
cost, err := math.Add64(byteCost, sigCost)
if err != nil {
return 0, err
}
if fixedFee {
cost, err = math.Add64(cost, params.AtomicTxBaseCost)
if err != nil {
return 0, err
}
}
return cost, nil
}
// Amount of [assetID] burned by this transaction
func (tx *UnsignedExportTx) Burned(assetID ids.ID) (uint64, error) {
var (
spent uint64
input uint64
err error
)
for _, out := range tx.ExportedOutputs {
if out.AssetID() == assetID {
spent, err = math.Add64(spent, out.Output().Amount())
if err != nil {
return 0, err
}
}
}
for _, in := range tx.Ins {
if in.AssetID == assetID {
input, err = math.Add64(input, in.Amount)
if err != nil {
return 0, err
}
}
}
return math.Sub64(input, spent)
}
// SemanticVerify this transaction is valid.
func (tx *UnsignedExportTx) SemanticVerify(
vm *VM,
stx *Tx,
_ *Block,
baseFee *big.Int,
rules params.Rules,
) error {
if err := tx.Verify(vm.ctx, rules); err != nil {
return err
}
// Check the transaction consumes and produces the right amounts
fc := avax.NewFlowChecker()
switch {
// Apply dynamic fees to export transactions as of Apricot Phase 3
case rules.IsApricotPhase3:
gasUsed, err := stx.GasUsed(rules.IsApricotPhase5)
if err != nil {
return err
}
txFee, err := calculateDynamicFee(gasUsed, baseFee)
if err != nil {
return err
}
fc.Produce(vm.ctx.AVAXAssetID, txFee)
// Apply fees to export transactions before Apricot Phase 3
default:
fc.Produce(vm.ctx.AVAXAssetID, params.AvalancheAtomicTxFee)
}
for _, out := range tx.ExportedOutputs {
fc.Produce(out.AssetID(), out.Output().Amount())
}
for _, in := range tx.Ins {
fc.Consume(in.AssetID, in.Amount)
}
if err := fc.Verify(); err != nil {
return fmt.Errorf("export tx flow check failed due to: %w", err)
}
if len(tx.Ins) != len(stx.Creds) {
return fmt.Errorf("export tx contained mismatched number of inputs/credentials (%d vs. %d)", len(tx.Ins), len(stx.Creds))
}
for i, input := range tx.Ins {
cred, ok := stx.Creds[i].(*secp256k1fx.Credential)
if !ok {
return fmt.Errorf("expected *secp256k1fx.Credential but got %T", cred)
}
if err := cred.Verify(); err != nil {
return err
}
if len(cred.Sigs) != 1 {
return fmt.Errorf("expected one signature for EVM Input Credential, but found: %d", len(cred.Sigs))
}
pubKeyIntf, err := vm.secpFactory.RecoverPublicKey(tx.UnsignedBytes(), cred.Sigs[0][:])
if err != nil {
return err
}
pubKey, ok := pubKeyIntf.(*crypto.PublicKeySECP256K1R)
if !ok {
// This should never happen
return fmt.Errorf("expected *crypto.PublicKeySECP256K1R but got %T", pubKeyIntf)
}
if input.Address != PublicKeyToEthAddress(pubKey) {
return errPublicKeySignatureMismatch
}
}
return nil
}
// AtomicOps returns the atomic operations for this transaction.
func (tx *UnsignedExportTx) AtomicOps() (ids.ID, *atomic.Requests, error) {
txID := tx.ID()
elems := make([]*atomic.Element, len(tx.ExportedOutputs))
for i, out := range tx.ExportedOutputs {
utxo := &avax.UTXO{
UTXOID: avax.UTXOID{
TxID: txID,
OutputIndex: uint32(i),
},
Asset: avax.Asset{ID: out.AssetID()},
Out: out.Out,
}
utxoBytes, err := Codec.Marshal(codecVersion, utxo)
if err != nil {
return ids.ID{}, nil, err
}
utxoID := utxo.InputID()
elem := &atomic.Element{
Key: utxoID[:],
Value: utxoBytes,
}
if out, ok := utxo.Out.(avax.Addressable); ok {
elem.Traits = out.Addresses()
}
elems[i] = elem
}
return tx.DestinationChain, &atomic.Requests{PutRequests: elems}, nil
}
// newExportTx returns a new ExportTx
func (vm *VM) newExportTx(
assetID ids.ID, // AssetID of the tokens to export
amount uint64, // Amount of tokens to export
chainID ids.ID, // Chain to send the UTXOs to
to ids.ShortID, // Address of chain recipient
baseFee *big.Int, // fee to use post-AP3
keys []*crypto.PrivateKeySECP256K1R, // Pay the fee and provide the tokens
) (*Tx, error) {
outs := []*avax.TransferableOutput{{ // Exported to X-Chain
Asset: avax.Asset{ID: assetID},
Out: &secp256k1fx.TransferOutput{
Amt: amount,
OutputOwners: secp256k1fx.OutputOwners{
Locktime: 0,
Threshold: 1,
Addrs: []ids.ShortID{to},
},
},
}}
var (
avaxNeeded uint64 = 0
ins, avaxIns []EVMInput
signers, avaxSigners [][]*crypto.PrivateKeySECP256K1R
err error
)
// consume non-AVAX
if assetID != vm.ctx.AVAXAssetID {
ins, signers, err = vm.GetSpendableFunds(keys, assetID, amount)
if err != nil {
return nil, fmt.Errorf("couldn't generate tx inputs/signers: %w", err)
}
} else {
avaxNeeded = amount
}
rules := vm.currentRules()
switch {
case rules.IsApricotPhase3:
utx := &UnsignedExportTx{
NetworkID: vm.ctx.NetworkID,
BlockchainID: vm.ctx.ChainID,
DestinationChain: chainID,
Ins: ins,
ExportedOutputs: outs,
}
tx := &Tx{UnsignedAtomicTx: utx}
if err := tx.Sign(vm.codec, nil); err != nil {
return nil, err
}
var cost uint64
cost, err = tx.GasUsed(rules.IsApricotPhase5)
if err != nil {
return nil, err
}
avaxIns, avaxSigners, err = vm.GetSpendableAVAXWithFee(keys, avaxNeeded, cost, baseFee)
default:
var newAvaxNeeded uint64
newAvaxNeeded, err = math.Add64(avaxNeeded, params.AvalancheAtomicTxFee)
if err != nil {
return nil, errOverflowExport
}
avaxIns, avaxSigners, err = vm.GetSpendableFunds(keys, vm.ctx.AVAXAssetID, newAvaxNeeded)
}
if err != nil {
return nil, fmt.Errorf("couldn't generate tx inputs/signers: %w", err)
}
ins = append(ins, avaxIns...)
signers = append(signers, avaxSigners...)
avax.SortTransferableOutputs(outs, vm.codec)
SortEVMInputsAndSigners(ins, signers)
// Create the transaction
utx := &UnsignedExportTx{
NetworkID: vm.ctx.NetworkID,
BlockchainID: vm.ctx.ChainID,
DestinationChain: chainID,
Ins: ins,
ExportedOutputs: outs,
}
tx := &Tx{UnsignedAtomicTx: utx}
if err := tx.Sign(vm.codec, signers); err != nil {
return nil, err
}
return tx, utx.Verify(vm.ctx, vm.currentRules())
}
// EVMStateTransfer executes the state update from the atomic export transaction
func (tx *UnsignedExportTx) EVMStateTransfer(ctx *snow.Context, state *state.StateDB) error {
addrs := map[[20]byte]uint64{}
for _, from := range tx.Ins {
if from.AssetID == ctx.AVAXAssetID {
log.Debug("crosschain", "dest", tx.DestinationChain, "addr", from.Address, "amount", from.Amount, "assetID", "AVAX")
// We multiply the input amount by x2cRate to convert AVAX back to the appropriate
// denomination before export.
amount := new(big.Int).Mul(
new(big.Int).SetUint64(from.Amount), x2cRate)
if state.GetBalance(from.Address).Cmp(amount) < 0 {
return errInsufficientFunds
}
state.SubBalance(from.Address, amount)
} else {
log.Debug("crosschain", "dest", tx.DestinationChain, "addr", from.Address, "amount", from.Amount, "assetID", from.AssetID)
amount := new(big.Int).SetUint64(from.Amount)
if state.GetBalanceMultiCoin(from.Address, common.Hash(from.AssetID)).Cmp(amount) < 0 {
return errInsufficientFunds
}
state.SubBalanceMultiCoin(from.Address, common.Hash(from.AssetID), amount)
}
if state.GetNonce(from.Address) != from.Nonce {
return errInvalidNonce
}
addrs[from.Address] = from.Nonce
}
for addr, nonce := range addrs {
state.SetNonce(addr, nonce+1)
}
return nil
}