OSDN Git Service

elegent the code
[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         transaction, err := a.wallet.GetTransactionByTxID(txInfo.TxID)
75         if err != nil {
76                 log.Errorf("getTransaction error: %v", err)
77                 return NewErrorResponse(err)
78         }
79
80         return NewSuccessResponse(transaction)
81 }
82
83 // POST /list-transactions
84 func (a *API) listTransactions(ctx context.Context, filter struct {
85         ID        string `json:"id"`
86         AccountID string `json:"account_id"`
87         Detail    bool   `json:"detail"`
88 }) Response {
89         transactions := []*query.AnnotatedTx{}
90         var err error
91
92         if filter.AccountID != "" {
93                 transactions, err = a.wallet.GetTransactionsByAccountID(filter.AccountID)
94         } else {
95                 transactions, err = a.wallet.GetTransactionsByTxID(filter.ID)
96         }
97
98         if err != nil {
99                 log.Errorf("listTransactions: %v", err)
100                 return NewErrorResponse(err)
101         }
102
103         if filter.Detail == false {
104                 txSummary := a.wallet.GetTransactionsSummary(transactions)
105                 return NewSuccessResponse(txSummary)
106         }
107         return NewSuccessResponse(transactions)
108 }
109
110 // POST /get-unconfirmed-transaction
111 func (a *API) getUnconfirmedTx(ctx context.Context, filter struct {
112         TxID chainjson.HexBytes `json:"tx_id"`
113 }) Response {
114         var tmpTxID [32]byte
115         copy(tmpTxID[:], filter.TxID[:])
116
117         txHash := bc.NewHash(tmpTxID)
118         txPool := a.chain.GetTxPool()
119         txDesc, err := txPool.GetTransaction(&txHash)
120         if err != nil {
121                 return NewErrorResponse(err)
122         }
123
124         tx := &BlockTx{
125                 ID:         txDesc.Tx.ID,
126                 Version:    txDesc.Tx.Version,
127                 Size:       txDesc.Tx.SerializedSize,
128                 TimeRange:  txDesc.Tx.TimeRange,
129                 Inputs:     []*query.AnnotatedInput{},
130                 Outputs:    []*query.AnnotatedOutput{},
131                 StatusFail: false,
132         }
133
134         for i := range txDesc.Tx.Inputs {
135                 tx.Inputs = append(tx.Inputs, a.wallet.BuildAnnotatedInput(txDesc.Tx, uint32(i)))
136         }
137         for i := range txDesc.Tx.Outputs {
138                 tx.Outputs = append(tx.Outputs, a.wallet.BuildAnnotatedOutput(txDesc.Tx, i))
139         }
140
141         return NewSuccessResponse(tx)
142 }
143
144 type unconfirmedTxsResp struct {
145         Total uint64    `json:"total"`
146         TxIDs []bc.Hash `json:"tx_ids"`
147 }
148
149 // POST /list-unconfirmed-transactions
150 func (a *API) listUnconfirmedTxs(ctx context.Context) Response {
151         txIDs := []bc.Hash{}
152
153         txPool := a.chain.GetTxPool()
154         txs := txPool.GetTransactions()
155         for _, txDesc := range txs {
156                 txIDs = append(txIDs, bc.Hash(txDesc.Tx.ID))
157         }
158
159         return NewSuccessResponse(&unconfirmedTxsResp{
160                 Total: uint64(len(txIDs)),
161                 TxIDs: txIDs,
162         })
163 }
164
165 // RawTx is the tx struct for getRawTransaction
166 type RawTx struct {
167         Version   uint64                   `json:"version"`
168         Size      uint64                   `json:"size"`
169         TimeRange uint64                   `json:"time_range"`
170         Inputs    []*query.AnnotatedInput  `json:"inputs"`
171         Outputs   []*query.AnnotatedOutput `json:"outputs"`
172         Fee       int64                    `json:"fee"`
173 }
174
175 // POST /decode-raw-transaction
176 func (a *API) decodeRawTransaction(ctx context.Context, ins struct {
177         Tx types.Tx `json:"raw_transaction"`
178 }) Response {
179         tx := &RawTx{
180                 Version:   ins.Tx.Version,
181                 Size:      ins.Tx.SerializedSize,
182                 TimeRange: ins.Tx.TimeRange,
183                 Inputs:    []*query.AnnotatedInput{},
184                 Outputs:   []*query.AnnotatedOutput{},
185         }
186
187         for i := range ins.Tx.Inputs {
188                 tx.Inputs = append(tx.Inputs, a.wallet.BuildAnnotatedInput(&ins.Tx, uint32(i)))
189         }
190         for i := range ins.Tx.Outputs {
191                 tx.Outputs = append(tx.Outputs, a.wallet.BuildAnnotatedOutput(&ins.Tx, i))
192         }
193
194         totalInputBtm := uint64(0)
195         totalOutputBtm := uint64(0)
196         for _, input := range tx.Inputs {
197                 if input.AssetID.String() == consensus.BTMAssetID.String() {
198                         totalInputBtm += input.Amount
199                 }
200         }
201
202         for _, output := range tx.Outputs {
203                 if output.AssetID.String() == consensus.BTMAssetID.String() {
204                         totalOutputBtm += output.Amount
205                 }
206         }
207
208         tx.Fee = int64(totalInputBtm) - int64(totalOutputBtm)
209         return NewSuccessResponse(tx)
210 }
211
212 // POST /list-unspent-outputs
213 func (a *API) listUnspentOutputs(ctx context.Context, filter struct {
214         ID string `json:"id"`
215 }) Response {
216         accountUTXOs := a.wallet.GetAccountUTXOs(filter.ID)
217
218         UTXOs := []query.AnnotatedUTXO{}
219         for _, utxo := range accountUTXOs {
220                 UTXOs = append([]query.AnnotatedUTXO{{
221                         AccountID:           utxo.AccountID,
222                         OutputID:            utxo.OutputID.String(),
223                         SourceID:            utxo.SourceID.String(),
224                         AssetID:             utxo.AssetID.String(),
225                         Amount:              utxo.Amount,
226                         SourcePos:           utxo.SourcePos,
227                         Program:             fmt.Sprintf("%x", utxo.ControlProgram),
228                         ControlProgramIndex: utxo.ControlProgramIndex,
229                         Address:             utxo.Address,
230                         ValidHeight:         utxo.ValidHeight,
231                         Alias:               a.wallet.AccountMgr.GetAliasByID(utxo.AccountID),
232                         AssetAlias:          a.wallet.AssetReg.GetAliasByID(utxo.AssetID.String()),
233                         Change:              utxo.Change,
234                 }}, UTXOs...)
235         }
236
237         return NewSuccessResponse(UTXOs)
238 }
239
240 // return gasRate
241 func (a *API) gasRate() Response {
242         gasrate := map[string]int64{"gas_rate": consensus.VMGasRate}
243         return NewSuccessResponse(gasrate)
244 }