OSDN Git Service

f49fef147a0e456241bbcc0f0b142c8a1edf3f5f
[bytom/bytom.git] / blockchain / 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/bytom/blockchain/signers"
12         "github.com/bytom/blockchain/txbuilder"
13         chainjson "github.com/bytom/encoding/json"
14         "github.com/bytom/protocol/bc"
15         "github.com/bytom/protocol/bc/legacy"
16 )
17
18 //NewIssueAction create a new asset issue action
19 func (reg *Registry) NewIssueAction(assetAmount bc.AssetAmount, referenceData chainjson.Map) txbuilder.Action {
20         return &issueAction{
21                 assets:        reg,
22                 AssetAmount:   assetAmount,
23                 ReferenceData: referenceData,
24         }
25 }
26
27 //DecodeIssueAction unmarshal JSON-encoded data of asset issue action
28 func (reg *Registry) DecodeIssueAction(data []byte) (txbuilder.Action, error) {
29         a := &issueAction{assets: reg}
30         err := json.Unmarshal(data, a)
31         return a, err
32 }
33
34 type issueAction struct {
35         assets *Registry
36         bc.AssetAmount
37         ReferenceData chainjson.Map `json:"reference_data"`
38 }
39
40 func (a *issueAction) Build(ctx context.Context, builder *txbuilder.TemplateBuilder) error {
41         if a.AssetId.IsZero() {
42                 return txbuilder.MissingFieldsError("asset_id")
43         }
44
45         asset, err := a.assets.findByID(ctx, a.AssetId)
46         if err != nil {
47                 return err
48         }
49
50         var nonce [8]byte
51         _, err = rand.Read(nonce[:])
52         if err != nil {
53                 return err
54         }
55
56         assetDef := asset.RawDefinition()
57
58         txin := legacy.NewIssuanceInput(nonce[:], a.Amount, a.ReferenceData, asset.InitialBlockHash, asset.IssuanceProgram, nil, assetDef)
59
60         tplIn := &txbuilder.SigningInstruction{}
61         path := signers.Path(asset.Signer, signers.AssetKeySpace)
62         tplIn.AddWitnessKeys(asset.Signer.XPubs, path, asset.Signer.Quorum)
63
64         log.Info("Issue action build")
65         builder.RestrictMinTime(time.Now())
66         return builder.AddInput(txin, tplIn)
67 }