-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
407 lines (345 loc) · 11.5 KB
/
builder.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
package account
import (
"context"
stdjson "encoding/json"
"github.com/bytom/bystack/blockchain/signers"
"github.com/bytom/bystack/blockchain/txbuilder"
"github.com/bytom/bystack/common"
"github.com/bytom/bystack/consensus"
"github.com/bytom/bystack/crypto/sm2/chainkd"
"github.com/bytom/bystack/encoding/json"
"github.com/bytom/bystack/errors"
"github.com/bytom/bystack/protocol/bc"
"github.com/bytom/bystack/protocol/bc/types"
"github.com/bytom/bystack/protocol/vm/vmutil"
)
//DecodeSpendAction unmarshal JSON-encoded data of spend action
func (m *Manager) DecodeSpendAction(data []byte) (txbuilder.Action, error) {
a := &spendAction{accounts: m}
return a, stdjson.Unmarshal(data, a)
}
type spendAction struct {
accounts *Manager
bc.AssetAmount
AccountID string `json:"account_id"`
UseUnconfirmed bool `json:"use_unconfirmed"`
}
func (a *spendAction) ActionType() string {
return "spend_account"
}
// MergeSpendAction merge common assetID and accountID spend action
func MergeSpendAction(actions []txbuilder.Action) []txbuilder.Action {
resultActions := []txbuilder.Action{}
spendActionMap := make(map[string]*spendAction)
for _, act := range actions {
switch act := act.(type) {
case *spendAction:
actionKey := act.AssetId.String() + act.AccountID
if tmpAct, ok := spendActionMap[actionKey]; ok {
tmpAct.Amount += act.Amount
tmpAct.UseUnconfirmed = tmpAct.UseUnconfirmed || act.UseUnconfirmed
} else {
spendActionMap[actionKey] = act
resultActions = append(resultActions, act)
}
default:
resultActions = append(resultActions, act)
}
}
return resultActions
}
//calcMergeGas calculate the gas required that n utxos are merged into one
func calcMergeGas(num int) uint64 {
gas := uint64(0)
for num > 1 {
gas += txbuilder.ChainTxMergeGas
num -= txbuilder.ChainTxUtxoNum - 1
}
return gas
}
func (m *Manager) reserveBtmUtxoChain(builder *txbuilder.TemplateBuilder, accountID string, amount uint64, useUnconfirmed bool) ([]*UTXO, error) {
reservedAmount := uint64(0)
utxos := []*UTXO{}
for gasAmount := uint64(0); reservedAmount < gasAmount+amount; gasAmount = calcMergeGas(len(utxos)) {
reserveAmount := amount + gasAmount - reservedAmount
res, err := m.utxoKeeper.Reserve(accountID, consensus.BTMAssetID, reserveAmount, useUnconfirmed, nil, builder.MaxTime())
if err != nil {
return nil, err
}
builder.OnRollback(func() { m.utxoKeeper.Cancel(res.id) })
reservedAmount += reserveAmount + res.change
utxos = append(utxos, res.utxos[:]...)
}
return utxos, nil
}
func (m *Manager) buildBtmTxChain(utxos []*UTXO, signer *signers.Signer) ([]*txbuilder.Template, *UTXO, error) {
if len(utxos) == 0 {
return nil, nil, errors.New("mergeSpendActionUTXO utxos num 0")
}
tpls := []*txbuilder.Template{}
if len(utxos) == 1 {
return tpls, utxos[len(utxos)-1], nil
}
acp, err := m.GetLocalCtrlProgramByAddress(utxos[0].Address)
if err != nil {
return nil, nil, err
}
buildAmount := uint64(0)
builder := &txbuilder.TemplateBuilder{}
for index := 0; index < len(utxos); index++ {
input, sigInst, err := UtxoToInputs(signer, utxos[index])
if err != nil {
return nil, nil, err
}
if err = builder.AddInput(input, sigInst); err != nil {
return nil, nil, err
}
buildAmount += input.Amount()
if builder.InputCount() != txbuilder.ChainTxUtxoNum && index != len(utxos)-1 {
continue
}
outAmount := buildAmount - txbuilder.ChainTxMergeGas
output := types.NewOriginalTxOutput(*consensus.BTMAssetID, outAmount, acp.ControlProgram, utxos[index].StateData)
if err := builder.AddOutput(output); err != nil {
return nil, nil, err
}
tpl, _, err := builder.Build()
if err != nil {
return nil, nil, err
}
bcOut, err := tpl.Transaction.OriginalOutput(*tpl.Transaction.ResultIds[0])
if err != nil {
return nil, nil, err
}
utxos = append(utxos, &UTXO{
OutputID: *tpl.Transaction.ResultIds[0],
AssetID: *consensus.BTMAssetID,
Amount: outAmount,
ControlProgram: acp.ControlProgram,
StateData: utxos[index].StateData,
SourceID: *bcOut.Source.Ref,
SourcePos: bcOut.Source.Position,
ControlProgramIndex: acp.KeyIndex,
Address: acp.Address,
Change: acp.Change,
})
tpls = append(tpls, tpl)
buildAmount = 0
builder = &txbuilder.TemplateBuilder{}
if index == len(utxos)-2 {
break
}
}
return tpls, utxos[len(utxos)-1], nil
}
// SpendAccountChain build the spend action with auto merge utxo function
func SpendAccountChain(ctx context.Context, builder *txbuilder.TemplateBuilder, action txbuilder.Action) ([]*txbuilder.Template, error) {
act, ok := action.(*spendAction)
if !ok {
return nil, errors.New("fail to convert the spend action")
}
if *act.AssetId != *consensus.BTMAssetID {
return nil, errors.New("spend chain action only support BTM")
}
utxos, err := act.accounts.reserveBtmUtxoChain(builder, act.AccountID, act.Amount, act.UseUnconfirmed)
if err != nil {
return nil, err
}
acct, err := act.accounts.FindByID(act.AccountID)
if err != nil {
return nil, err
}
tpls, utxo, err := act.accounts.buildBtmTxChain(utxos, acct.Signer)
if err != nil {
return nil, err
}
input, sigInst, err := UtxoToInputs(acct.Signer, utxo)
if err != nil {
return nil, err
}
if err := builder.AddInput(input, sigInst); err != nil {
return nil, err
}
if utxo.Amount > act.Amount {
if err = builder.AddOutput(types.NewOriginalTxOutput(*consensus.BTMAssetID, utxo.Amount-act.Amount, utxo.ControlProgram, utxo.StateData)); err != nil {
return nil, errors.Wrap(err, "adding change output")
}
}
return tpls, nil
}
func (a *spendAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
var missing []string
if a.AccountID == "" {
missing = append(missing, "account_id")
}
if a.AssetId.IsZero() {
missing = append(missing, "asset_id")
}
if a.AssetAmount.Amount == 0 {
missing = append(missing, "amount")
}
if len(missing) > 0 {
return txbuilder.MissingFieldsError(missing...)
}
acct, err := a.accounts.FindByID(a.AccountID)
if err != nil {
return errors.Wrap(err, "get account info")
}
res, err := a.accounts.utxoKeeper.Reserve(a.AccountID, a.AssetId, a.Amount, a.UseUnconfirmed, nil, b.MaxTime())
if err != nil {
return errors.Wrap(err, "reserving utxos")
}
// Cancel the reservation if the build gets rolled back.
b.OnRollback(func() { a.accounts.utxoKeeper.Cancel(res.id) })
for _, r := range res.utxos {
txInput, sigInst, err := UtxoToInputs(acct.Signer, r)
if err != nil {
return errors.Wrap(err, "creating inputs")
}
if err = b.AddInput(txInput, sigInst); err != nil {
return errors.Wrap(err, "adding inputs")
}
}
if res.change > 0 {
if err = b.AddOutput(types.NewOriginalTxOutput(*a.AssetId, res.change, res.utxos[0].ControlProgram, nil)); err != nil {
return errors.Wrap(err, "adding change output")
}
}
return nil
}
//DecodeSpendUTXOAction unmarshal JSON-encoded data of spend utxo action
func (m *Manager) DecodeSpendUTXOAction(data []byte) (txbuilder.Action, error) {
a := &spendUTXOAction{accounts: m}
return a, stdjson.Unmarshal(data, a)
}
type spendUTXOAction struct {
accounts *Manager
OutputID *bc.Hash `json:"output_id"`
UseUnconfirmed bool `json:"use_unconfirmed"`
Arguments []txbuilder.ContractArgument `json:"arguments"`
}
func (a *spendUTXOAction) ActionType() string {
return "spend_account_unspent_output"
}
func (a *spendUTXOAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
if a.OutputID == nil {
return txbuilder.MissingFieldsError("output_id")
}
res, err := a.accounts.utxoKeeper.ReserveParticular(*a.OutputID, a.UseUnconfirmed, b.MaxTime())
if err != nil {
return err
}
b.OnRollback(func() { a.accounts.utxoKeeper.Cancel(res.id) })
var accountSigner *signers.Signer
if len(res.utxos[0].AccountID) != 0 {
account, err := a.accounts.FindByID(res.utxos[0].AccountID)
if err != nil {
return err
}
accountSigner = account.Signer
}
txInput, sigInst, err := UtxoToInputs(accountSigner, res.utxos[0])
if err != nil {
return err
}
if a.Arguments == nil {
return b.AddInput(txInput, sigInst)
}
sigInst = &txbuilder.SigningInstruction{}
if err := txbuilder.AddContractArgs(sigInst, a.Arguments); err != nil {
return err
}
return b.AddInput(txInput, sigInst)
}
// UtxoToInputs convert an utxo to the txinput
func UtxoToInputs(signer *signers.Signer, u *UTXO) (*types.TxInput, *txbuilder.SigningInstruction, error) {
txInput := types.NewSpendInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram, u.StateData)
if u.Vote != nil {
txInput = types.NewVetoInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram, u.Vote, nil)
}
sigInst := &txbuilder.SigningInstruction{}
if signer == nil {
return txInput, sigInst, nil
}
path, err := signers.Path(signer, signers.AccountKeySpace, u.Change, u.ControlProgramIndex)
if err != nil {
return nil, nil, err
}
if u.Address == "" {
sigInst.AddWitnessKeys(signer.XPubs, path, signer.Quorum)
return txInput, sigInst, nil
}
address, err := common.DecodeAddress(u.Address, &consensus.ActiveNetParams)
if err != nil {
return nil, nil, err
}
sigInst.AddRawWitnessKeys(signer.XPubs, path, signer.Quorum)
derivedXPubs := chainkd.DeriveXPubs(signer.XPubs, path)
switch address.(type) {
case *common.AddressWitnessPubKeyHash:
derivedPK := derivedXPubs[0].PublicKey()
sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness([]byte(derivedPK)))
case *common.AddressWitnessScriptHash:
derivedPKs := chainkd.XPubKeys(derivedXPubs)
script, err := vmutil.P2SPMultiSigProgram(derivedPKs, signer.Quorum)
if err != nil {
return nil, nil, err
}
sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness(script))
default:
return nil, nil, errors.New("unsupport address type")
}
return txInput, sigInst, nil
}
//DecodeVetoAction unmarshal JSON-encoded data of spend action
func (m *Manager) DecodeVetoAction(data []byte) (txbuilder.Action, error) {
a := &vetoAction{accounts: m}
return a, stdjson.Unmarshal(data, a)
}
type vetoAction struct {
accounts *Manager
bc.AssetAmount
AccountID string `json:"account_id"`
Vote json.HexBytes `json:"vote"`
UseUnconfirmed bool `json:"use_unconfirmed"`
}
func (a *vetoAction) ActionType() string {
return "veto"
}
func (a *vetoAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
var missing []string
if a.AccountID == "" {
missing = append(missing, "account_id")
}
if a.AssetId.IsZero() {
missing = append(missing, "asset_id")
}
if len(missing) > 0 {
return txbuilder.MissingFieldsError(missing...)
}
acct, err := a.accounts.FindByID(a.AccountID)
if err != nil {
return errors.Wrap(err, "get account info")
}
res, err := a.accounts.utxoKeeper.Reserve(a.AccountID, a.AssetId, a.Amount, a.UseUnconfirmed, a.Vote, b.MaxTime())
if err != nil {
return errors.Wrap(err, "reserving utxos")
}
// Cancel the reservation if the build gets rolled back.
b.OnRollback(func() { a.accounts.utxoKeeper.Cancel(res.id) })
for _, r := range res.utxos {
txInput, sigInst, err := UtxoToInputs(acct.Signer, r)
if err != nil {
return errors.Wrap(err, "creating inputs")
}
if err = b.AddInput(txInput, sigInst); err != nil {
return errors.Wrap(err, "adding inputs")
}
}
if res.change > 0 {
if err = b.AddOutput(types.NewOriginalTxOutput(*a.AssetId, res.change, res.utxos[0].ControlProgram, nil)); err != nil {
return errors.Wrap(err, "adding change output")
}
}
return nil
}