OSDN Git Service

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