OSDN Git Service

befa2863519926f527a5b53012601aa9d711cc1d
[bytom/bytom.git] / api / transact.go
1 package api
2
3 import (
4         "context"
5         "encoding/json"
6         "math"
7         "strings"
8         "time"
9
10         log "github.com/sirupsen/logrus"
11
12         "github.com/bytom/account"
13         "github.com/bytom/blockchain/txbuilder"
14         "github.com/bytom/consensus"
15         "github.com/bytom/consensus/segwit"
16         "github.com/bytom/errors"
17         "github.com/bytom/math/checked"
18         "github.com/bytom/net/http/reqid"
19         "github.com/bytom/protocol/bc"
20         "github.com/bytom/protocol/bc/types"
21 )
22
23 var (
24         defaultTxTTL    = 5 * time.Minute
25         defaultBaseRate = float64(100000)
26 )
27
28 func (a *API) actionDecoder(action string) (func([]byte) (txbuilder.Action, error), bool) {
29         decoders := map[string]func([]byte) (txbuilder.Action, error){
30                 "control_address":              txbuilder.DecodeControlAddressAction,
31                 "control_program":              txbuilder.DecodeControlProgramAction,
32                 "control_receiver":             txbuilder.DecodeControlReceiverAction,
33                 "issue":                        a.wallet.AssetReg.DecodeIssueAction,
34                 "retire":                       txbuilder.DecodeRetireAction,
35                 "spend_account":                a.wallet.AccountMgr.DecodeSpendAction,
36                 "spend_account_unspent_output": a.wallet.AccountMgr.DecodeSpendUTXOAction,
37         }
38         decoder, ok := decoders[action]
39         return decoder, ok
40 }
41
42 func onlyHaveSpendActions(req *BuildRequest) bool {
43         count := 0
44         for _, m := range req.Actions {
45                 if actionType := m["type"].(string); strings.HasPrefix(actionType, "spend") {
46                         count++
47                 }
48         }
49
50         return count == len(req.Actions)
51 }
52
53 func (a *API) buildSingle(ctx context.Context, req *BuildRequest) (*txbuilder.Template, error) {
54         if err := a.completeMissingIds(ctx, req); err != nil {
55                 return nil, err
56         }
57
58         if onlyHaveSpendActions(req) {
59                 return nil, errors.New("transaction only contain spend actions, didn't have output actions")
60         }
61
62         actions := make([]txbuilder.Action, 0, len(req.Actions))
63         for i, act := range req.Actions {
64                 typ, ok := act["type"].(string)
65                 if !ok {
66                         return nil, errors.WithDetailf(errBadActionType, "no action type provided on action %d", i)
67                 }
68                 decoder, ok := a.actionDecoder(typ)
69                 if !ok {
70                         return nil, errors.WithDetailf(errBadActionType, "unknown action type %q on action %d", typ, i)
71                 }
72
73                 // Remarshal to JSON, the action may have been modified when we
74                 // filtered aliases.
75                 b, err := json.Marshal(act)
76                 if err != nil {
77                         return nil, err
78                 }
79                 action, err := decoder(b)
80                 if err != nil {
81                         return nil, errors.WithDetailf(errBadAction, "%s on action %d", err.Error(), i)
82                 }
83                 actions = append(actions, action)
84         }
85         actions = account.MergeSpendAction(actions)
86
87         ttl := req.TTL.Duration
88         if ttl == 0 {
89                 ttl = defaultTxTTL
90         }
91         maxTime := time.Now().Add(ttl)
92
93         tpl, err := txbuilder.Build(ctx, req.Tx, actions, maxTime, req.TimeRange)
94         if errors.Root(err) == txbuilder.ErrAction {
95                 // append each of the inner errors contained in the data.
96                 var Errs string
97                 for _, innerErr := range errors.Data(err)["actions"].([]error) {
98                         Errs = Errs + "<" + innerErr.Error() + ">"
99                 }
100                 err = errors.New(err.Error() + "-" + Errs)
101         }
102         if err != nil {
103                 return nil, err
104         }
105
106         // ensure null is never returned for signing instructions
107         if tpl.SigningInstructions == nil {
108                 tpl.SigningInstructions = []*txbuilder.SigningInstruction{}
109         }
110         return tpl, nil
111 }
112
113 // POST /build-transaction
114 func (a *API) build(ctx context.Context, buildReqs *BuildRequest) Response {
115         subctx := reqid.NewSubContext(ctx, reqid.New())
116
117         tmpl, err := a.buildSingle(subctx, buildReqs)
118         if err != nil {
119                 return NewErrorResponse(err)
120         }
121
122         return NewSuccessResponse(tmpl)
123 }
124
125 type submitTxResp struct {
126         TxID *bc.Hash `json:"tx_id"`
127 }
128
129 // POST /submit-transaction
130 func (a *API) submit(ctx context.Context, ins struct {
131         Tx types.Tx `json:"raw_transaction"`
132 }) Response {
133         if err := txbuilder.FinalizeTx(ctx, a.chain, &ins.Tx); err != nil {
134                 return NewErrorResponse(err)
135         }
136
137         log.WithField("tx_id", ins.Tx.ID.String()).Info("submit single tx")
138         return NewSuccessResponse(&submitTxResp{TxID: &ins.Tx.ID})
139 }
140
141 // EstimateTxGasResp estimate transaction consumed gas
142 type EstimateTxGasResp struct {
143         TotalNeu   int64 `json:"total_neu"`
144         StorageNeu int64 `json:"storage_neu"`
145         VMNeu      int64 `json:"vm_neu"`
146 }
147
148 // EstimateTxGas estimate consumed neu for transaction
149 func EstimateTxGas(template txbuilder.Template) (*EstimateTxGasResp, error) {
150         // base tx size and not include sign
151         data, err := template.Transaction.TxData.MarshalText()
152         if err != nil {
153                 return nil, err
154         }
155         baseTxSize := int64(len(data))
156
157         // extra tx size for sign witness parts
158         baseWitnessSize := int64(300)
159         lenSignInst := int64(len(template.SigningInstructions))
160         signSize := baseWitnessSize * lenSignInst
161
162         // total gas for tx storage
163         totalTxSizeGas, ok := checked.MulInt64(baseTxSize+signSize, consensus.StorageGasRate)
164         if !ok {
165                 return nil, errors.New("calculate txsize gas got a math error")
166         }
167
168         // consume gas for run VM
169         totalP2WPKHGas := int64(0)
170         totalP2WSHGas := int64(0)
171         baseP2WPKHGas := int64(1419)
172         baseP2WSHGas := int64(2499)
173
174         for _, inpID := range template.Transaction.Tx.InputIDs {
175                 sp, err := template.Transaction.Spend(inpID)
176                 if err != nil {
177                         continue
178                 }
179
180                 resOut, err := template.Transaction.Output(*sp.SpentOutputId)
181                 if err != nil {
182                         continue
183                 }
184
185                 if segwit.IsP2WPKHScript(resOut.ControlProgram.Code) {
186                         totalP2WPKHGas += baseP2WPKHGas
187                 } else if segwit.IsP2WSHScript(resOut.ControlProgram.Code) {
188                         totalP2WSHGas += baseP2WSHGas
189                 }
190         }
191
192         // total estimate gas
193         totalGas := totalTxSizeGas + totalP2WPKHGas + totalP2WSHGas
194
195         // rounding totalNeu with base rate 100000
196         totalNeu := float64(totalGas*consensus.VMGasRate) / defaultBaseRate
197         roundingNeu := math.Ceil(totalNeu)
198         estimateNeu := int64(roundingNeu) * int64(defaultBaseRate)
199
200         return &EstimateTxGasResp{
201                 TotalNeu:   estimateNeu,
202                 StorageNeu: totalTxSizeGas * consensus.VMGasRate,
203                 VMNeu:      (totalP2WPKHGas + totalP2WSHGas) * consensus.VMGasRate,
204         }, nil
205 }
206
207 // POST /estimate-transaction-gas
208 func (a *API) estimateTxGas(ctx context.Context, in struct {
209         TxTemplate txbuilder.Template `json:"transaction_template"`
210 }) Response {
211         txGasResp, err := EstimateTxGas(in.TxTemplate)
212         if err != nil {
213                 return NewErrorResponse(err)
214         }
215         return NewSuccessResponse(txGasResp)
216 }