OSDN Git Service

delete some comments
[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/csp"
12         edchainkd "github.com/vapor/crypto/ed25519/chainkd"
13         "github.com/vapor/encoding/json"
14         "github.com/vapor/errors"
15         "github.com/vapor/protocol/bc"
16         "github.com/vapor/protocol/bc/types"
17         "github.com/vapor/protocol/vm/vmutil"
18 )
19
20 var (
21         //chainTxUtxoNum maximum utxo quantity in a tx
22         chainTxUtxoNum = 5
23         //chainTxMergeGas chain tx gas
24         chainTxMergeGas = uint64(10000000)
25 )
26
27 //DecodeSpendAction unmarshal JSON-encoded data of spend action
28 func (m *Manager) DecodeSpendAction(data []byte) (txbuilder.Action, error) {
29         a := &spendAction{accounts: m}
30         return a, stdjson.Unmarshal(data, a)
31 }
32
33 type spendAction struct {
34         accounts *Manager
35         bc.AssetAmount
36         AccountID      string `json:"account_id"`
37         UseUnconfirmed bool   `json:"use_unconfirmed"`
38 }
39
40 func (a *spendAction) ActionType() string {
41         return "spend_account"
42 }
43
44 // MergeSpendAction merge common assetID and accountID spend action
45 func MergeSpendAction(actions []txbuilder.Action) []txbuilder.Action {
46         resultActions := []txbuilder.Action{}
47         spendActionMap := make(map[string]*spendAction)
48
49         for _, act := range actions {
50                 switch act := act.(type) {
51                 case *spendAction:
52                         actionKey := act.AssetId.String() + act.AccountID
53                         if tmpAct, ok := spendActionMap[actionKey]; ok {
54                                 tmpAct.Amount += act.Amount
55                                 tmpAct.UseUnconfirmed = tmpAct.UseUnconfirmed || act.UseUnconfirmed
56                         } else {
57                                 spendActionMap[actionKey] = act
58                                 resultActions = append(resultActions, act)
59                         }
60                 default:
61                         resultActions = append(resultActions, act)
62                 }
63         }
64         return resultActions
65 }
66
67 //calcMergeGas calculate the gas required that n utxos are merged into one
68 func calcMergeGas(num int) uint64 {
69         gas := uint64(0)
70         for num > 1 {
71                 gas += chainTxMergeGas
72                 num -= chainTxUtxoNum - 1
73         }
74         return gas
75 }
76
77 func (m *Manager) reserveBtmUtxoChain(builder *txbuilder.TemplateBuilder, accountID string, amount uint64, useUnconfirmed bool) ([]*UTXO, error) {
78         reservedAmount := uint64(0)
79         utxos := []*UTXO{}
80         for gasAmount := uint64(0); reservedAmount < gasAmount+amount; gasAmount = calcMergeGas(len(utxos)) {
81                 reserveAmount := amount + gasAmount - reservedAmount
82                 res, err := m.utxoKeeper.Reserve(accountID, consensus.BTMAssetID, reserveAmount, useUnconfirmed, nil, builder.MaxTime())
83                 if err != nil {
84                         return nil, err
85                 }
86
87                 builder.OnRollback(func() { m.utxoKeeper.Cancel(res.id) })
88                 reservedAmount += reserveAmount + res.change
89                 utxos = append(utxos, res.utxos[:]...)
90         }
91         return utxos, nil
92 }
93
94 func (m *Manager) buildBtmTxChain(utxos []*UTXO, signer *signers.Signer) ([]*txbuilder.Template, *UTXO, error) {
95         if len(utxos) == 0 {
96                 return nil, nil, errors.New("mergeSpendActionUTXO utxos num 0")
97         }
98
99         tpls := []*txbuilder.Template{}
100         if len(utxos) == 1 {
101                 return tpls, utxos[len(utxos)-1], nil
102         }
103
104         acp, err := m.GetLocalCtrlProgramByAddress(utxos[0].Address)
105         if err != nil {
106                 return nil, nil, err
107         }
108
109         buildAmount := uint64(0)
110         builder := &txbuilder.TemplateBuilder{}
111         for index := 0; index < len(utxos); index++ {
112                 input, sigInst, err := UtxoToInputs(signer, utxos[index])
113                 if err != nil {
114                         return nil, nil, err
115                 }
116
117                 if err = builder.AddInput(input, sigInst); err != nil {
118                         return nil, nil, err
119                 }
120
121                 buildAmount += input.Amount()
122                 if builder.InputCount() != chainTxUtxoNum && index != len(utxos)-1 {
123                         continue
124                 }
125
126                 outAmount := buildAmount - chainTxMergeGas
127                 output := types.NewIntraChainOutput(*consensus.BTMAssetID, outAmount, acp.ControlProgram)
128                 if err := builder.AddOutput(output); err != nil {
129                         return nil, nil, err
130                 }
131
132                 tpl, _, err := builder.Build()
133                 if err != nil {
134                         return nil, nil, err
135                 }
136
137                 bcOut, err := tpl.Transaction.IntraChainOutput(*tpl.Transaction.ResultIds[0])
138                 if err != nil {
139                         return nil, nil, err
140                 }
141
142                 utxos = append(utxos, &UTXO{
143                         OutputID:            *tpl.Transaction.ResultIds[0],
144                         AssetID:             *consensus.BTMAssetID,
145                         Amount:              outAmount,
146                         ControlProgram:      acp.ControlProgram,
147                         SourceID:            *bcOut.Source.Ref,
148                         SourcePos:           bcOut.Source.Position,
149                         ControlProgramIndex: acp.KeyIndex,
150                         Address:             acp.Address,
151                         Change:              acp.Change,
152                 })
153
154                 tpls = append(tpls, tpl)
155                 buildAmount = 0
156                 builder = &txbuilder.TemplateBuilder{}
157                 if index == len(utxos)-2 {
158                         break
159                 }
160         }
161         return tpls, utxos[len(utxos)-1], nil
162 }
163
164 // SpendAccountChain build the spend action with auto merge utxo function
165 func SpendAccountChain(ctx context.Context, builder *txbuilder.TemplateBuilder, action txbuilder.Action) ([]*txbuilder.Template, error) {
166         act, ok := action.(*spendAction)
167         if !ok {
168                 return nil, errors.New("fail to convert the spend action")
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.NewSpendInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram)
314         sigInst := &txbuilder.SigningInstruction{}
315         if signer == nil {
316                 return txInput, sigInst, nil
317         }
318
319         path, err := signers.Path(signer, signers.AccountKeySpace, u.Change, u.ControlProgramIndex)
320         if err != nil {
321                 return nil, nil, err
322         }
323         if u.Address == "" {
324                 sigInst.AddWitnessKeys(signer.XPubs, path, signer.Quorum)
325                 return txInput, sigInst, nil
326         }
327
328         address, err := common.DecodeAddress(u.Address, &consensus.ActiveNetParams)
329         if err != nil {
330                 return nil, nil, err
331         }
332         sigInst.AddRawWitnessKeys(signer.XPubs, path, signer.Quorum)
333         derivedXPubs := csp.DeriveXPubs(signer.XPubs, path)
334
335         if len(derivedXPubs) == 0 {
336                 panic("UtxoToInputs derivedXPubs is nil.")
337         }
338
339         switch address.(type) {
340         case *common.AddressWitnessPubKeyHash:
341                 switch dxpub := derivedXPubs[0].(type) {
342                 case edchainkd.XPub:
343                         derivedPK := dxpub.PublicKey()
344                         sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness([]byte(derivedPK)))
345                 }
346
347         case *common.AddressWitnessScriptHash:
348                 derivedPKs := csp.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                 return m.SaveControlPrograms(acps...)
388         })
389 }
390
391 //DecodeUnvoteAction unmarshal JSON-encoded data of spend action
392 func (m *Manager) DecodeUnvoteAction(data []byte) (txbuilder.Action, error) {
393         a := &unvoteAction{accounts: m}
394         return a, stdjson.Unmarshal(data, a)
395 }
396
397 type unvoteAction struct {
398         accounts *Manager
399         bc.AssetAmount
400         AccountID      string        `json:"account_id"`
401         Vote           json.HexBytes `json:"vote"`
402         UseUnconfirmed bool          `json:"use_unconfirmed"`
403 }
404
405 func (a *unvoteAction) ActionType() string {
406         return "unvote"
407 }
408
409 func (a *unvoteAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
410         var missing []string
411         if a.AccountID == "" {
412                 missing = append(missing, "account_id")
413         }
414         if a.AssetId.IsZero() {
415                 missing = append(missing, "asset_id")
416         }
417         if len(missing) > 0 {
418                 return txbuilder.MissingFieldsError(missing...)
419         }
420
421         acct, err := a.accounts.FindByID(a.AccountID)
422         if err != nil {
423                 return errors.Wrap(err, "get account info")
424         }
425
426         res, err := a.accounts.utxoKeeper.Reserve(a.AccountID, a.AssetId, a.Amount, a.UseUnconfirmed, a.Vote, b.MaxTime())
427         if err != nil {
428                 return errors.Wrap(err, "reserving utxos")
429         }
430
431         // Cancel the reservation if the build gets rolled back.
432         b.OnRollback(func() { a.accounts.utxoKeeper.Cancel(res.id) })
433         for _, r := range res.utxos {
434                 txInput, sigInst, err := UtxoToInputs(acct.Signer, r)
435                 if err != nil {
436                         return errors.Wrap(err, "creating inputs")
437                 }
438
439                 if err = b.AddInput(txInput, sigInst); err != nil {
440                         return errors.Wrap(err, "adding inputs")
441                 }
442         }
443
444         if res.change > 0 {
445                 acp, err := a.accounts.CreateAddress(a.AccountID, true)
446                 if err != nil {
447                         return errors.Wrap(err, "creating control program")
448                 }
449
450                 // Don't insert the control program until callbacks are executed.
451                 a.accounts.insertControlProgramDelayed(b, acp)
452                 if err = b.AddOutput(types.NewVoteOutput(*a.AssetId, res.change, acp.ControlProgram, a.Vote)); err != nil {
453                         return errors.Wrap(err, "adding change voteOutput")
454                 }
455         }
456         return nil
457 }