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"
23 //chainTxUtxoNum maximum utxo quantity in a tx
25 //chainTxMergeGas chain tx gas
26 chainTxMergeGas = uint64(10000000)
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)
36 type crossInAction struct {
39 SourceID string `json:"source_id"` // AnnotatedUTXO
40 SourcePos uint64 `json:"source_pos"`
41 AssetDefinition map[string]interface{} `json:"asset_definition"`
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"`
60 func (a *crossInAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
62 if a.AssetId.IsZero() {
63 missing = append(missing, "asset_id")
66 missing = append(missing, "amount")
69 return txbuilder.MissingFieldsError(missing...)
72 // Handle asset definition.
73 // Asset issuance's legality is guaranteed by the federation.
74 rawDefinition, err := asset.SerializeAssetDef(a.AssetDefinition)
76 return asset.ErrSerializing
78 if !chainjson.IsValidJSON(rawDefinition) {
79 return errors.New("asset definition is not in valid json format")
81 // TODO: check duplicate
82 if preAsset, _ := a.accounts.assetReg.GetAsset(a.AssetId.String()); preAsset != nil {
83 preRawDefinition, _ := asset.SerializeAssetDef(a.AssetDefinition)
85 return asset.ErrSerializing
88 if !testutil.DeepEqual(preRawDefinition, rawDefinition) {
89 return errors.New("asset definition mismatch with previous definition")
93 // txin := types.NewIssuanceInput(nonce[:], a.Amount, asset.IssuanceProgram, nil, asset.RawDefinitionByte)
94 // tplIn := &txbuilder.SigningInstruction{}
95 // if asset.Signer != nil {
96 // path := signers.GetBip0032Path(asset.Signer, signers.AssetKeySpace)
97 // tplIn.AddRawWitnessKeys(asset.Signer.XPubs, path, asset.Signer.Quorum)
98 // } else if a.Arguments != nil {
99 // if err := txbuilder.AddContractArgs(tplIn, a.Arguments); err != nil {
104 // log.Info("Issue action build")
105 // builder.RestrictMinTime(time.Now())
106 // return builder.AddInput(txin, tplIn)
108 // in := types.NewCrossChainInput(arguments [][]byte, sourceID bc.Hash, assetID bc.AssetID, amount, sourcePos uint64, controlProgram, assetDefinition []byte)
109 sourceID := testutil.MustDecodeHash(a.SourceID)
110 in := types.NewCrossChainInput(nil, sourceID, *a.AssetId, a.Amount, a.SourcePos, nil, rawDefinition)
111 return b.AddInput(in, nil)
114 func (a *crossInAction) ActionType() string {
115 return "cross_chain_in"
118 //DecodeSpendAction unmarshal JSON-encoded data of spend action
119 func (m *Manager) DecodeSpendAction(data []byte) (txbuilder.Action, error) {
120 a := &spendAction{accounts: m}
121 return a, json.Unmarshal(data, a)
124 type spendAction struct {
127 AccountID string `json:"account_id"`
128 UseUnconfirmed bool `json:"use_unconfirmed"`
131 func (a *spendAction) ActionType() string {
132 return "spend_account"
135 // MergeSpendAction merge common assetID and accountID spend action
136 func MergeSpendAction(actions []txbuilder.Action) []txbuilder.Action {
137 resultActions := []txbuilder.Action{}
138 spendActionMap := make(map[string]*spendAction)
140 for _, act := range actions {
141 switch act := act.(type) {
143 actionKey := act.AssetId.String() + act.AccountID
144 if tmpAct, ok := spendActionMap[actionKey]; ok {
145 tmpAct.Amount += act.Amount
146 tmpAct.UseUnconfirmed = tmpAct.UseUnconfirmed || act.UseUnconfirmed
148 spendActionMap[actionKey] = act
149 resultActions = append(resultActions, act)
152 resultActions = append(resultActions, act)
158 //calcMergeGas calculate the gas required that n utxos are merged into one
159 func calcMergeGas(num int) uint64 {
162 gas += chainTxMergeGas
163 num -= chainTxUtxoNum - 1
168 func (m *Manager) reserveBtmUtxoChain(builder *txbuilder.TemplateBuilder, accountID string, amount uint64, useUnconfirmed bool) ([]*UTXO, error) {
169 reservedAmount := uint64(0)
171 for gasAmount := uint64(0); reservedAmount < gasAmount+amount; gasAmount = calcMergeGas(len(utxos)) {
172 reserveAmount := amount + gasAmount - reservedAmount
173 res, err := m.utxoKeeper.Reserve(accountID, consensus.BTMAssetID, reserveAmount, useUnconfirmed, builder.MaxTime())
178 builder.OnRollback(func() { m.utxoKeeper.Cancel(res.id) })
179 reservedAmount += reserveAmount + res.change
180 utxos = append(utxos, res.utxos[:]...)
185 func (m *Manager) buildBtmTxChain(utxos []*UTXO, signer *signers.Signer) ([]*txbuilder.Template, *UTXO, error) {
187 return nil, nil, errors.New("mergeSpendActionUTXO utxos num 0")
190 tpls := []*txbuilder.Template{}
192 return tpls, utxos[len(utxos)-1], nil
195 acp, err := m.GetLocalCtrlProgramByAddress(utxos[0].Address)
200 buildAmount := uint64(0)
201 builder := &txbuilder.TemplateBuilder{}
202 for index := 0; index < len(utxos); index++ {
203 input, sigInst, err := UtxoToInputs(signer, utxos[index])
208 if err = builder.AddInput(input, sigInst); err != nil {
212 buildAmount += input.Amount()
213 if builder.InputCount() != chainTxUtxoNum && index != len(utxos)-1 {
217 outAmount := buildAmount - chainTxMergeGas
218 output := types.NewIntraChainOutput(*consensus.BTMAssetID, outAmount, acp.ControlProgram)
219 if err := builder.AddOutput(output); err != nil {
223 tpl, _, err := builder.Build()
228 bcOut, err := tpl.Transaction.IntraChainOutput(*tpl.Transaction.ResultIds[0])
233 utxos = append(utxos, &UTXO{
234 OutputID: *tpl.Transaction.ResultIds[0],
235 AssetID: *consensus.BTMAssetID,
237 ControlProgram: acp.ControlProgram,
238 SourceID: *bcOut.Source.Ref,
239 SourcePos: bcOut.Source.Position,
240 ControlProgramIndex: acp.KeyIndex,
241 Address: acp.Address,
245 tpls = append(tpls, tpl)
247 builder = &txbuilder.TemplateBuilder{}
248 if index == len(utxos)-2 {
252 return tpls, utxos[len(utxos)-1], nil
255 // SpendAccountChain build the spend action with auto merge utxo function
256 func SpendAccountChain(ctx context.Context, builder *txbuilder.TemplateBuilder, action txbuilder.Action) ([]*txbuilder.Template, error) {
257 act, ok := action.(*spendAction)
259 return nil, errors.New("fail to convert the spend action")
261 if *act.AssetId != *consensus.BTMAssetID {
262 return nil, errors.New("spend chain action only support BTM")
265 utxos, err := act.accounts.reserveBtmUtxoChain(builder, act.AccountID, act.Amount, act.UseUnconfirmed)
270 acct, err := act.accounts.FindByID(act.AccountID)
275 tpls, utxo, err := act.accounts.buildBtmTxChain(utxos, acct.Signer)
280 input, sigInst, err := UtxoToInputs(acct.Signer, utxo)
285 if err := builder.AddInput(input, sigInst); err != nil {
289 if utxo.Amount > act.Amount {
290 if err = builder.AddOutput(types.NewIntraChainOutput(*consensus.BTMAssetID, utxo.Amount-act.Amount, utxo.ControlProgram)); err != nil {
291 return nil, errors.Wrap(err, "adding change output")
297 func (a *spendAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
299 if a.AccountID == "" {
300 missing = append(missing, "account_id")
302 if a.AssetId.IsZero() {
303 missing = append(missing, "asset_id")
305 if len(missing) > 0 {
306 return txbuilder.MissingFieldsError(missing...)
309 acct, err := a.accounts.FindByID(a.AccountID)
311 return errors.Wrap(err, "get account info")
314 res, err := a.accounts.utxoKeeper.Reserve(a.AccountID, a.AssetId, a.Amount, a.UseUnconfirmed, b.MaxTime())
316 return errors.Wrap(err, "reserving utxos")
319 // Cancel the reservation if the build gets rolled back.
320 b.OnRollback(func() { a.accounts.utxoKeeper.Cancel(res.id) })
321 for _, r := range res.utxos {
322 txInput, sigInst, err := UtxoToInputs(acct.Signer, r)
324 return errors.Wrap(err, "creating inputs")
327 if err = b.AddInput(txInput, sigInst); err != nil {
328 return errors.Wrap(err, "adding inputs")
333 acp, err := a.accounts.CreateAddress(a.AccountID, true)
335 return errors.Wrap(err, "creating control program")
338 // Don't insert the control program until callbacks are executed.
339 a.accounts.insertControlProgramDelayed(b, acp)
340 if err = b.AddOutput(types.NewIntraChainOutput(*a.AssetId, res.change, acp.ControlProgram)); err != nil {
341 return errors.Wrap(err, "adding change output")
347 //DecodeSpendUTXOAction unmarshal JSON-encoded data of spend utxo action
348 func (m *Manager) DecodeSpendUTXOAction(data []byte) (txbuilder.Action, error) {
349 a := &spendUTXOAction{accounts: m}
350 return a, json.Unmarshal(data, a)
353 type spendUTXOAction struct {
355 OutputID *bc.Hash `json:"output_id"`
356 UseUnconfirmed bool `json:"use_unconfirmed"`
357 Arguments []txbuilder.ContractArgument `json:"arguments"`
360 func (a *spendUTXOAction) ActionType() string {
361 return "spend_account_unspent_output"
364 func (a *spendUTXOAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
365 if a.OutputID == nil {
366 return txbuilder.MissingFieldsError("output_id")
369 res, err := a.accounts.utxoKeeper.ReserveParticular(*a.OutputID, a.UseUnconfirmed, b.MaxTime())
374 b.OnRollback(func() { a.accounts.utxoKeeper.Cancel(res.id) })
375 var accountSigner *signers.Signer
376 if len(res.utxos[0].AccountID) != 0 {
377 account, err := a.accounts.FindByID(res.utxos[0].AccountID)
382 accountSigner = account.Signer
385 txInput, sigInst, err := UtxoToInputs(accountSigner, res.utxos[0])
390 if a.Arguments == nil {
391 return b.AddInput(txInput, sigInst)
394 sigInst = &txbuilder.SigningInstruction{}
395 if err := txbuilder.AddContractArgs(sigInst, a.Arguments); err != nil {
399 return b.AddInput(txInput, sigInst)
402 // UtxoToInputs convert an utxo to the txinput
403 func UtxoToInputs(signer *signers.Signer, u *UTXO) (*types.TxInput, *txbuilder.SigningInstruction, error) {
404 txInput := types.NewSpendInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram)
405 sigInst := &txbuilder.SigningInstruction{}
407 return txInput, sigInst, nil
410 path, err := signers.Path(signer, signers.AccountKeySpace, u.Change, u.ControlProgramIndex)
415 sigInst.AddWitnessKeys(signer.XPubs, path, signer.Quorum)
416 return txInput, sigInst, nil
419 address, err := common.DecodeAddress(u.Address, &consensus.ActiveNetParams)
424 sigInst.AddRawWitnessKeys(signer.XPubs, path, signer.Quorum)
425 derivedXPubs := chainkd.DeriveXPubs(signer.XPubs, path)
427 switch address.(type) {
428 case *common.AddressWitnessPubKeyHash:
429 derivedPK := derivedXPubs[0].PublicKey()
430 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness([]byte(derivedPK)))
432 case *common.AddressWitnessScriptHash:
433 derivedPKs := chainkd.XPubKeys(derivedXPubs)
434 script, err := vmutil.P2SPMultiSigProgram(derivedPKs, signer.Quorum)
438 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness(script))
441 return nil, nil, errors.New("unsupport address type")
444 return txInput, sigInst, nil
447 // insertControlProgramDelayed takes a template builder and an account
448 // control program that hasn't been inserted to the database yet. It
449 // registers callbacks on the TemplateBuilder so that all of the template's
450 // account control programs are batch inserted if building the rest of
451 // the template is successful.
452 func (m *Manager) insertControlProgramDelayed(b *txbuilder.TemplateBuilder, acp *CtrlProgram) {
453 m.delayedACPsMu.Lock()
454 m.delayedACPs[b] = append(m.delayedACPs[b], acp)
455 m.delayedACPsMu.Unlock()
457 b.OnRollback(func() {
458 m.delayedACPsMu.Lock()
459 delete(m.delayedACPs, b)
460 m.delayedACPsMu.Unlock()
462 b.OnBuild(func() error {
463 m.delayedACPsMu.Lock()
464 acps := m.delayedACPs[b]
465 delete(m.delayedACPs, b)
466 m.delayedACPsMu.Unlock()
468 // Insert all of the account control programs at once.
472 return m.SaveControlPrograms(acps...)