OSDN Git Service

fix log
[bytom/vapor.git] / account / builder.go
1 package account
2
3 import (
4         "context"
5         stdjson "encoding/json"
6
7         "github.com/vapor/blockchain/signers"
8         "github.com/vapor/blockchain/txbuilder"
9         "github.com/vapor/common"
10         "github.com/vapor/consensus"
11         "github.com/vapor/crypto/ed25519/chainkd"
12         "github.com/vapor/encoding/json"
13         "github.com/vapor/errors"
14         "github.com/vapor/protocol/bc"
15         "github.com/vapor/protocol/bc/types"
16         "github.com/vapor/protocol/vm/vmutil"
17 )
18
19 var (
20         //chainTxUtxoNum maximum utxo quantity in a tx
21         chainTxUtxoNum = 20
22         //chainTxMergeGas chain tx gas
23         chainTxMergeGas = uint64(10000000)
24 )
25
26 //DecodeSpendAction unmarshal JSON-encoded data of spend action
27 func (m *Manager) DecodeSpendAction(data []byte) (txbuilder.Action, error) {
28         a := &spendAction{accounts: m}
29         return a, stdjson.Unmarshal(data, a)
30 }
31
32 type spendAction struct {
33         accounts *Manager
34         bc.AssetAmount
35         AccountID      string `json:"account_id"`
36         UseUnconfirmed bool   `json:"use_unconfirmed"`
37 }
38
39 func (a *spendAction) ActionType() string {
40         return "spend_account"
41 }
42
43 // MergeSpendAction merge common assetID and accountID spend action
44 func MergeSpendAction(actions []txbuilder.Action) []txbuilder.Action {
45         resultActions := []txbuilder.Action{}
46         spendActionMap := make(map[string]*spendAction)
47
48         for _, act := range actions {
49                 switch act := act.(type) {
50                 case *spendAction:
51                         actionKey := act.AssetId.String() + act.AccountID
52                         if tmpAct, ok := spendActionMap[actionKey]; ok {
53                                 tmpAct.Amount += act.Amount
54                                 tmpAct.UseUnconfirmed = tmpAct.UseUnconfirmed || act.UseUnconfirmed
55                         } else {
56                                 spendActionMap[actionKey] = act
57                                 resultActions = append(resultActions, act)
58                         }
59                 default:
60                         resultActions = append(resultActions, act)
61                 }
62         }
63         return resultActions
64 }
65
66 //calcMergeGas calculate the gas required that n utxos are merged into one
67 func calcMergeGas(num int) uint64 {
68         gas := uint64(0)
69         for num > 1 {
70                 gas += chainTxMergeGas
71                 num -= chainTxUtxoNum - 1
72         }
73         return gas
74 }
75
76 func (m *Manager) reserveBtmUtxoChain(builder *txbuilder.TemplateBuilder, accountID string, amount uint64, useUnconfirmed bool) ([]*UTXO, error) {
77         reservedAmount := uint64(0)
78         utxos := []*UTXO{}
79         for gasAmount := uint64(0); reservedAmount < gasAmount+amount; gasAmount = calcMergeGas(len(utxos)) {
80                 reserveAmount := amount + gasAmount - reservedAmount
81                 res, err := m.utxoKeeper.Reserve(accountID, consensus.BTMAssetID, reserveAmount, useUnconfirmed, nil, builder.MaxTime())
82                 if err != nil {
83                         return nil, err
84                 }
85
86                 builder.OnRollback(func() { m.utxoKeeper.Cancel(res.id) })
87                 reservedAmount += reserveAmount + res.change
88                 utxos = append(utxos, res.utxos[:]...)
89         }
90         return utxos, nil
91 }
92
93 func (m *Manager) BuildBtmTxChain(utxos []*UTXO, signer *signers.Signer) ([]*txbuilder.Template, *UTXO, error) {
94         if len(utxos) == 0 {
95                 return nil, nil, errors.New("mergeSpendActionUTXO utxos num 0")
96         }
97
98         tpls := []*txbuilder.Template{}
99         if len(utxos) == 1 {
100                 return tpls, utxos[len(utxos)-1], nil
101         }
102
103         acp, err := m.GetLocalCtrlProgramByAddress(utxos[0].Address)
104         if err != nil {
105                 return nil, nil, err
106         }
107
108         buildAmount := uint64(0)
109         builder := &txbuilder.TemplateBuilder{}
110         for index := 0; index < len(utxos); index++ {
111                 input, sigInst, err := UtxoToInputs(signer, utxos[index])
112                 if err != nil {
113                         return nil, nil, err
114                 }
115
116                 if err = builder.AddInput(input, sigInst); err != nil {
117                         return nil, nil, err
118                 }
119
120                 buildAmount += input.Amount()
121                 if builder.InputCount() != chainTxUtxoNum && index != len(utxos)-1 {
122                         continue
123                 }
124
125                 outAmount := buildAmount - chainTxMergeGas
126                 output := types.NewIntraChainOutput(*consensus.BTMAssetID, outAmount, acp.ControlProgram)
127                 if err := builder.AddOutput(output); err != nil {
128                         return nil, nil, err
129                 }
130
131                 tpl, _, err := builder.Build()
132                 if err != nil {
133                         return nil, nil, err
134                 }
135
136                 bcOut, err := tpl.Transaction.IntraChainOutput(*tpl.Transaction.ResultIds[0])
137                 if err != nil {
138                         return nil, nil, err
139                 }
140
141                 utxos = append(utxos, &UTXO{
142                         OutputID:            *tpl.Transaction.ResultIds[0],
143                         AssetID:             *consensus.BTMAssetID,
144                         Amount:              outAmount,
145                         ControlProgram:      acp.ControlProgram,
146                         SourceID:            *bcOut.Source.Ref,
147                         SourcePos:           bcOut.Source.Position,
148                         ControlProgramIndex: acp.KeyIndex,
149                         Address:             acp.Address,
150                         Change:              acp.Change,
151                 })
152
153                 tpls = append(tpls, tpl)
154                 buildAmount = 0
155                 builder = &txbuilder.TemplateBuilder{}
156                 if index == len(utxos)-2 {
157                         break
158                 }
159         }
160         return tpls, utxos[len(utxos)-1], nil
161 }
162
163 // SpendAccountChain build the spend action with auto merge utxo function
164 func SpendAccountChain(ctx context.Context, builder *txbuilder.TemplateBuilder, action txbuilder.Action) ([]*txbuilder.Template, error) {
165         act, ok := action.(*spendAction)
166         if !ok {
167                 return nil, errors.New("fail to convert the spend action")
168         }
169
170         if *act.AssetId != *consensus.BTMAssetID {
171                 return nil, errors.New("spend chain action only support BTM")
172         }
173
174         utxos, err := act.accounts.reserveBtmUtxoChain(builder, act.AccountID, act.Amount, act.UseUnconfirmed)
175         if err != nil {
176                 return nil, err
177         }
178
179         acct, err := act.accounts.FindByID(act.AccountID)
180         if err != nil {
181                 return nil, err
182         }
183
184         tpls, utxo, err := act.accounts.BuildBtmTxChain(utxos, acct.Signer)
185         if err != nil {
186                 return nil, err
187         }
188
189         input, sigInst, err := UtxoToInputs(acct.Signer, utxo)
190         if err != nil {
191                 return nil, err
192         }
193
194         if err := builder.AddInput(input, sigInst); err != nil {
195                 return nil, err
196         }
197
198         if utxo.Amount > act.Amount {
199                 if err = builder.AddOutput(types.NewIntraChainOutput(*consensus.BTMAssetID, utxo.Amount-act.Amount, utxo.ControlProgram)); err != nil {
200                         return nil, errors.Wrap(err, "adding change output")
201                 }
202         }
203         return tpls, nil
204 }
205
206 func (a *spendAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
207         var missing []string
208         if a.AccountID == "" {
209                 missing = append(missing, "account_id")
210         }
211         if a.AssetId.IsZero() {
212                 missing = append(missing, "asset_id")
213         }
214         if len(missing) > 0 {
215                 return txbuilder.MissingFieldsError(missing...)
216         }
217
218         acct, err := a.accounts.FindByID(a.AccountID)
219         if err != nil {
220                 return errors.Wrap(err, "get account info")
221         }
222
223         res, err := a.accounts.utxoKeeper.Reserve(a.AccountID, a.AssetId, a.Amount, a.UseUnconfirmed, nil, b.MaxTime())
224         if err != nil {
225                 return errors.Wrap(err, "reserving utxos")
226         }
227
228         // Cancel the reservation if the build gets rolled back.
229         b.OnRollback(func() { a.accounts.utxoKeeper.Cancel(res.id) })
230         for _, r := range res.utxos {
231                 txInput, sigInst, err := UtxoToInputs(acct.Signer, r)
232                 if err != nil {
233                         return errors.Wrap(err, "creating inputs")
234                 }
235
236                 if err = b.AddInput(txInput, sigInst); err != nil {
237                         return errors.Wrap(err, "adding inputs")
238                 }
239         }
240
241         if res.change > 0 {
242                 acp, err := a.accounts.CreateAddress(a.AccountID, true)
243                 if err != nil {
244                         return errors.Wrap(err, "creating control program")
245                 }
246
247                 // Don't insert the control program until callbacks are executed.
248                 a.accounts.insertControlProgramDelayed(b, acp)
249                 if err = b.AddOutput(types.NewIntraChainOutput(*a.AssetId, res.change, acp.ControlProgram)); err != nil {
250                         return errors.Wrap(err, "adding change output")
251                 }
252         }
253         return nil
254 }
255
256 //DecodeSpendUTXOAction unmarshal JSON-encoded data of spend utxo action
257 func (m *Manager) DecodeSpendUTXOAction(data []byte) (txbuilder.Action, error) {
258         a := &spendUTXOAction{accounts: m}
259         return a, stdjson.Unmarshal(data, a)
260 }
261
262 type spendUTXOAction struct {
263         accounts       *Manager
264         OutputID       *bc.Hash                     `json:"output_id"`
265         UseUnconfirmed bool                         `json:"use_unconfirmed"`
266         Arguments      []txbuilder.ContractArgument `json:"arguments"`
267 }
268
269 func (a *spendUTXOAction) ActionType() string {
270         return "spend_account_unspent_output"
271 }
272
273 func (a *spendUTXOAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
274         if a.OutputID == nil {
275                 return txbuilder.MissingFieldsError("output_id")
276         }
277
278         res, err := a.accounts.utxoKeeper.ReserveParticular(*a.OutputID, a.UseUnconfirmed, b.MaxTime())
279         if err != nil {
280                 return err
281         }
282
283         b.OnRollback(func() { a.accounts.utxoKeeper.Cancel(res.id) })
284         var accountSigner *signers.Signer
285         if len(res.utxos[0].AccountID) != 0 {
286                 account, err := a.accounts.FindByID(res.utxos[0].AccountID)
287                 if err != nil {
288                         return err
289                 }
290
291                 accountSigner = account.Signer
292         }
293
294         txInput, sigInst, err := UtxoToInputs(accountSigner, res.utxos[0])
295         if err != nil {
296                 return err
297         }
298
299         if a.Arguments == nil {
300                 return b.AddInput(txInput, sigInst)
301         }
302
303         sigInst = &txbuilder.SigningInstruction{}
304         if err := txbuilder.AddContractArgs(sigInst, a.Arguments); err != nil {
305                 return err
306         }
307
308         return b.AddInput(txInput, sigInst)
309 }
310
311 // UtxoToInputs convert an utxo to the txinput
312 func UtxoToInputs(signer *signers.Signer, u *UTXO) (*types.TxInput, *txbuilder.SigningInstruction, error) {
313         txInput := &types.TxInput{}
314         if u.Vote == nil {
315                 txInput = types.NewSpendInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram)
316         } else {
317                 txInput = types.NewVetoInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram, u.Vote)
318         }
319         sigInst := &txbuilder.SigningInstruction{}
320         if signer == nil {
321                 return txInput, sigInst, nil
322         }
323
324         path, err := signers.Path(signer, signers.AccountKeySpace, u.Change, u.ControlProgramIndex)
325         if err != nil {
326                 return nil, nil, err
327         }
328
329         if u.Address == "" {
330                 sigInst.AddWitnessKeys(signer.XPubs, path, signer.Quorum)
331                 return txInput, sigInst, nil
332         }
333
334         address, err := common.DecodeAddress(u.Address, &consensus.ActiveNetParams)
335         if err != nil {
336                 return nil, nil, err
337         }
338
339         sigInst.AddRawWitnessKeys(signer.XPubs, path, signer.Quorum)
340         derivedXPubs := chainkd.DeriveXPubs(signer.XPubs, path)
341
342         switch address.(type) {
343         case *common.AddressWitnessPubKeyHash:
344                 derivedPK := derivedXPubs[0].PublicKey()
345                 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness([]byte(derivedPK)))
346
347         case *common.AddressWitnessScriptHash:
348                 derivedPKs := chainkd.XPubKeys(derivedXPubs)
349                 script, err := vmutil.P2SPMultiSigProgram(derivedPKs, signer.Quorum)
350                 if err != nil {
351                         return nil, nil, err
352                 }
353                 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness(script))
354
355         default:
356                 return nil, nil, errors.New("unsupport address type")
357         }
358
359         return txInput, sigInst, nil
360 }
361
362 // insertControlProgramDelayed takes a template builder and an account
363 // control program that hasn't been inserted to the database yet. It
364 // registers callbacks on the TemplateBuilder so that all of the template's
365 // account control programs are batch inserted if building the rest of
366 // the template is successful.
367 func (m *Manager) insertControlProgramDelayed(b *txbuilder.TemplateBuilder, acp *CtrlProgram) {
368         m.delayedACPsMu.Lock()
369         m.delayedACPs[b] = append(m.delayedACPs[b], acp)
370         m.delayedACPsMu.Unlock()
371
372         b.OnRollback(func() {
373                 m.delayedACPsMu.Lock()
374                 delete(m.delayedACPs, b)
375                 m.delayedACPsMu.Unlock()
376         })
377         b.OnBuild(func() error {
378                 m.delayedACPsMu.Lock()
379                 acps := m.delayedACPs[b]
380                 delete(m.delayedACPs, b)
381                 m.delayedACPsMu.Unlock()
382
383                 // Insert all of the account control programs at once.
384                 if len(acps) == 0 {
385                         return nil
386                 }
387
388                 return m.SaveControlPrograms(acps...)
389         })
390 }
391
392 //DecodeVetoAction unmarshal JSON-encoded data of spend action
393 func (m *Manager) DecodeVetoAction(data []byte) (txbuilder.Action, error) {
394         a := &vetoAction{accounts: m}
395         return a, stdjson.Unmarshal(data, a)
396 }
397
398 type vetoAction struct {
399         accounts *Manager
400         bc.AssetAmount
401         AccountID      string        `json:"account_id"`
402         Vote           json.HexBytes `json:"vote"`
403         UseUnconfirmed bool          `json:"use_unconfirmed"`
404 }
405
406 func (a *vetoAction) ActionType() string {
407         return "veto"
408 }
409
410 func (a *vetoAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
411         var missing []string
412         if a.AccountID == "" {
413                 missing = append(missing, "account_id")
414         }
415         if a.AssetId.IsZero() {
416                 missing = append(missing, "asset_id")
417         }
418         if len(missing) > 0 {
419                 return txbuilder.MissingFieldsError(missing...)
420         }
421
422         acct, err := a.accounts.FindByID(a.AccountID)
423         if err != nil {
424                 return errors.Wrap(err, "get account info")
425         }
426
427         res, err := a.accounts.utxoKeeper.Reserve(a.AccountID, a.AssetId, a.Amount, a.UseUnconfirmed, a.Vote, b.MaxTime())
428         if err != nil {
429                 return errors.Wrap(err, "reserving utxos")
430         }
431
432         // Cancel the reservation if the build gets rolled back.
433         b.OnRollback(func() { a.accounts.utxoKeeper.Cancel(res.id) })
434         for _, r := range res.utxos {
435                 txInput, sigInst, err := UtxoToInputs(acct.Signer, r)
436                 if err != nil {
437                         return errors.Wrap(err, "creating inputs")
438                 }
439
440                 if err = b.AddInput(txInput, sigInst); err != nil {
441                         return errors.Wrap(err, "adding inputs")
442                 }
443         }
444
445         if res.change > 0 {
446                 acp, err := a.accounts.CreateAddress(a.AccountID, true)
447                 if err != nil {
448                         return errors.Wrap(err, "creating control program")
449                 }
450
451                 // Don't insert the control program until callbacks are executed.
452                 a.accounts.insertControlProgramDelayed(b, acp)
453                 if err = b.AddOutput(types.NewVoteOutput(*a.AssetId, res.change, acp.ControlProgram, a.Vote)); err != nil {
454                         return errors.Wrap(err, "adding change voteOutput")
455                 }
456         }
457         return nil
458 }