OSDN Git Service

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