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/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"
21 //chainTxUtxoNum maximum utxo quantity in a tx
23 //chainTxMergeGas chain tx gas
24 chainTxMergeGas = uint64(10000000)
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)
33 type spendAction struct {
36 AccountID string `json:"account_id"`
37 UseUnconfirmed bool `json:"use_unconfirmed"`
40 func (a *spendAction) ActionType() string {
41 return "spend_account"
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)
49 for _, act := range actions {
50 switch act := act.(type) {
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
57 spendActionMap[actionKey] = act
58 resultActions = append(resultActions, act)
61 resultActions = append(resultActions, act)
67 //calcMergeGas calculate the gas required that n utxos are merged into one
68 func calcMergeGas(num int) uint64 {
71 gas += chainTxMergeGas
72 num -= chainTxUtxoNum - 1
77 func (m *Manager) reserveBtmUtxoChain(builder *txbuilder.TemplateBuilder, accountID string, amount uint64, useUnconfirmed bool) ([]*UTXO, error) {
78 reservedAmount := uint64(0)
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())
87 builder.OnRollback(func() { m.utxoKeeper.Cancel(res.id) })
88 reservedAmount += reserveAmount + res.change
89 utxos = append(utxos, res.utxos[:]...)
94 func (m *Manager) buildBtmTxChain(utxos []*UTXO, signer *signers.Signer) ([]*txbuilder.Template, *UTXO, error) {
96 return nil, nil, errors.New("mergeSpendActionUTXO utxos num 0")
99 tpls := []*txbuilder.Template{}
101 return tpls, utxos[len(utxos)-1], nil
104 acp, err := m.GetLocalCtrlProgramByAddress(utxos[0].Address)
109 buildAmount := uint64(0)
110 builder := &txbuilder.TemplateBuilder{}
111 for index := 0; index < len(utxos); index++ {
112 input, sigInst, err := UtxoToInputs(signer, utxos[index])
117 if err = builder.AddInput(input, sigInst); err != nil {
121 buildAmount += input.Amount()
122 if builder.InputCount() != chainTxUtxoNum && index != len(utxos)-1 {
126 outAmount := buildAmount - chainTxMergeGas
127 output := types.NewIntraChainOutput(*consensus.BTMAssetID, outAmount, acp.ControlProgram)
128 if err := builder.AddOutput(output); err != nil {
132 tpl, _, err := builder.Build()
137 bcOut, err := tpl.Transaction.IntraChainOutput(*tpl.Transaction.ResultIds[0])
142 utxos = append(utxos, &UTXO{
143 OutputID: *tpl.Transaction.ResultIds[0],
144 AssetID: *consensus.BTMAssetID,
146 ControlProgram: acp.ControlProgram,
147 SourceID: *bcOut.Source.Ref,
148 SourcePos: bcOut.Source.Position,
149 ControlProgramIndex: acp.KeyIndex,
150 Address: acp.Address,
154 tpls = append(tpls, tpl)
156 builder = &txbuilder.TemplateBuilder{}
157 if index == len(utxos)-2 {
161 return tpls, utxos[len(utxos)-1], nil
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)
168 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.NewSpendInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram)
314 sigInst := &txbuilder.SigningInstruction{}
316 return txInput, sigInst, nil
319 path, err := signers.Path(signer, signers.AccountKeySpace, u.Change, u.ControlProgramIndex)
324 sigInst.AddWitnessKeys(signer.XPubs, path, signer.Quorum)
325 return txInput, sigInst, nil
328 address, err := common.DecodeAddress(u.Address, &consensus.ActiveNetParams)
332 sigInst.AddRawWitnessKeys(signer.XPubs, path, signer.Quorum)
333 derivedXPubs := csp.DeriveXPubs(signer.XPubs, path)
335 if len(derivedXPubs) == 0 {
336 panic("UtxoToInputs derivedXPubs is nil.")
339 switch address.(type) {
340 case *common.AddressWitnessPubKeyHash:
341 switch dxpub := derivedXPubs[0].(type) {
343 derivedPK := dxpub.PublicKey()
344 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness([]byte(derivedPK)))
347 case *common.AddressWitnessScriptHash:
348 derivedPKs := csp.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.
387 return m.SaveControlPrograms(acps...)
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)
397 type unvoteAction struct {
400 AccountID string `json:"account_id"`
401 Vote json.HexBytes `json:"vote"`
402 UseUnconfirmed bool `json:"use_unconfirmed"`
405 func (a *unvoteAction) ActionType() string {
409 func (a *unvoteAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
411 if a.AccountID == "" {
412 missing = append(missing, "account_id")
414 if a.AssetId.IsZero() {
415 missing = append(missing, "asset_id")
417 if len(missing) > 0 {
418 return txbuilder.MissingFieldsError(missing...)
421 acct, err := a.accounts.FindByID(a.AccountID)
423 return errors.Wrap(err, "get account info")
426 res, err := a.accounts.utxoKeeper.Reserve(a.AccountID, a.AssetId, a.Amount, a.UseUnconfirmed, a.Vote, b.MaxTime())
428 return errors.Wrap(err, "reserving utxos")
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)
436 return errors.Wrap(err, "creating inputs")
439 if err = b.AddInput(txInput, sigInst); err != nil {
440 return errors.Wrap(err, "adding inputs")
445 acp, err := a.accounts.CreateAddress(a.AccountID, true)
447 return errors.Wrap(err, "creating control program")
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")