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 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,
38 decoder, ok := decoders[action]
42 func onlyHaveSpendActions(req *BuildRequest) bool {
44 for _, m := range req.Actions {
45 if actionType := m["type"].(string); strings.HasPrefix(actionType, "spend") {
50 return count == len(req.Actions)
53 func (a *API) buildSingle(ctx context.Context, req *BuildRequest) (*txbuilder.Template, error) {
54 if err := a.completeMissingIds(ctx, req); err != nil {
58 if onlyHaveSpendActions(req) {
59 return nil, errors.New("transaction only contain spend actions, didn't have output actions")
62 actions := make([]txbuilder.Action, 0, len(req.Actions))
63 for i, act := range req.Actions {
64 typ, ok := act["type"].(string)
66 return nil, errors.WithDetailf(errBadActionType, "no action type provided on action %d", i)
68 decoder, ok := a.actionDecoder(typ)
70 return nil, errors.WithDetailf(errBadActionType, "unknown action type %q on action %d", typ, i)
73 // Remarshal to JSON, the action may have been modified when we
75 b, err := json.Marshal(act)
79 action, err := decoder(b)
81 return nil, errors.WithDetailf(errBadAction, "%s on action %d", err.Error(), i)
83 actions = append(actions, action)
85 actions = account.MergeSpendAction(actions)
87 ttl := req.TTL.Duration
91 maxTime := time.Now().Add(ttl)
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.
97 for _, innerErr := range errors.Data(err)["actions"].([]error) {
98 Errs = Errs + "<" + innerErr.Error() + ">"
100 err = errors.New(err.Error() + "-" + Errs)
106 // ensure null is never returned for signing instructions
107 if tpl.SigningInstructions == nil {
108 tpl.SigningInstructions = []*txbuilder.SigningInstruction{}
113 // POST /build-transaction
114 func (a *API) build(ctx context.Context, buildReqs *BuildRequest) Response {
115 subctx := reqid.NewSubContext(ctx, reqid.New())
117 tmpl, err := a.buildSingle(subctx, buildReqs)
119 return NewErrorResponse(err)
122 return NewSuccessResponse(tmpl)
125 type submitTxResp struct {
126 TxID *bc.Hash `json:"tx_id"`
129 // POST /submit-transaction
130 func (a *API) submit(ctx context.Context, ins struct {
131 Tx types.Tx `json:"raw_transaction"`
133 if err := txbuilder.FinalizeTx(ctx, a.chain, &ins.Tx); err != nil {
134 return NewErrorResponse(err)
137 log.WithField("tx_id", ins.Tx.ID.String()).Info("submit single tx")
138 return NewSuccessResponse(&submitTxResp{TxID: &ins.Tx.ID})
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"`
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()
155 baseTxSize := int64(len(data))
157 // extra tx size for sign witness parts
158 baseWitnessSize := int64(300)
159 lenSignInst := int64(len(template.SigningInstructions))
160 signSize := baseWitnessSize * lenSignInst
162 // total gas for tx storage
163 totalTxSizeGas, ok := checked.MulInt64(baseTxSize+signSize, consensus.StorageGasRate)
165 return nil, errors.New("calculate txsize gas got a math error")
168 // consume gas for run VM
169 totalP2WPKHGas := int64(0)
170 totalP2WSHGas := int64(0)
171 baseP2WPKHGas := int64(1419)
172 baseP2WSHGas := int64(2499)
174 for _, inpID := range template.Transaction.Tx.InputIDs {
175 sp, err := template.Transaction.Spend(inpID)
180 resOut, err := template.Transaction.Output(*sp.SpentOutputId)
185 if segwit.IsP2WPKHScript(resOut.ControlProgram.Code) {
186 totalP2WPKHGas += baseP2WPKHGas
187 } else if segwit.IsP2WSHScript(resOut.ControlProgram.Code) {
188 totalP2WSHGas += baseP2WSHGas
192 // total estimate gas
193 totalGas := totalTxSizeGas + totalP2WPKHGas + totalP2WSHGas
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)
200 return &EstimateTxGasResp{
201 TotalNeu: estimateNeu,
202 StorageNeu: totalTxSizeGas * consensus.VMGasRate,
203 VMNeu: (totalP2WPKHGas + totalP2WSHGas) * consensus.VMGasRate,
207 // POST /estimate-transaction-gas
208 func (a *API) estimateTxGas(ctx context.Context, in struct {
209 TxTemplate txbuilder.Template `json:"transaction_template"`
211 txGasResp, err := EstimateTxGas(in.TxTemplate)
213 return NewErrorResponse(err)
215 return NewSuccessResponse(txGasResp)