-
Notifications
You must be signed in to change notification settings - Fork 665
/
import_tx.go
261 lines (232 loc) · 7.33 KB
/
import_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
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package platformvm
import (
"errors"
"fmt"
"github.com/ava-labs/avalanchego/codec"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow"
"github.com/ava-labs/avalanchego/utils/crypto"
"github.com/ava-labs/avalanchego/utils/math"
"github.com/ava-labs/avalanchego/vms/components/avax"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
)
var (
errAssetIDMismatch = errors.New("asset IDs in the input don't match the utxo")
errWrongNumberOfCredentials = errors.New("should have the same number of credentials as inputs")
errNoImportInputs = errors.New("tx has no imported inputs")
errInputsNotSortedUnique = errors.New("inputs not sorted and unique")
_ UnsignedAtomicTx = &UnsignedImportTx{}
)
// UnsignedImportTx is an unsigned ImportTx
type UnsignedImportTx struct {
BaseTx `serialize:"true"`
// Which chain to consume the funds from
SourceChain ids.ID `serialize:"true" json:"sourceChain"`
// Inputs that consume UTXOs produced on the chain
ImportedInputs []*avax.TransferableInput `serialize:"true" json:"importedInputs"`
}
// InputUTXOs returns the UTXOIDs of the imported funds
func (tx *UnsignedImportTx) InputUTXOs() ids.Set {
set := ids.Set{}
for _, in := range tx.ImportedInputs {
set.Add(in.InputID())
}
return set
}
// Verify this transaction is well-formed
func (tx *UnsignedImportTx) Verify(
avmID ids.ID,
ctx *snow.Context,
c codec.Manager,
feeAmount uint64,
feeAssetID ids.ID,
) error {
switch {
case tx == nil:
return errNilTx
case tx.syntacticallyVerified: // already passed syntactic verification
return nil
case tx.SourceChain != avmID:
// TODO: remove this check if we allow for P->C swaps
return errWrongChainID
case len(tx.ImportedInputs) == 0:
return errNoImportInputs
}
if err := tx.BaseTx.Verify(ctx, c); err != nil {
return err
}
for _, in := range tx.ImportedInputs {
if err := in.Verify(); err != nil {
return fmt.Errorf("input failed verification: %w", err)
}
}
if !avax.IsSortedAndUniqueTransferableInputs(tx.ImportedInputs) {
return errInputsNotSortedUnique
}
tx.syntacticallyVerified = true
return nil
}
// SemanticVerify this transaction is valid.
func (tx *UnsignedImportTx) SemanticVerify(
vm *VM,
parentState MutableState,
stx *Tx,
) (VersionedState, TxError) {
if err := tx.Verify(vm.ctx.XChainID, vm.ctx, vm.codec, vm.TxFee, vm.ctx.AVAXAssetID); err != nil {
return nil, permError{err}
}
utxos := make([]*avax.UTXO, len(tx.Ins)+len(tx.ImportedInputs))
for index, input := range tx.Ins {
utxo, err := parentState.GetUTXO(input.InputID())
if err != nil {
return nil, tempError{
fmt.Errorf("failed to get UTXO %s: %w", &input.UTXOID, err),
}
}
utxos[index] = utxo
}
if vm.bootstrapped {
utxoIDs := make([][]byte, len(tx.ImportedInputs))
for i, in := range tx.ImportedInputs {
utxoID := in.UTXOID.InputID()
utxoIDs[i] = utxoID[:]
}
allUTXOBytes, err := vm.ctx.SharedMemory.Get(tx.SourceChain, utxoIDs)
if err != nil {
return nil, tempError{
fmt.Errorf("failed to get shared memory: %w", err),
}
}
for i, utxoBytes := range allUTXOBytes {
utxo := &avax.UTXO{}
if _, err := vm.codec.Unmarshal(utxoBytes, utxo); err != nil {
return nil, tempError{
fmt.Errorf("failed to unmarshal UTXO: %w", err),
}
}
utxos[i+len(tx.Ins)] = utxo
}
ins := make([]*avax.TransferableInput, len(tx.Ins)+len(tx.ImportedInputs))
copy(ins, tx.Ins)
copy(ins[len(tx.Ins):], tx.ImportedInputs)
if err := vm.semanticVerifySpendUTXOs(tx, utxos, ins, tx.Outs, stx.Creds, vm.TxFee, vm.ctx.AVAXAssetID); err != nil {
return nil, err
}
}
// Set up the state if this tx is committed
newState := newVersionedState(
parentState,
parentState.CurrentStakerChainState(),
parentState.PendingStakerChainState(),
)
// Consume the UTXOS
consumeInputs(newState, tx.Ins)
// Produce the UTXOS
txID := tx.ID()
produceOutputs(newState, txID, vm.ctx.AVAXAssetID, tx.Outs)
return newState, nil
}
// Accept this transaction and spend imported inputs
// We spend imported UTXOs here rather than in semanticVerify because
// we don't want to remove an imported UTXO in semanticVerify
// only to have the transaction not be Accepted. This would be inconsistent.
// Recall that imported UTXOs are not kept in a versionDB.
func (tx *UnsignedImportTx) Accept(ctx *snow.Context, batch database.Batch) error {
utxoIDs := make([][]byte, len(tx.ImportedInputs))
for i, in := range tx.ImportedInputs {
utxoID := in.InputID()
utxoIDs[i] = utxoID[:]
}
return ctx.SharedMemory.Remove(tx.SourceChain, utxoIDs, batch)
}
// Create a new transaction
func (vm *VM) newImportTx(
chainID ids.ID, // chain to import from
to ids.ShortID, // Address of recipient
keys []*crypto.PrivateKeySECP256K1R, // Keys to import the funds
changeAddr ids.ShortID, // Address to send change to, if there is any
) (*Tx, error) {
if vm.ctx.XChainID != chainID {
return nil, errWrongChainID
}
kc := secp256k1fx.NewKeychain()
for _, key := range keys {
kc.Add(key)
}
atomicUTXOs, _, _, err := vm.GetAtomicUTXOs(chainID, kc.Addresses(), ids.ShortEmpty, ids.Empty, -1)
if err != nil {
return nil, fmt.Errorf("problem retrieving atomic UTXOs: %w", err)
}
importedInputs := []*avax.TransferableInput{}
signers := [][]*crypto.PrivateKeySECP256K1R{}
importedAmount := uint64(0)
now := vm.clock.Unix()
for _, utxo := range atomicUTXOs {
if utxo.AssetID() != vm.ctx.AVAXAssetID {
continue
}
inputIntf, utxoSigners, err := kc.Spend(utxo.Out, now)
if err != nil {
continue
}
input, ok := inputIntf.(avax.TransferableIn)
if !ok {
continue
}
importedAmount, err = math.Add64(importedAmount, input.Amount())
if err != nil {
return nil, err
}
importedInputs = append(importedInputs, &avax.TransferableInput{
UTXOID: utxo.UTXOID,
Asset: utxo.Asset,
In: input,
})
signers = append(signers, utxoSigners)
}
avax.SortTransferableInputsWithSigners(importedInputs, signers)
if importedAmount == 0 {
return nil, errNoFunds // No imported UTXOs were spendable
}
ins := []*avax.TransferableInput{}
outs := []*avax.TransferableOutput{}
if importedAmount < vm.TxFee { // imported amount goes toward paying tx fee
var baseSigners [][]*crypto.PrivateKeySECP256K1R
ins, outs, _, baseSigners, err = vm.stake(keys, 0, vm.TxFee-importedAmount, changeAddr)
if err != nil {
return nil, fmt.Errorf("couldn't generate tx inputs/outputs: %w", err)
}
signers = append(baseSigners, signers...)
} else if importedAmount > vm.TxFee {
outs = append(outs, &avax.TransferableOutput{
Asset: avax.Asset{ID: vm.ctx.AVAXAssetID},
Out: &secp256k1fx.TransferOutput{
Amt: importedAmount - vm.TxFee,
OutputOwners: secp256k1fx.OutputOwners{
Locktime: 0,
Threshold: 1,
Addrs: []ids.ShortID{to},
},
},
})
}
// Create the transaction
utx := &UnsignedImportTx{
BaseTx: BaseTx{BaseTx: avax.BaseTx{
NetworkID: vm.ctx.NetworkID,
BlockchainID: vm.ctx.ChainID,
Outs: outs,
Ins: ins,
}},
SourceChain: chainID,
ImportedInputs: importedInputs,
}
tx := &Tx{UnsignedTx: utx}
if err := tx.Sign(vm.codec, signers); err != nil {
return nil, err
}
return tx, utx.Verify(vm.ctx.XChainID, vm.ctx, vm.codec, vm.TxFee, vm.ctx.AVAXAssetID)
}