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 a.accounts.assetReg.GetAsset(a.AssetId.String())
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 {
95 // log.Info("Issue action build")
96 // builder.RestrictMinTime(time.Now())
97 // return builder.AddInput(txin, tplIn)
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)
105 func (a *crossInAction) ActionType() string {
106 return "cross_chain_in"
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)
115 type spendAction struct {
118 AccountID string `json:"account_id"`
119 UseUnconfirmed bool `json:"use_unconfirmed"`
122 func (a *spendAction) ActionType() string {
123 return "spend_account"
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)
131 for _, act := range actions {
132 switch act := act.(type) {
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
139 spendActionMap[actionKey] = act
140 resultActions = append(resultActions, act)
143 resultActions = append(resultActions, act)
149 //calcMergeGas calculate the gas required that n utxos are merged into one
150 func calcMergeGas(num int) uint64 {
153 gas += chainTxMergeGas
154 num -= chainTxUtxoNum - 1
159 func (m *Manager) reserveBtmUtxoChain(builder *txbuilder.TemplateBuilder, accountID string, amount uint64, useUnconfirmed bool) ([]*UTXO, error) {
160 reservedAmount := uint64(0)
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())
169 builder.OnRollback(func() { m.utxoKeeper.Cancel(res.id) })
170 reservedAmount += reserveAmount + res.change
171 utxos = append(utxos, res.utxos[:]...)
176 func (m *Manager) buildBtmTxChain(utxos []*UTXO, signer *signers.Signer) ([]*txbuilder.Template, *UTXO, error) {
178 return nil, nil, errors.New("mergeSpendActionUTXO utxos num 0")
181 tpls := []*txbuilder.Template{}
183 return tpls, utxos[len(utxos)-1], nil
186 acp, err := m.GetLocalCtrlProgramByAddress(utxos[0].Address)
191 buildAmount := uint64(0)
192 builder := &txbuilder.TemplateBuilder{}
193 for index := 0; index < len(utxos); index++ {
194 input, sigInst, err := UtxoToInputs(signer, utxos[index])
199 if err = builder.AddInput(input, sigInst); err != nil {
203 buildAmount += input.Amount()
204 if builder.InputCount() != chainTxUtxoNum && index != len(utxos)-1 {
208 outAmount := buildAmount - chainTxMergeGas
209 output := types.NewIntraChainOutput(*consensus.BTMAssetID, outAmount, acp.ControlProgram)
210 if err := builder.AddOutput(output); err != nil {
214 tpl, _, err := builder.Build()
219 bcOut, err := tpl.Transaction.IntraChainOutput(*tpl.Transaction.ResultIds[0])
224 utxos = append(utxos, &UTXO{
225 OutputID: *tpl.Transaction.ResultIds[0],
226 AssetID: *consensus.BTMAssetID,
228 ControlProgram: acp.ControlProgram,
229 SourceID: *bcOut.Source.Ref,
230 SourcePos: bcOut.Source.Position,
231 ControlProgramIndex: acp.KeyIndex,
232 Address: acp.Address,
236 tpls = append(tpls, tpl)
238 builder = &txbuilder.TemplateBuilder{}
239 if index == len(utxos)-2 {
243 return tpls, utxos[len(utxos)-1], nil
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)
250 return nil, errors.New("fail to convert the spend action")
252 if *act.AssetId != *consensus.BTMAssetID {
253 return nil, errors.New("spend chain action only support BTM")
256 utxos, err := act.accounts.reserveBtmUtxoChain(builder, act.AccountID, act.Amount, act.UseUnconfirmed)
261 acct, err := act.accounts.FindByID(act.AccountID)
266 tpls, utxo, err := act.accounts.buildBtmTxChain(utxos, acct.Signer)
271 input, sigInst, err := UtxoToInputs(acct.Signer, utxo)
276 if err := builder.AddInput(input, sigInst); err != nil {
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")
288 func (a *spendAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
290 if a.AccountID == "" {
291 missing = append(missing, "account_id")
293 if a.AssetId.IsZero() {
294 missing = append(missing, "asset_id")
296 if len(missing) > 0 {
297 return txbuilder.MissingFieldsError(missing...)
300 acct, err := a.accounts.FindByID(a.AccountID)
302 return errors.Wrap(err, "get account info")
305 res, err := a.accounts.utxoKeeper.Reserve(a.AccountID, a.AssetId, a.Amount, a.UseUnconfirmed, b.MaxTime())
307 return errors.Wrap(err, "reserving utxos")
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)
315 return errors.Wrap(err, "creating inputs")
318 if err = b.AddInput(txInput, sigInst); err != nil {
319 return errors.Wrap(err, "adding inputs")
324 acp, err := a.accounts.CreateAddress(a.AccountID, true)
326 return errors.Wrap(err, "creating control program")
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")
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)
344 type spendUTXOAction struct {
346 OutputID *bc.Hash `json:"output_id"`
347 UseUnconfirmed bool `json:"use_unconfirmed"`
348 Arguments []txbuilder.ContractArgument `json:"arguments"`
351 func (a *spendUTXOAction) ActionType() string {
352 return "spend_account_unspent_output"
355 func (a *spendUTXOAction) Build(ctx context.Context, b *txbuilder.TemplateBuilder) error {
356 if a.OutputID == nil {
357 return txbuilder.MissingFieldsError("output_id")
360 res, err := a.accounts.utxoKeeper.ReserveParticular(*a.OutputID, a.UseUnconfirmed, b.MaxTime())
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)
373 accountSigner = account.Signer
376 txInput, sigInst, err := UtxoToInputs(accountSigner, res.utxos[0])
381 if a.Arguments == nil {
382 return b.AddInput(txInput, sigInst)
385 sigInst = &txbuilder.SigningInstruction{}
386 if err := txbuilder.AddContractArgs(sigInst, a.Arguments); err != nil {
390 return b.AddInput(txInput, sigInst)
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{}
398 return txInput, sigInst, nil
401 path, err := signers.Path(signer, signers.AccountKeySpace, u.Change, u.ControlProgramIndex)
406 sigInst.AddWitnessKeys(signer.XPubs, path, signer.Quorum)
407 return txInput, sigInst, nil
410 address, err := common.DecodeAddress(u.Address, &consensus.ActiveNetParams)
415 sigInst.AddRawWitnessKeys(signer.XPubs, path, signer.Quorum)
416 derivedXPubs := chainkd.DeriveXPubs(signer.XPubs, path)
418 switch address.(type) {
419 case *common.AddressWitnessPubKeyHash:
420 derivedPK := derivedXPubs[0].PublicKey()
421 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness([]byte(derivedPK)))
423 case *common.AddressWitnessScriptHash:
424 derivedPKs := chainkd.XPubKeys(derivedXPubs)
425 script, err := vmutil.P2SPMultiSigProgram(derivedPKs, signer.Quorum)
429 sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness(script))
432 return nil, nil, errors.New("unsupport address type")
435 return txInput, sigInst, nil
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()
448 b.OnRollback(func() {
449 m.delayedACPsMu.Lock()
450 delete(m.delayedACPs, b)
451 m.delayedACPsMu.Unlock()
453 b.OnBuild(func() error {
454 m.delayedACPsMu.Lock()
455 acps := m.delayedACPs[b]
456 delete(m.delayedACPs, b)
457 m.delayedACPsMu.Unlock()
459 // Insert all of the account control programs at once.
463 return m.SaveControlPrograms(acps...)