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/errors"
13 "github.com/vapor/protocol/bc"
14 "github.com/vapor/protocol/bc/types"
15 "github.com/vapor/protocol/vm/vmutil"
19 //chainTxUtxoNum maximum utxo quantity in a tx
21 //chainTxMergeGas chain tx gas
22 chainTxMergeGas = uint64(10000000)
25 //DecodeSpendAction unmarshal JSON-encoded data of spend action
26 func (m *Manager) DecodeSpendAction(data []byte) (txbuilder.Action, error) {
27 a := &spendAction{accounts: m}
28 return a, json.Unmarshal(data, a)
31 type spendAction struct {
34 AccountID string `json:"account_id"`
35 UseUnconfirmed bool `json:"use_unconfirmed"`
38 func (a *spendAction) ActionType() string {
39 return "spend_account"
42 // MergeSpendAction merge common assetID and accountID spend action
43 func MergeSpendAction(actions []txbuilder.Action) []txbuilder.Action {
44 resultActions := []txbuilder.Action{}
45 spendActionMap := make(map[string]*spendAction)
47 for _, act := range actions {
48 switch act := act.(type) {
50 actionKey := act.AssetId.String() + act.AccountID
51 if tmpAct, ok := spendActionMap[actionKey]; ok {
52 tmpAct.Amount += act.Amount
53 tmpAct.UseUnconfirmed = tmpAct.UseUnconfirmed || act.UseUnconfirmed
55 spendActionMap[actionKey] = act
56 resultActions = append(resultActions, act)
59 resultActions = append(resultActions, act)
65 //calcMergeGas calculate the gas required that n utxos are merged into one
66 func calcMergeGas(num int) uint64 {
69 gas += chainTxMergeGas
70 num -= chainTxUtxoNum - 1
75 func (m *Manager) reserveBtmUtxoChain(builder *txbuilder.TemplateBuilder, accountID string, amount uint64, useUnconfirmed bool) ([]*UTXO, error) {
76 reservedAmount := uint64(0)
78 for gasAmount := uint64(0); reservedAmount < gasAmount+amount; gasAmount = calcMergeGas(len(utxos)) {
79 reserveAmount := amount + gasAmount - reservedAmount
80 res, err := m.utxoKeeper.Reserve(accountID, consensus.BTMAssetID, reserveAmount, useUnconfirmed, builder.MaxTime())
85 builder.OnRollback(func() { m.utxoKeeper.Cancel(res.id) })
86 reservedAmount += reserveAmount + res.change
87 utxos = append(utxos, res.utxos[:]...)
92 func (m *Manager) buildBtmTxChain(utxos []*UTXO, signer *signers.Signer) ([]*txbuilder.Template, *UTXO, error) {
94 return nil, nil, errors.New("mergeSpendActionUTXO utxos num 0")
97 tpls := []*txbuilder.Template{}
99 return tpls, utxos[len(utxos)-1], nil
102 acp, err := m.GetLocalCtrlProgramByAddress(utxos[0].Address)
107 buildAmount := uint64(0)
108 builder := &txbuilder.TemplateBuilder{}
109 for index := 0; index < len(utxos); index++ {
110 input, sigInst, err := UtxoToInputs(signer, utxos[index])
115 if err = builder.AddInput(input, sigInst); err != nil {
119 buildAmount += input.Amount()
120 if builder.InputCount() != chainTxUtxoNum && index != len(utxos)-1 {
124 outAmount := buildAmount - chainTxMergeGas
125 output := types.NewTxOutput(*consensus.BTMAssetID, outAmount, acp.ControlProgram)
126 if err := builder.AddOutput(output); err != nil {
130 tpl, _, err := builder.Build()
135 bcOut, err := tpl.Transaction.Output(*tpl.Transaction.ResultIds[0])
140 utxos = append(utxos, &UTXO{
141 OutputID: *tpl.Transaction.ResultIds[0],
142 AssetID: *consensus.BTMAssetID,
144 ControlProgram: acp.ControlProgram,
145 SourceID: *bcOut.Source.Ref,
146 SourcePos: bcOut.Source.Position,
147 ControlProgramIndex: acp.KeyIndex,
148 Address: acp.Address,
152 tpls = append(tpls, tpl)
154 builder = &txbuilder.TemplateBuilder{}
155 if index == len(utxos)-2 {
159 return tpls, utxos[len(utxos)-1], nil
162 // SpendAccountChain build the spend action with auto merge utxo function
163 func SpendAccountChain(ctx context.Context, builder *txbuilder.TemplateBuilder, action txbuilder.Action) ([]*txbuilder.Template, error) {
164 act, ok := action.(*spendAction)
166 return nil, errors.New("fail to convert the spend action")
168 if *act.AssetId != *consensus.BTMAssetID {
169 return nil, errors.New("spend chain action only support BTM")
172 utxos, err := act.accounts.reserveBtmUtxoChain(builder, act.AccountID, act.Amount, act.UseUnconfirmed)
177 acct, err := act.accounts.FindByID(act.AccountID)
182 tpls, utxo, err := act.accounts.buildBtmTxChain(utxos, acct.Signer)
187 input, sigInst, err := UtxoToInputs(acct.Signer, utxo)
192 if err := builder.AddInput(input, sigInst); err != nil {
196 if utxo.Amount > act.Amount {
197 if err = builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, utxo.Amount-act.Amount, utxo.ControlProgram)); err != nil {
198 return nil, errors.Wrap(err, "adding change output")
204 func (a *spendAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
206 if a.AccountID == "" {
207 missing = append(missing, "account_id")
209 if a.AssetId.IsZero() {
210 missing = append(missing, "asset_id")
212 if len(missing) > 0 {
213 return txbuilder.MissingFieldsError(missing...)
216 acct, err := a.accounts.FindByID(a.AccountID)
218 return errors.Wrap(err, "get account info")
221 res, err := a.accounts.utxoKeeper.Reserve(a.AccountID, a.AssetId, a.Amount, a.UseUnconfirmed, b.MaxTime())
223 return errors.Wrap(err, "reserving utxos")
226 // Cancel the reservation if the build gets rolled back.
227 b.OnRollback(func() { a.accounts.utxoKeeper.Cancel(res.id) })
228 for _, r := range res.utxos {
229 txInput, sigInst, err := UtxoToInputs(acct.Signer, r)
231 return errors.Wrap(err, "creating inputs")
234 if err = b.AddInput(txInput, sigInst); err != nil {
235 return errors.Wrap(err, "adding inputs")
240 acp, err := a.accounts.CreateAddress(a.AccountID, true)
242 return errors.Wrap(err, "creating control program")
245 // Don't insert the control program until callbacks are executed.
246 a.accounts.insertControlProgramDelayed(b, acp)
247 if err = b.AddOutput(types.NewTxOutput(*a.AssetId, res.change, acp.ControlProgram)); err != nil {
248 return errors.Wrap(err, "adding change output")
254 //DecodeSpendUTXOAction unmarshal JSON-encoded data of spend utxo action
255 func (m *Manager) DecodeSpendUTXOAction(data []byte) (txbuilder.Action, error) {
256 a := &spendUTXOAction{accounts: m}
257 return a, json.Unmarshal(data, a)
260 type spendUTXOAction struct {
262 OutputID *bc.Hash `json:"output_id"`
263 UseUnconfirmed bool `json:"use_unconfirmed"`
264 Arguments []txbuilder.ContractArgument `json:"arguments"`
267 func (a *spendUTXOAction) ActionType() string {
268 return "spend_account_unspent_output"
271 func (a *spendUTXOAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
272 if a.OutputID == nil {
273 return txbuilder.MissingFieldsError("output_id")
276 res, err := a.accounts.utxoKeeper.ReserveParticular(*a.OutputID, a.UseUnconfirmed, b.MaxTime())
281 b.OnRollback(func() { a.accounts.utxoKeeper.Cancel(res.id) })
282 var accountSigner *signers.Signer
283 if len(res.utxos[0].AccountID) != 0 {
284 account, err := a.accounts.FindByID(res.utxos[0].AccountID)
289 accountSigner = account.Signer
292 txInput, sigInst, err := UtxoToInputs(accountSigner, res.utxos[0])
297 if a.Arguments == nil {
298 return b.AddInput(txInput, sigInst)
301 sigInst = &txbuilder.SigningInstruction{}
302 if err := txbuilder.AddContractArgs(sigInst, a.Arguments); err != nil {
306 return b.AddInput(txInput, sigInst)
309 // UtxoToInputs convert an utxo to the txinput
310 func UtxoToInputs(signer *signers.Signer, u *UTXO) (*types.TxInput, *txbuilder.SigningInstruction, error) {
311 txInput := types.NewSpendInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram)
312 sigInst := &txbuilder.SigningInstruction{}
314 return txInput, sigInst, nil
317 path, err := signers.Path(signer, signers.AccountKeySpace, u.Change, u.ControlProgramIndex)
322 sigInst.AddWitnessKeys(signer.XPubs, path, signer.Quorum)
323 return txInput, sigInst, nil
326 address, err := common.DecodeAddress(u.Address, &consensus.ActiveNetParams)
331 sigInst.AddRawWitnessKeys(signer.XPubs, path, signer.Quorum)
332 derivedXPubs := chainkd.DeriveXPubs(signer.XPubs, path)
334 switch address.(type) {
335 case *common.AddressWitnessPubKeyHash:
336 derivedPK := derivedXPubs[0].PublicKey()
337 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness([]byte(derivedPK)))
339 case *common.AddressWitnessScriptHash:
340 derivedPKs := chainkd.XPubKeys(derivedXPubs)
341 script, err := vmutil.P2SPMultiSigProgram(derivedPKs, signer.Quorum)
345 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness(script))
348 return nil, nil, errors.New("unsupport address type")
351 return txInput, sigInst, nil
354 // insertControlProgramDelayed takes a template builder and an account
355 // control program that hasn't been inserted to the database yet. It
356 // registers callbacks on the TemplateBuilder so that all of the template's
357 // account control programs are batch inserted if building the rest of
358 // the template is successful.
359 func (m *Manager) insertControlProgramDelayed(b *txbuilder.TemplateBuilder, acp *CtrlProgram) {
360 m.delayedACPsMu.Lock()
361 m.delayedACPs[b] = append(m.delayedACPs[b], acp)
362 m.delayedACPsMu.Unlock()
364 b.OnRollback(func() {
365 m.delayedACPsMu.Lock()
366 delete(m.delayedACPs, b)
367 m.delayedACPsMu.Unlock()
369 b.OnBuild(func() error {
370 m.delayedACPsMu.Lock()
371 acps := m.delayedACPs[b]
372 delete(m.delayedACPs, b)
373 m.delayedACPsMu.Unlock()
375 // Insert all of the account control programs at once.
379 return m.SaveControlPrograms(acps...)