OSDN Git Service

optimise
[bytom/bytom.git] / api / query.go
1 package api
2
3 import (
4         "context"
5         "fmt"
6
7         log "github.com/sirupsen/logrus"
8
9         "github.com/bytom/account"
10         "github.com/bytom/blockchain/query"
11         "github.com/bytom/consensus"
12         chainjson "github.com/bytom/encoding/json"
13         "github.com/bytom/protocol/bc"
14         "github.com/bytom/protocol/bc/types"
15 )
16
17 // POST /list-accounts
18 func (a *API) listAccounts(ctx context.Context, filter struct {
19         ID string `json:"id"`
20 }) Response {
21         accounts, err := a.wallet.AccountMgr.ListAccounts(filter.ID)
22         if err != nil {
23                 log.Errorf("listAccounts: %v", err)
24                 return NewErrorResponse(err)
25         }
26
27         annotatedAccounts := []query.AnnotatedAccount{}
28         for _, acc := range accounts {
29                 annotatedAccounts = append(annotatedAccounts, *account.Annotated(acc))
30         }
31
32         return NewSuccessResponse(annotatedAccounts)
33 }
34
35 // POST /get-asset
36 func (a *API) getAsset(ctx context.Context, filter struct {
37         ID string `json:"id"`
38 }) Response {
39         asset, err := a.wallet.AssetReg.GetAsset(filter.ID)
40         if err != nil {
41                 log.Errorf("getAsset: %v", err)
42                 return NewErrorResponse(err)
43         }
44
45         return NewSuccessResponse(asset)
46 }
47
48 // POST /list-assets
49 func (a *API) listAssets(ctx context.Context, filter struct {
50         ID string `json:"id"`
51 }) Response {
52         assets, err := a.wallet.AssetReg.ListAssets(filter.ID)
53         if err != nil {
54                 log.Errorf("listAssets: %v", err)
55                 return NewErrorResponse(err)
56         }
57
58         return NewSuccessResponse(assets)
59 }
60
61 // POST /list-balances
62 func (a *API) listBalances(ctx context.Context) Response {
63         balances, err := a.wallet.GetAccountBalances("")
64         if err != nil {
65                 return NewErrorResponse(err)
66         }
67         return NewSuccessResponse(balances)
68 }
69
70 // POST /get-transaction
71 func (a *API) getTransaction(ctx context.Context, txInfo struct {
72         TxID string `json:"tx_id"`
73 }) Response {
74         var annotatedTx *query.AnnotatedTx
75         var err error
76
77         annotatedTx, err = a.wallet.GetTransactionByTxID(txInfo.TxID)
78         if err != nil {
79                 // transaction not found in blockchain db, search it from unconfirmed db
80                 annotatedTx, err = a.wallet.GetUnconfirmedTxByTxID(txInfo.TxID)
81                 if err != nil {
82                         return NewErrorResponse(err)
83                 }
84         }
85
86         return NewSuccessResponse(annotatedTx)
87 }
88
89 // POST /list-transactions
90 func (a *API) listTransactions(ctx context.Context, filter struct {
91         ID          string `json:"id"`
92         AccountID   string `json:"account_id"`
93         Detail      bool   `json:"detail"`
94         Unconfirmed bool   `json:"unconfirmed"`
95 }) Response {
96         transactions := []*query.AnnotatedTx{}
97         var err error
98         var transaction *query.AnnotatedTx
99
100         if filter.ID != "" {
101                 if filter.Unconfirmed {
102                         transaction, err = a.wallet.GetUnconfirmedTxByTxID(filter.ID)
103                 } else {
104                         transaction, err = a.wallet.GetTransactionByTxID(filter.ID)
105                 }
106                 transactions = []*query.AnnotatedTx{transaction}
107         } else {
108                 if filter.Unconfirmed {
109                         transactions, err = a.wallet.GetUnconfirmedTxs(filter.AccountID)
110                 } else {
111                         transactions, err = a.wallet.GetTransactions(filter.AccountID)
112                 }
113         }
114
115         if err != nil {
116                 log.Errorf("listTransactions: %v", err)
117                 return NewErrorResponse(err)
118         }
119
120         if filter.Detail == false {
121                 txSummary := a.wallet.GetTransactionsSummary(transactions)
122                 return NewSuccessResponse(txSummary)
123         }
124         return NewSuccessResponse(transactions)
125 }
126
127 // POST /get-unconfirmed-transaction
128 func (a *API) getUnconfirmedTx(ctx context.Context, filter struct {
129         TxID chainjson.HexBytes `json:"tx_id"`
130 }) Response {
131         var tmpTxID [32]byte
132         copy(tmpTxID[:], filter.TxID[:])
133
134         txHash := bc.NewHash(tmpTxID)
135         txPool := a.chain.GetTxPool()
136         txDesc, err := txPool.GetTransaction(&txHash)
137         if err != nil {
138                 return NewErrorResponse(err)
139         }
140
141         tx := &BlockTx{
142                 ID:         txDesc.Tx.ID,
143                 Version:    txDesc.Tx.Version,
144                 Size:       txDesc.Tx.SerializedSize,
145                 TimeRange:  txDesc.Tx.TimeRange,
146                 Inputs:     []*query.AnnotatedInput{},
147                 Outputs:    []*query.AnnotatedOutput{},
148                 StatusFail: false,
149         }
150
151         for i := range txDesc.Tx.Inputs {
152                 tx.Inputs = append(tx.Inputs, a.wallet.BuildAnnotatedInput(txDesc.Tx, uint32(i)))
153         }
154         for i := range txDesc.Tx.Outputs {
155                 tx.Outputs = append(tx.Outputs, a.wallet.BuildAnnotatedOutput(txDesc.Tx, i))
156         }
157
158         return NewSuccessResponse(tx)
159 }
160
161 type unconfirmedTxsResp struct {
162         Total uint64    `json:"total"`
163         TxIDs []bc.Hash `json:"tx_ids"`
164 }
165
166 // POST /list-unconfirmed-transactions
167 func (a *API) listUnconfirmedTxs(ctx context.Context) Response {
168         txIDs := []bc.Hash{}
169
170         txPool := a.chain.GetTxPool()
171         txs := txPool.GetTransactions()
172         for _, txDesc := range txs {
173                 txIDs = append(txIDs, bc.Hash(txDesc.Tx.ID))
174         }
175
176         return NewSuccessResponse(&unconfirmedTxsResp{
177                 Total: uint64(len(txIDs)),
178                 TxIDs: txIDs,
179         })
180 }
181
182 // RawTx is the tx struct for getRawTransaction
183 type RawTx struct {
184         Version   uint64                   `json:"version"`
185         Size      uint64                   `json:"size"`
186         TimeRange uint64                   `json:"time_range"`
187         Inputs    []*query.AnnotatedInput  `json:"inputs"`
188         Outputs   []*query.AnnotatedOutput `json:"outputs"`
189         Fee       int64                    `json:"fee"`
190 }
191
192 // POST /decode-raw-transaction
193 func (a *API) decodeRawTransaction(ctx context.Context, ins struct {
194         Tx types.Tx `json:"raw_transaction"`
195 }) Response {
196         tx := &RawTx{
197                 Version:   ins.Tx.Version,
198                 Size:      ins.Tx.SerializedSize,
199                 TimeRange: ins.Tx.TimeRange,
200                 Inputs:    []*query.AnnotatedInput{},
201                 Outputs:   []*query.AnnotatedOutput{},
202         }
203
204         for i := range ins.Tx.Inputs {
205                 tx.Inputs = append(tx.Inputs, a.wallet.BuildAnnotatedInput(&ins.Tx, uint32(i)))
206         }
207         for i := range ins.Tx.Outputs {
208                 tx.Outputs = append(tx.Outputs, a.wallet.BuildAnnotatedOutput(&ins.Tx, i))
209         }
210
211         totalInputBtm := uint64(0)
212         totalOutputBtm := uint64(0)
213         for _, input := range tx.Inputs {
214                 if input.AssetID.String() == consensus.BTMAssetID.String() {
215                         totalInputBtm += input.Amount
216                 }
217         }
218
219         for _, output := range tx.Outputs {
220                 if output.AssetID.String() == consensus.BTMAssetID.String() {
221                         totalOutputBtm += output.Amount
222                 }
223         }
224
225         tx.Fee = int64(totalInputBtm) - int64(totalOutputBtm)
226         return NewSuccessResponse(tx)
227 }
228
229 // POST /list-unspent-outputs
230 func (a *API) listUnspentOutputs(ctx context.Context, filter struct {
231         ID string `json:"id"`
232 }) Response {
233         accountUTXOs := a.wallet.GetAccountUTXOs(filter.ID)
234
235         UTXOs := []query.AnnotatedUTXO{}
236         for _, utxo := range accountUTXOs {
237                 UTXOs = append([]query.AnnotatedUTXO{{
238                         AccountID:           utxo.AccountID,
239                         OutputID:            utxo.OutputID.String(),
240                         SourceID:            utxo.SourceID.String(),
241                         AssetID:             utxo.AssetID.String(),
242                         Amount:              utxo.Amount,
243                         SourcePos:           utxo.SourcePos,
244                         Program:             fmt.Sprintf("%x", utxo.ControlProgram),
245                         ControlProgramIndex: utxo.ControlProgramIndex,
246                         Address:             utxo.Address,
247                         ValidHeight:         utxo.ValidHeight,
248                         Alias:               a.wallet.AccountMgr.GetAliasByID(utxo.AccountID),
249                         AssetAlias:          a.wallet.AssetReg.GetAliasByID(utxo.AssetID.String()),
250                         Change:              utxo.Change,
251                 }}, UTXOs...)
252         }
253
254         return NewSuccessResponse(UTXOs)
255 }
256
257 // return gasRate
258 func (a *API) gasRate() Response {
259         gasrate := map[string]int64{"gas_rate": consensus.VMGasRate}
260         return NewSuccessResponse(gasrate)
261 }