OSDN Git Service

44f944183d0b6a950cd1f1826838b3ed53c517c5
[bytom/vapor.git] / asset / builder.go
1 package asset
2
3 import (
4         "context"
5         "crypto/rand"
6         "encoding/json"
7         "time"
8
9         log "github.com/sirupsen/logrus"
10
11         "github.com/vapor/blockchain/signers"
12         "github.com/vapor/blockchain/txbuilder"
13         "github.com/vapor/protocol/bc"
14         "github.com/vapor/protocol/bc/types"
15 )
16
17 //NewIssueAction create a new asset issue action
18 func (reg *Registry) NewIssueAction(assetAmount bc.AssetAmount) txbuilder.Action {
19         return &issueAction{
20                 assets:      reg,
21                 AssetAmount: assetAmount,
22         }
23 }
24
25 //DecodeIssueAction unmarshal JSON-encoded data of asset issue action
26 func (reg *Registry) DecodeIssueAction(data []byte) (txbuilder.Action, error) {
27         a := &issueAction{assets: reg}
28         err := json.Unmarshal(data, a)
29         return a, err
30 }
31
32 type issueAction struct {
33         assets *Registry
34         bc.AssetAmount
35         Arguments []txbuilder.ContractArgument `json:"arguments"`
36 }
37
38 func (a *issueAction) Build(ctx context.Context, builder *txbuilder.TemplateBuilder) error {
39         if a.AssetId.IsZero() {
40                 return txbuilder.MissingFieldsError("asset_id")
41         }
42
43         asset, err := a.assets.FindByID(ctx, a.AssetId)
44         if err != nil {
45                 return err
46         }
47
48         var nonce [8]byte
49         _, err = rand.Read(nonce[:])
50         if err != nil {
51                 return err
52         }
53
54         txin := types.NewIssuanceInput(nonce[:], a.Amount, asset.IssuanceProgram, nil, asset.RawDefinitionByte)
55         tplIn := &txbuilder.SigningInstruction{}
56         if asset.Signer != nil {
57                 path := signers.GetBip0032Path(asset.Signer, signers.AssetKeySpace)
58                 tplIn.AddRawWitnessKeys(asset.Signer.XPubs, path, asset.Signer.Quorum)
59         } else if a.Arguments != nil {
60                 if err := txbuilder.AddContractArgs(tplIn, a.Arguments); err != nil {
61                         return err
62                 }
63         }
64
65         log.Info("Issue action build")
66         builder.RestrictMinTime(time.Now())
67         return builder.AddInput(txin, tplIn)
68 }
69
70 func (a *issueAction) ActionType() string {
71         return "issue"
72 }