10 log "github.com/sirupsen/logrus"
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"
24 defaultTxTTL = 5 * time.Minute
25 defaultBaseRate = float64(100000)
28 func (a *API) actionDecoder(action string) (func([]byte) (txbuilder.Action, error), bool) {
29 var decoder func([]byte) (txbuilder.Action, error)
31 case "control_address":
32 decoder = txbuilder.DecodeControlAddressAction
33 case "control_program":
34 decoder = txbuilder.DecodeControlProgramAction
35 case "control_receiver":
36 decoder = txbuilder.DecodeControlReceiverAction
38 decoder = a.wallet.AssetReg.DecodeIssueAction
40 decoder = txbuilder.DecodeRetireAction
42 decoder = a.wallet.AccountMgr.DecodeSpendAction
43 case "spend_account_unspent_output":
44 decoder = a.wallet.AccountMgr.DecodeSpendUTXOAction
51 func onlyHaveSpendActions(req *BuildRequest) bool {
53 for _, m := range req.Actions {
54 if actionType := m["type"].(string); strings.HasPrefix(actionType, "spend") {
59 return count == len(req.Actions)
62 func (a *API) buildSingle(ctx context.Context, req *BuildRequest) (*txbuilder.Template, error) {
63 err := a.filterAliases(ctx, req)
68 if onlyHaveSpendActions(req) {
69 return nil, errors.New("transaction only contain spend actions, didn't have output actions")
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)
77 return nil, errors.WithDetailf(errBadActionType, "no action type provided on action %d", i)
79 decoder, ok := a.actionDecoder(typ)
81 return nil, errors.WithDetailf(errBadActionType, "unknown action type %q on action %d", typ, i)
84 // Remarshal to JSON, the action may have been modified when we
86 b, err := json.Marshal(act)
90 action, err := decoder(b)
92 return nil, errors.WithDetailf(errBadAction, "%s on action %d", err.Error(), i)
95 if typ == "spend_account" {
96 spendActions = append(spendActions, action)
98 actions = append(actions, action)
101 actions = append(account.MergeSpendAction(spendActions), actions...)
103 ttl := req.TTL.Duration
107 maxTime := time.Now().Add(ttl)
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.
113 for _, innerErr := range errors.Data(err)["actions"].([]error) {
114 Errs = Errs + "<" + innerErr.Error() + ">"
116 err = errors.New(err.Error() + "-" + Errs)
122 // ensure null is never returned for signing instructions
123 if tpl.SigningInstructions == nil {
124 tpl.SigningInstructions = []*txbuilder.SigningInstruction{}
129 // POST /build-transaction
130 func (a *API) build(ctx context.Context, buildReqs *BuildRequest) Response {
131 subctx := reqid.NewSubContext(ctx, reqid.New())
133 tmpl, err := a.buildSingle(subctx, buildReqs)
135 return NewErrorResponse(err)
138 return NewSuccessResponse(tmpl)
141 type submitTxResp struct {
142 TxID *bc.Hash `json:"tx_id"`
145 // POST /submit-transaction
146 func (a *API) submit(ctx context.Context, ins struct {
147 Tx types.Tx `json:"raw_transaction"`
149 if err := txbuilder.FinalizeTx(ctx, a.chain, &ins.Tx); err != nil {
150 return NewErrorResponse(err)
153 log.WithField("tx_id", ins.Tx.ID).Info("submit single tx")
154 return NewSuccessResponse(&submitTxResp{TxID: &ins.Tx.ID})
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"`
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()
171 baseTxSize := int64(len(data))
173 // extra tx size for sign witness parts
174 baseWitnessSize := int64(300)
175 lenSignInst := int64(len(template.SigningInstructions))
176 signSize := baseWitnessSize * lenSignInst
178 // total gas for tx storage
179 totalTxSizeGas, ok := checked.MulInt64(baseTxSize+signSize, consensus.StorageGasRate)
181 return nil, errors.New("calculate txsize gas got a math error")
184 // consume gas for run VM
185 totalP2WPKHGas := int64(0)
186 totalP2WSHGas := int64(0)
187 baseP2WPKHGas := int64(1419)
188 baseP2WSHGas := int64(2499)
190 for _, inpID := range template.Transaction.Tx.InputIDs {
191 sp, err := template.Transaction.Spend(inpID)
196 resOut, err := template.Transaction.Output(*sp.SpentOutputId)
201 if segwit.IsP2WPKHScript(resOut.ControlProgram.Code) {
202 totalP2WPKHGas += baseP2WPKHGas
203 } else if segwit.IsP2WSHScript(resOut.ControlProgram.Code) {
204 totalP2WSHGas += baseP2WSHGas
208 // total estimate gas
209 totalGas := totalTxSizeGas + totalP2WPKHGas + totalP2WSHGas
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)
216 return &EstimateTxGasResp{
217 TotalNeu: estimateNeu,
218 StorageNeu: totalTxSizeGas * consensus.VMGasRate,
219 VMNeu: (totalP2WPKHGas + totalP2WSHGas) * consensus.VMGasRate,
223 // POST /estimate-transaction-gas
224 func (a *API) estimateTxGas(ctx context.Context, in struct {
225 TxTemplate txbuilder.Template `json:"transaction_template"`
227 txGasResp, err := EstimateTxGas(in.TxTemplate)
229 return NewErrorResponse(err)
231 return NewSuccessResponse(txGasResp)