10 log "github.com/sirupsen/logrus"
12 "github.com/bytom/blockchain/txbuilder"
13 "github.com/bytom/errors"
14 "github.com/bytom/net/http/reqid"
15 "github.com/bytom/protocol/bc"
16 "github.com/bytom/protocol/bc/types"
19 var defaultTxTTL = 5 * time.Minute
21 func (a *API) actionDecoder(action string) (func([]byte) (txbuilder.Action, error), bool) {
22 var decoder func([]byte) (txbuilder.Action, error)
24 case "control_account":
25 decoder = a.wallet.AccountMgr.DecodeControlAction
26 case "control_address":
27 decoder = txbuilder.DecodeControlAddressAction
28 case "control_program":
29 decoder = txbuilder.DecodeControlProgramAction
30 case "control_receiver":
31 decoder = txbuilder.DecodeControlReceiverAction
33 decoder = a.wallet.AssetReg.DecodeIssueAction
35 decoder = txbuilder.DecodeRetireAction
37 decoder = a.wallet.AccountMgr.DecodeSpendAction
38 case "spend_account_unspent_output":
39 decoder = a.wallet.AccountMgr.DecodeSpendUTXOAction
46 func mergeActions(req *BuildRequest) []map[string]interface{} {
47 actions := make([]map[string]interface{}, 0)
48 actionMap := make(map[string]map[string]interface{})
50 for _, m := range req.Actions {
51 if actionType := m["type"].(string); actionType != "spend_account" {
52 actions = append(actions, m)
56 actionKey := m["asset_id"].(string) + m["account_id"].(string)
57 amountNumber := m["amount"].(json.Number)
58 amount, _ := amountNumber.Int64()
60 if tmpM, ok := actionMap[actionKey]; ok {
61 tmpNumber, _ := tmpM["amount"].(json.Number)
62 tmpAmount, _ := tmpNumber.Int64()
63 tmpM["amount"] = json.Number(fmt.Sprintf("%v", tmpAmount+amount))
65 actionMap[actionKey] = m
66 actions = append(actions, m)
73 func onlyHaveSpendActions(req *BuildRequest) bool {
75 for _, m := range req.Actions {
76 if actionType := m["type"].(string); strings.HasPrefix(actionType, "spend") {
81 return count == len(req.Actions)
84 func (a *API) buildSingle(ctx context.Context, req *BuildRequest) (*txbuilder.Template, error) {
85 err := a.filterAliases(ctx, req)
90 if onlyHaveSpendActions(req) {
91 return nil, errors.New("transaction only contain spend actions, didn't have output actions")
94 reqActions := mergeActions(req)
95 actions := make([]txbuilder.Action, 0, len(reqActions))
96 for i, act := range reqActions {
97 typ, ok := act["type"].(string)
99 return nil, errors.WithDetailf(errBadActionType, "no action type provided on action %d", i)
101 decoder, ok := a.actionDecoder(typ)
103 return nil, errors.WithDetailf(errBadActionType, "unknown action type %q on action %d", typ, i)
106 // Remarshal to JSON, the action may have been modified when we
108 b, err := json.Marshal(act)
112 action, err := decoder(b)
114 return nil, errors.WithDetailf(errBadAction, "%s on action %d", err.Error(), i)
116 actions = append(actions, action)
119 ttl := req.TTL.Duration
123 maxTime := time.Now().Add(ttl)
125 tpl, err := txbuilder.Build(ctx, req.Tx, actions, maxTime, req.TimeRange)
126 if errors.Root(err) == txbuilder.ErrAction {
127 // append each of the inner errors contained in the data.
129 for _, innerErr := range errors.Data(err)["actions"].([]error) {
130 Errs = Errs + "<" + innerErr.Error() + ">"
132 err = errors.New(err.Error() + "-" + Errs)
138 // ensure null is never returned for signing instructions
139 if tpl.SigningInstructions == nil {
140 tpl.SigningInstructions = []*txbuilder.SigningInstruction{}
145 // POST /build-transaction
146 func (a *API) build(ctx context.Context, buildReqs *BuildRequest) Response {
147 subctx := reqid.NewSubContext(ctx, reqid.New())
149 tmpl, err := a.buildSingle(subctx, buildReqs)
151 return NewErrorResponse(err)
154 return NewSuccessResponse(tmpl)
157 func (a *API) submitSingle(ctx context.Context, tpl *txbuilder.Template) (map[string]string, error) {
158 if tpl.Transaction == nil {
159 return nil, errors.Wrap(txbuilder.ErrMissingRawTx)
162 if err := txbuilder.FinalizeTx(ctx, a.chain, tpl.Transaction); err != nil {
163 return nil, errors.Wrapf(err, "tx %s", tpl.Transaction.ID.String())
166 return map[string]string{"tx_id": tpl.Transaction.ID.String()}, nil
169 type submitTxResp struct {
170 TxID *bc.Hash `json:"tx_id"`
173 // POST /submit-transaction
174 func (a *API) submit(ctx context.Context, ins struct {
175 Tx types.Tx `json:"raw_transaction"`
177 if err := txbuilder.FinalizeTx(ctx, a.chain, &ins.Tx); err != nil {
178 return NewErrorResponse(err)
181 log.WithField("tx_id", ins.Tx.ID).Info("submit single tx")
182 return NewSuccessResponse(&submitTxResp{TxID: &ins.Tx.ID})
185 // POST /sign-submit-transaction
186 func (a *API) signSubmit(ctx context.Context, x struct {
187 Password []string `json:"password"`
188 Txs txbuilder.Template `json:"transaction"`
190 if err := txbuilder.Sign(ctx, &x.Txs, nil, x.Password[0], a.pseudohsmSignTemplate); err != nil {
191 log.WithField("build err", err).Error("fail on sign transaction.")
192 return NewErrorResponse(err)
194 log.Info("Sign Transaction complete.")
196 txID, err := a.submitSingle(nil, &x.Txs)
198 log.WithField("err", err).Error("submit single tx")
199 return NewErrorResponse(err)
202 log.WithField("tx_id", txID["tx_id"]).Info("submit single tx")
203 return NewSuccessResponse(txID)