10 log "github.com/sirupsen/logrus"
12 "github.com/bytom/blockchain/txbuilder"
13 "github.com/bytom/consensus"
14 "github.com/bytom/consensus/segwit"
15 "github.com/bytom/errors"
16 "github.com/bytom/math/checked"
17 "github.com/bytom/net/http/reqid"
18 "github.com/bytom/protocol/bc"
19 "github.com/bytom/protocol/bc/types"
22 var defaultTxTTL = 5 * time.Minute
24 func (a *API) actionDecoder(action string) (func([]byte) (txbuilder.Action, error), bool) {
25 var decoder func([]byte) (txbuilder.Action, error)
27 case "control_address":
28 decoder = txbuilder.DecodeControlAddressAction
29 case "control_program":
30 decoder = txbuilder.DecodeControlProgramAction
31 case "control_receiver":
32 decoder = txbuilder.DecodeControlReceiverAction
34 decoder = a.wallet.AssetReg.DecodeIssueAction
36 decoder = txbuilder.DecodeRetireAction
38 decoder = a.wallet.AccountMgr.DecodeSpendAction
39 case "spend_account_unspent_output":
40 decoder = a.wallet.AccountMgr.DecodeSpendUTXOAction
47 func mergeActions(req *BuildRequest) []map[string]interface{} {
48 var actions []map[string]interface{}
49 actionMap := make(map[string]map[string]interface{})
51 for _, m := range req.Actions {
52 if actionType := m["type"].(string); actionType != "spend_account" {
53 actions = append(actions, m)
57 actionKey := m["asset_id"].(string) + m["account_id"].(string)
58 amountNumber := m["amount"].(json.Number)
59 amount, _ := amountNumber.Int64()
61 if tmpM, ok := actionMap[actionKey]; ok {
62 tmpNumber, _ := tmpM["amount"].(json.Number)
63 tmpAmount, _ := tmpNumber.Int64()
64 tmpM["amount"] = json.Number(fmt.Sprintf("%v", tmpAmount+amount))
66 actionMap[actionKey] = m
67 actions = append(actions, m)
74 func onlyHaveSpendActions(req *BuildRequest) bool {
76 for _, m := range req.Actions {
77 if actionType := m["type"].(string); strings.HasPrefix(actionType, "spend") {
82 return count == len(req.Actions)
85 func (a *API) buildSingle(ctx context.Context, req *BuildRequest) (*txbuilder.Template, error) {
86 err := a.filterAliases(ctx, req)
91 if onlyHaveSpendActions(req) {
92 return nil, errors.New("transaction only contain spend actions, didn't have output actions")
95 reqActions := mergeActions(req)
96 actions := make([]txbuilder.Action, 0, len(reqActions))
97 for i, act := range reqActions {
98 typ, ok := act["type"].(string)
100 return nil, errors.WithDetailf(errBadActionType, "no action type provided on action %d", i)
102 decoder, ok := a.actionDecoder(typ)
104 return nil, errors.WithDetailf(errBadActionType, "unknown action type %q on action %d", typ, i)
107 // Remarshal to JSON, the action may have been modified when we
109 b, err := json.Marshal(act)
113 action, err := decoder(b)
115 return nil, errors.WithDetailf(errBadAction, "%s on action %d", err.Error(), i)
117 actions = append(actions, action)
120 ttl := req.TTL.Duration
124 maxTime := time.Now().Add(ttl)
126 tpl, err := txbuilder.Build(ctx, req.Tx, actions, maxTime, req.TimeRange)
127 if errors.Root(err) == txbuilder.ErrAction {
128 // append each of the inner errors contained in the data.
130 for _, innerErr := range errors.Data(err)["actions"].([]error) {
131 Errs = Errs + "<" + innerErr.Error() + ">"
133 err = errors.New(err.Error() + "-" + Errs)
139 // ensure null is never returned for signing instructions
140 if tpl.SigningInstructions == nil {
141 tpl.SigningInstructions = []*txbuilder.SigningInstruction{}
146 // POST /build-transaction
147 func (a *API) build(ctx context.Context, buildReqs *BuildRequest) Response {
148 subctx := reqid.NewSubContext(ctx, reqid.New())
150 tmpl, err := a.buildSingle(subctx, buildReqs)
152 return NewErrorResponse(err)
155 return NewSuccessResponse(tmpl)
158 type submitTxResp struct {
159 TxID *bc.Hash `json:"tx_id"`
162 // POST /submit-transaction
163 func (a *API) submit(ctx context.Context, ins struct {
164 Tx types.Tx `json:"raw_transaction"`
166 if err := txbuilder.FinalizeTx(ctx, a.chain, &ins.Tx); err != nil {
167 return NewErrorResponse(err)
170 log.WithField("tx_id", ins.Tx.ID).Info("submit single tx")
171 return NewSuccessResponse(&submitTxResp{TxID: &ins.Tx.ID})
174 // EstimateTxGasResp estimate transaction consumed gas
175 type EstimateTxGasResp struct {
176 TotalGas int64 `json:"total_gas"`
177 StorageGas int64 `json:"storage_gas"`
178 VMGas int64 `json:"vm_gas"`
181 // POST /estimate-transaction-gas
182 func (a *API) estimateTxGas(ctx context.Context, in struct {
183 TxTemplate txbuilder.Template `json:"transaction_template"`
185 // base tx size and not include sign
186 data, err := in.TxTemplate.Transaction.TxData.MarshalText()
188 return NewErrorResponse(err)
190 baseTxSize := int64(len(data))
192 // extra tx size for sign witness parts
193 baseWitnessSize := int64(300)
194 lenSignInst := int64(len(in.TxTemplate.SigningInstructions))
195 signSize := baseWitnessSize * lenSignInst
197 // total gas for tx storage
198 totalTxSizeGas, ok := checked.MulInt64(baseTxSize+signSize, consensus.StorageGasRate)
200 return NewErrorResponse(errors.New("calculate txsize gas got a math error"))
203 // consume gas for run VM
204 totalP2WPKHGas := int64(0)
205 totalP2WSHGas := int64(0)
206 baseP2WPKHGas := int64(1419)
207 baseP2WSHGas := int64(2499)
209 for _, inpID := range in.TxTemplate.Transaction.Tx.InputIDs {
210 sp, err := in.TxTemplate.Transaction.Spend(inpID)
215 resOut, err := in.TxTemplate.Transaction.Output(*sp.SpentOutputId)
220 if segwit.IsP2WPKHScript(resOut.ControlProgram.Code) {
221 totalP2WPKHGas += baseP2WPKHGas
222 } else if segwit.IsP2WPKHScript(resOut.ControlProgram.Code) {
223 totalP2WSHGas += baseP2WSHGas
227 // total estimate gas
228 totalGas := totalTxSizeGas + totalP2WPKHGas + totalP2WSHGas
230 txGasResp := &EstimateTxGasResp{
232 StorageGas: totalTxSizeGas,
233 VMGas: totalP2WPKHGas + totalP2WSHGas,
236 return NewSuccessResponse(txGasResp)