10 log "github.com/sirupsen/logrus"
12 "github.com/vapor/account"
13 "github.com/vapor/blockchain/txbuilder"
14 "github.com/vapor/consensus"
15 "github.com/vapor/consensus/segwit"
16 "github.com/vapor/errors"
17 "github.com/vapor/math/checked"
18 "github.com/vapor/net/http/reqid"
19 "github.com/vapor/protocol/bc"
20 "github.com/vapor/protocol/bc/types"
24 defaultTxTTL = 5 * time.Minute
25 defaultBaseRate = float64(100000)
26 flexibleGas = int64(1800)
29 func (a *API) actionDecoder(action string) (func([]byte) (txbuilder.Action, error), bool) {
30 decoders := map[string]func([]byte) (txbuilder.Action, error){
31 "control_address": txbuilder.DecodeControlAddressAction,
32 "control_program": txbuilder.DecodeControlProgramAction,
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 "dpos_address": a.wallet.AccountMgr.DecodeDposAction,
39 decoder, ok := decoders[action]
43 func onlyHaveInputActions(req *BuildRequest) (bool, error) {
45 for i, act := range req.Actions {
46 actionType, ok := act["type"].(string)
48 return false, errors.WithDetailf(ErrBadActionType, "no action type provided on action %d", i)
50 if strings.HasPrefix(actionType, "dpos_address") {
53 if strings.HasPrefix(actionType, "spend") || actionType == "issue" {
58 return count == len(req.Actions), nil
61 func (a *API) buildSingle(ctx context.Context, req *BuildRequest) (*txbuilder.Template, error) {
62 if err := a.checkRequestValidity(ctx, req); err != nil {
65 actions, err := a.mergeSpendActions(req)
70 maxTime := time.Now().Add(req.TTL.Duration)
71 tpl, err := txbuilder.Build(ctx, req.Tx, actions, maxTime, req.TimeRange)
72 if errors.Root(err) == txbuilder.ErrAction {
73 // append each of the inner errors contained in the data.
76 for i, innerErr := range errors.Data(err)["actions"].([]error) {
78 rootErr = errors.Root(innerErr)
80 Errs = Errs + innerErr.Error()
82 err = errors.WithDetail(rootErr, Errs)
88 // ensure null is never returned for signing instructions
89 if tpl.SigningInstructions == nil {
90 tpl.SigningInstructions = []*txbuilder.SigningInstruction{}
95 // POST /build-transaction
96 func (a *API) build(ctx context.Context, buildReqs *BuildRequest) Response {
97 subctx := reqid.NewSubContext(ctx, reqid.New())
98 tmpl, err := a.buildSingle(subctx, buildReqs)
100 return NewErrorResponse(err)
103 return NewSuccessResponse(tmpl)
105 func (a *API) checkRequestValidity(ctx context.Context, req *BuildRequest) error {
106 if err := a.completeMissingIDs(ctx, req); err != nil {
110 if req.TTL.Duration == 0 {
111 req.TTL.Duration = defaultTxTTL
114 if ok, err := onlyHaveInputActions(req); err != nil {
117 return errors.WithDetail(ErrBadActionConstruction, "transaction contains only input actions and no output actions")
122 func (a *API) mergeSpendActions(req *BuildRequest) ([]txbuilder.Action, error) {
123 actions := make([]txbuilder.Action, 0, len(req.Actions))
124 for i, act := range req.Actions {
125 typ, ok := act["type"].(string)
127 return nil, errors.WithDetailf(ErrBadActionType, "no action type provided on action %d", i)
129 decoder, ok := a.actionDecoder(typ)
131 return nil, errors.WithDetailf(ErrBadActionType, "unknown action type %q on action %d", typ, i)
134 // Remarshal to JSON, the action may have been modified when we
136 b, err := json.Marshal(act)
140 action, err := decoder(b)
142 return nil, errors.WithDetailf(ErrBadAction, "%s on action %d", err.Error(), i)
144 actions = append(actions, action)
146 actions = account.MergeSpendAction(actions)
150 func (a *API) buildTxs(ctx context.Context, req *BuildRequest) ([]*txbuilder.Template, error) {
151 if err := a.checkRequestValidity(ctx, req); err != nil {
154 actions, err := a.mergeSpendActions(req)
159 builder := txbuilder.NewBuilder(time.Now().Add(req.TTL.Duration))
160 tpls := []*txbuilder.Template{}
161 for _, action := range actions {
162 if action.ActionType() == "spend_account" {
163 tpls, err = account.SpendAccountChain(ctx, builder, action)
165 err = action.Build(ctx, builder)
174 tpl, _, err := builder.Build()
180 tpls = append(tpls, tpl)
184 // POST /build-chain-transactions
185 func (a *API) buildChainTxs(ctx context.Context, buildReqs *BuildRequest) Response {
186 subctx := reqid.NewSubContext(ctx, reqid.New())
187 tmpls, err := a.buildTxs(subctx, buildReqs)
189 return NewErrorResponse(err)
191 return NewSuccessResponse(tmpls)
194 type submitTxResp struct {
195 TxID *bc.Hash `json:"tx_id"`
198 // POST /submit-transaction
199 func (a *API) submit(ctx context.Context, ins struct {
200 Tx types.Tx `json:"raw_transaction"`
202 if err := txbuilder.FinalizeTx(ctx, a.chain, &ins.Tx); err != nil {
203 return NewErrorResponse(err)
206 log.WithField("tx_id", ins.Tx.ID.String()).Info("submit single tx")
207 return NewSuccessResponse(&submitTxResp{TxID: &ins.Tx.ID})
210 type submitTxsResp struct {
211 TxID []*bc.Hash `json:"tx_id"`
214 // POST /submit-transactions
215 func (a *API) submitTxs(ctx context.Context, ins struct {
216 Tx []types.Tx `json:"raw_transactions"`
218 txHashs := []*bc.Hash{}
219 for i := range ins.Tx {
220 if err := txbuilder.FinalizeTx(ctx, a.chain, &ins.Tx[i]); err != nil {
221 return NewErrorResponse(err)
223 log.WithField("tx_id", ins.Tx[i].ID.String()).Info("submit single tx")
224 txHashs = append(txHashs, &ins.Tx[i].ID)
226 return NewSuccessResponse(&submitTxsResp{TxID: txHashs})
229 // EstimateTxGasResp estimate transaction consumed gas
230 type EstimateTxGasResp struct {
231 TotalNeu int64 `json:"total_neu"`
232 StorageNeu int64 `json:"storage_neu"`
233 VMNeu int64 `json:"vm_neu"`
236 // EstimateTxGas estimate consumed neu for transaction
237 func EstimateTxGas(template txbuilder.Template) (*EstimateTxGasResp, error) {
238 // base tx size and not include sign
239 data, err := template.Transaction.TxData.MarshalText()
243 baseTxSize := int64(len(data))
245 // extra tx size for sign witness parts
246 signSize := estimateSignSize(template.SigningInstructions)
248 // total gas for tx storage
249 totalTxSizeGas, ok := checked.MulInt64(baseTxSize+signSize, consensus.StorageGasRate)
251 return nil, errors.New("calculate txsize gas got a math error")
254 // consume gas for run VM
255 totalP2WPKHGas := int64(0)
256 totalP2WSHGas := int64(0)
257 baseP2WPKHGas := int64(1419)
258 // flexible Gas is used for handle need extra utxo situation
260 for pos, inpID := range template.Transaction.Tx.InputIDs {
261 sp, err := template.Transaction.Spend(inpID)
266 resOut, err := template.Transaction.Output(*sp.SpentOutputId)
271 if segwit.IsP2WPKHScript(resOut.ControlProgram.Code) {
272 totalP2WPKHGas += baseP2WPKHGas
273 } else if segwit.IsP2WSHScript(resOut.ControlProgram.Code) {
274 sigInst := template.SigningInstructions[pos]
275 totalP2WSHGas += estimateP2WSHGas(sigInst)
279 // total estimate gas
280 totalGas := totalTxSizeGas + totalP2WPKHGas + totalP2WSHGas + flexibleGas
282 // rounding totalNeu with base rate 100000
283 totalNeu := float64(totalGas*consensus.VMGasRate) / defaultBaseRate
284 roundingNeu := math.Ceil(totalNeu)
285 estimateNeu := int64(roundingNeu) * int64(defaultBaseRate)
289 return &EstimateTxGasResp{
290 TotalNeu: estimateNeu,
291 StorageNeu: totalTxSizeGas * consensus.VMGasRate,
292 VMNeu: (totalP2WPKHGas + totalP2WSHGas) * consensus.VMGasRate,
296 // estimate p2wsh gas.
297 // OP_CHECKMULTISIG consume (984 * a - 72 * b - 63) gas,
298 // where a represent the num of public keys, and b represent the num of quorum.
299 func estimateP2WSHGas(sigInst *txbuilder.SigningInstruction) int64 {
301 baseP2WSHGas := int64(738)
303 for _, witness := range sigInst.WitnessComponents {
304 switch t := witness.(type) {
305 case *txbuilder.SignatureWitness:
306 P2WSHGas += baseP2WSHGas + (984*int64(len(t.Keys)) - 72*int64(t.Quorum) - 63)
307 case *txbuilder.RawTxSigWitness:
308 P2WSHGas += baseP2WSHGas + (984*int64(len(t.Keys)) - 72*int64(t.Quorum) - 63)
314 // estimate signature part size.
315 // if need multi-sign, calculate the size according to the length of keys.
316 func estimateSignSize(signingInstructions []*txbuilder.SigningInstruction) int64 {
318 baseWitnessSize := int64(300)
320 for _, sigInst := range signingInstructions {
321 for _, witness := range sigInst.WitnessComponents {
322 switch t := witness.(type) {
323 case *txbuilder.SignatureWitness:
324 signSize += int64(t.Quorum) * baseWitnessSize
325 case *txbuilder.RawTxSigWitness:
326 signSize += int64(t.Quorum) * baseWitnessSize
333 // POST /estimate-transaction-gas
334 func (a *API) estimateTxGas(ctx context.Context, in struct {
335 TxTemplate txbuilder.Template `json:"transaction_template"`
337 txGasResp, err := EstimateTxGas(in.TxTemplate)
339 return NewErrorResponse(err)
341 return NewSuccessResponse(txGasResp)