5 stdjson "encoding/json"
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"
20 //chainTxUtxoNum maximum utxo quantity in a tx
22 //chainTxMergeGas chain tx gas
23 chainTxMergeGas = uint64(10000000)
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)
32 type spendAction struct {
35 AccountID string `json:"account_id"`
36 UseUnconfirmed bool `json:"use_unconfirmed"`
39 func (a *spendAction) ActionType() string {
40 return "spend_account"
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)
48 for _, act := range actions {
49 switch act := act.(type) {
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
56 spendActionMap[actionKey] = act
57 resultActions = append(resultActions, act)
60 resultActions = append(resultActions, act)
66 //calcMergeGas calculate the gas required that n utxos are merged into one
67 func calcMergeGas(num int) uint64 {
70 gas += chainTxMergeGas
71 num -= chainTxUtxoNum - 1
76 func (m *Manager) reserveBtmUtxoChain(builder *txbuilder.TemplateBuilder, accountID string, amount uint64, useUnconfirmed bool) ([]*UTXO, error) {
77 reservedAmount := uint64(0)
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())
86 builder.OnRollback(func() { m.utxoKeeper.Cancel(res.id) })
87 reservedAmount += reserveAmount + res.change
88 utxos = append(utxos, res.utxos[:]...)
93 func (m *Manager) BuildBtmTxChain(utxos []*UTXO, signer *signers.Signer) ([]*txbuilder.Template, *UTXO, error) {
95 return nil, nil, errors.New("mergeSpendActionUTXO utxos num 0")
98 tpls := []*txbuilder.Template{}
100 return tpls, utxos[len(utxos)-1], nil
103 acp, err := m.GetLocalCtrlProgramByAddress(utxos[0].Address)
108 buildAmount := uint64(0)
109 builder := &txbuilder.TemplateBuilder{}
110 for index := 0; index < len(utxos); index++ {
111 input, sigInst, err := UtxoToInputs(signer, utxos[index])
116 if err = builder.AddInput(input, sigInst); err != nil {
120 buildAmount += input.Amount()
121 if builder.InputCount() != chainTxUtxoNum && index != len(utxos)-1 {
125 outAmount := buildAmount - chainTxMergeGas
126 output := types.NewIntraChainOutput(*consensus.BTMAssetID, outAmount, acp.ControlProgram)
127 if err := builder.AddOutput(output); err != nil {
131 tpl, _, err := builder.Build()
136 bcOut, err := tpl.Transaction.IntraChainOutput(*tpl.Transaction.ResultIds[0])
141 utxos = append(utxos, &UTXO{
142 OutputID: *tpl.Transaction.ResultIds[0],
143 AssetID: *consensus.BTMAssetID,
145 ControlProgram: acp.ControlProgram,
146 SourceID: *bcOut.Source.Ref,
147 SourcePos: bcOut.Source.Position,
148 ControlProgramIndex: acp.KeyIndex,
149 Address: acp.Address,
153 tpls = append(tpls, tpl)
155 builder = &txbuilder.TemplateBuilder{}
156 if index == len(utxos)-2 {
160 return tpls, utxos[len(utxos)-1], nil
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)
167 return nil, errors.New("fail to convert the spend action")
170 if *act.AssetId != *consensus.BTMAssetID {
171 return nil, errors.New("spend chain action only support BTM")
174 utxos, err := act.accounts.reserveBtmUtxoChain(builder, act.AccountID, act.Amount, act.UseUnconfirmed)
179 acct, err := act.accounts.FindByID(act.AccountID)
184 tpls, utxo, err := act.accounts.BuildBtmTxChain(utxos, acct.Signer)
189 input, sigInst, err := UtxoToInputs(acct.Signer, utxo)
194 if err := builder.AddInput(input, sigInst); err != nil {
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")
206 func (a *spendAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
208 if a.AccountID == "" {
209 missing = append(missing, "account_id")
211 if a.AssetId.IsZero() {
212 missing = append(missing, "asset_id")
214 if len(missing) > 0 {
215 return txbuilder.MissingFieldsError(missing...)
218 acct, err := a.accounts.FindByID(a.AccountID)
220 return errors.Wrap(err, "get account info")
223 res, err := a.accounts.utxoKeeper.Reserve(a.AccountID, a.AssetId, a.Amount, a.UseUnconfirmed, nil, b.MaxTime())
225 return errors.Wrap(err, "reserving utxos")
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)
233 return errors.Wrap(err, "creating inputs")
236 if err = b.AddInput(txInput, sigInst); err != nil {
237 return errors.Wrap(err, "adding inputs")
242 acp, err := a.accounts.CreateAddress(a.AccountID, true)
244 return errors.Wrap(err, "creating control program")
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")
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)
262 type spendUTXOAction struct {
264 OutputID *bc.Hash `json:"output_id"`
265 UseUnconfirmed bool `json:"use_unconfirmed"`
266 Arguments []txbuilder.ContractArgument `json:"arguments"`
269 func (a *spendUTXOAction) ActionType() string {
270 return "spend_account_unspent_output"
273 func (a *spendUTXOAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
274 if a.OutputID == nil {
275 return txbuilder.MissingFieldsError("output_id")
278 res, err := a.accounts.utxoKeeper.ReserveParticular(*a.OutputID, a.UseUnconfirmed, b.MaxTime())
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)
291 accountSigner = account.Signer
294 txInput, sigInst, err := UtxoToInputs(accountSigner, res.utxos[0])
299 if a.Arguments == nil {
300 return b.AddInput(txInput, sigInst)
303 sigInst = &txbuilder.SigningInstruction{}
304 if err := txbuilder.AddContractArgs(sigInst, a.Arguments); err != nil {
308 return b.AddInput(txInput, sigInst)
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{}
315 txInput = types.NewSpendInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram)
317 txInput = types.NewVetoInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram, u.Vote)
319 sigInst := &txbuilder.SigningInstruction{}
321 return txInput, sigInst, nil
324 path, err := signers.Path(signer, signers.AccountKeySpace, u.Change, u.ControlProgramIndex)
330 sigInst.AddWitnessKeys(signer.XPubs, path, signer.Quorum)
331 return txInput, sigInst, nil
334 address, err := common.DecodeAddress(u.Address, &consensus.ActiveNetParams)
339 sigInst.AddRawWitnessKeys(signer.XPubs, path, signer.Quorum)
340 derivedXPubs := chainkd.DeriveXPubs(signer.XPubs, path)
342 switch address.(type) {
343 case *common.AddressWitnessPubKeyHash:
344 derivedPK := derivedXPubs[0].PublicKey()
345 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness([]byte(derivedPK)))
347 case *common.AddressWitnessScriptHash:
348 derivedPKs := chainkd.XPubKeys(derivedXPubs)
349 script, err := vmutil.P2SPMultiSigProgram(derivedPKs, signer.Quorum)
353 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness(script))
356 return nil, nil, errors.New("unsupport address type")
359 return txInput, sigInst, nil
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()
372 b.OnRollback(func() {
373 m.delayedACPsMu.Lock()
374 delete(m.delayedACPs, b)
375 m.delayedACPsMu.Unlock()
377 b.OnBuild(func() error {
378 m.delayedACPsMu.Lock()
379 acps := m.delayedACPs[b]
380 delete(m.delayedACPs, b)
381 m.delayedACPsMu.Unlock()
383 // Insert all of the account control programs at once.
388 return m.SaveControlPrograms(acps...)
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)
398 type vetoAction struct {
401 AccountID string `json:"account_id"`
402 Vote json.HexBytes `json:"vote"`
403 UseUnconfirmed bool `json:"use_unconfirmed"`
406 func (a *vetoAction) ActionType() string {
410 func (a *vetoAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
412 if a.AccountID == "" {
413 missing = append(missing, "account_id")
415 if a.AssetId.IsZero() {
416 missing = append(missing, "asset_id")
418 if len(missing) > 0 {
419 return txbuilder.MissingFieldsError(missing...)
422 acct, err := a.accounts.FindByID(a.AccountID)
424 return errors.Wrap(err, "get account info")
427 res, err := a.accounts.utxoKeeper.Reserve(a.AccountID, a.AssetId, a.Amount, a.UseUnconfirmed, a.Vote, b.MaxTime())
429 return errors.Wrap(err, "reserving utxos")
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)
437 return errors.Wrap(err, "creating inputs")
440 if err = b.AddInput(txInput, sigInst); err != nil {
441 return errors.Wrap(err, "adding inputs")
446 acp, err := a.accounts.CreateAddress(a.AccountID, true)
448 return errors.Wrap(err, "creating control program")
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")