OSDN Git Service

7015522f5a0003f30fa9daede6f0e5181bd10b0c
[bytom/bytom.git] / api / query.go
1 package api
2
3 import (
4         "context"
5         "encoding/hex"
6         "fmt"
7
8         log "github.com/sirupsen/logrus"
9
10         "github.com/bytom/account"
11         "github.com/bytom/asset"
12         "github.com/bytom/blockchain/query"
13         "github.com/bytom/blockchain/signers"
14         "github.com/bytom/blockchain/txbuilder"
15         "github.com/bytom/consensus"
16         "github.com/bytom/crypto/ed25519"
17         "github.com/bytom/crypto/ed25519/chainkd"
18         chainjson "github.com/bytom/encoding/json"
19         "github.com/bytom/errors"
20         "github.com/bytom/protocol/bc"
21         "github.com/bytom/protocol/bc/types"
22 )
23
24 // POST /list-accounts
25 func (a *API) listAccounts(ctx context.Context, filter struct {
26         ID    string `json:"id"`
27         Alias string `json:"alias"`
28 }) Response {
29         accountID := filter.ID
30         if filter.Alias != "" {
31                 acc, err := a.wallet.AccountMgr.FindByAlias(filter.Alias)
32                 if err != nil {
33                         return NewErrorResponse(err)
34                 }
35                 accountID = acc.ID
36         }
37
38         accounts, err := a.wallet.AccountMgr.ListAccounts(accountID)
39         if err != nil {
40                 log.Errorf("listAccounts: %v", err)
41                 return NewErrorResponse(err)
42         }
43
44         annotatedAccounts := []query.AnnotatedAccount{}
45         for _, acc := range accounts {
46                 annotatedAccounts = append(annotatedAccounts, *account.Annotated(acc))
47         }
48
49         return NewSuccessResponse(annotatedAccounts)
50 }
51
52 // POST /get-asset
53 func (a *API) getAsset(ctx context.Context, filter struct {
54         ID string `json:"id"`
55 }) Response {
56         ass, err := a.wallet.AssetReg.GetAsset(filter.ID)
57         if err != nil {
58                 log.Errorf("getAsset: %v", err)
59                 return NewErrorResponse(err)
60         }
61
62         annotatedAsset, err := asset.Annotated(ass)
63         if err != nil {
64                 return NewErrorResponse(err)
65         }
66         return NewSuccessResponse(annotatedAsset)
67 }
68
69 // POST /list-assets
70 func (a *API) listAssets(ctx context.Context, filter struct {
71         ID string `json:"id"`
72 }) Response {
73         assets, err := a.wallet.AssetReg.ListAssets(filter.ID)
74         if err != nil {
75                 log.Errorf("listAssets: %v", err)
76                 return NewErrorResponse(err)
77         }
78
79         annotatedAssets := []*query.AnnotatedAsset{}
80         for _, ass := range assets {
81                 annotatedAsset, err := asset.Annotated(ass)
82                 if err != nil {
83                         return NewErrorResponse(err)
84                 }
85                 annotatedAssets = append(annotatedAssets, annotatedAsset)
86         }
87         return NewSuccessResponse(annotatedAssets)
88 }
89
90 // POST /list-balances
91 func (a *API) listBalances(ctx context.Context, filter struct {
92         AccountID    string `json:"account_id"`
93         AccountAlias string `json:"account_alias"`
94 }) Response {
95         accountID := filter.AccountID
96         if filter.AccountAlias != "" {
97                 acc, err := a.wallet.AccountMgr.FindByAlias(filter.AccountAlias)
98                 if err != nil {
99                         return NewErrorResponse(err)
100                 }
101                 accountID = acc.ID
102         }
103
104         balances, err := a.wallet.GetAccountBalances(accountID, "")
105         if err != nil {
106                 return NewErrorResponse(err)
107         }
108         return NewSuccessResponse(balances)
109 }
110
111 // POST /get-transaction
112 func (a *API) getTransaction(ctx context.Context, txInfo struct {
113         TxID string `json:"tx_id"`
114 }) Response {
115         var annotatedTx *query.AnnotatedTx
116         var err error
117
118         annotatedTx, err = a.wallet.GetTransactionByTxID(txInfo.TxID)
119         if err != nil {
120                 // transaction not found in blockchain db, search it from unconfirmed db
121                 annotatedTx, err = a.wallet.GetUnconfirmedTxByTxID(txInfo.TxID)
122                 if err != nil {
123                         return NewErrorResponse(err)
124                 }
125         }
126
127         return NewSuccessResponse(annotatedTx)
128 }
129
130 // POST /list-transactions
131 func (a *API) listTransactions(ctx context.Context, filter struct {
132         AccountID    string `json:"account_id"`
133         AccountAlias string `json:"account_alias"`
134         StartTxID    string `json:"start_tx_id"`
135         Detail       bool   `json:"detail"`
136         Unconfirmed  bool   `json:"unconfirmed"`
137         Count        uint   `json:"count"`
138 }) Response {
139         accountID := filter.AccountID
140         if filter.AccountAlias != "" {
141                 acc, err := a.wallet.AccountMgr.FindByAlias(filter.AccountAlias)
142                 if err != nil {
143                         return NewErrorResponse(err)
144                 }
145                 accountID = acc.ID
146         }
147
148         transactions, err := a.wallet.GetTransactions(accountID, filter.StartTxID, filter.Count, filter.Unconfirmed)
149         if err != nil {
150                 return NewErrorResponse(err)
151         }
152
153         if filter.Detail == false {
154                 txSummary := a.wallet.GetTransactionsSummary(transactions)
155                 return NewSuccessResponse(txSummary)
156         }
157
158         return NewSuccessResponse(transactions)
159 }
160
161 // POST /get-unconfirmed-transaction
162 func (a *API) getUnconfirmedTx(ctx context.Context, filter struct {
163         TxID chainjson.HexBytes `json:"tx_id"`
164 }) Response {
165         var tmpTxID [32]byte
166         copy(tmpTxID[:], filter.TxID[:])
167
168         txHash := bc.NewHash(tmpTxID)
169         txPool := a.chain.GetTxPool()
170         txDesc, err := txPool.GetTransaction(&txHash)
171         if err != nil {
172                 return NewErrorResponse(err)
173         }
174
175         tx := &BlockTx{
176                 ID:         txDesc.Tx.ID,
177                 Version:    txDesc.Tx.Version,
178                 Size:       txDesc.Tx.SerializedSize,
179                 TimeRange:  txDesc.Tx.TimeRange,
180                 Inputs:     []*query.AnnotatedInput{},
181                 Outputs:    []*query.AnnotatedOutput{},
182                 StatusFail: txDesc.StatusFail,
183         }
184
185         resOutID := txDesc.Tx.ResultIds[0]
186         resOut := txDesc.Tx.Entries[*resOutID]
187         switch out := resOut.(type) {
188         case *bc.Output:
189                 tx.MuxID = *out.Source.Ref
190         case *bc.Retirement:
191                 tx.MuxID = *out.Source.Ref
192         }
193
194         for i := range txDesc.Tx.Inputs {
195                 tx.Inputs = append(tx.Inputs, a.wallet.BuildAnnotatedInput(txDesc.Tx, uint32(i)))
196         }
197         for i := range txDesc.Tx.Outputs {
198                 tx.Outputs = append(tx.Outputs, a.wallet.BuildAnnotatedOutput(txDesc.Tx, i))
199         }
200
201         return NewSuccessResponse(tx)
202 }
203
204 type unconfirmedTxsResp struct {
205         Total uint64    `json:"total"`
206         TxIDs []bc.Hash `json:"tx_ids"`
207 }
208
209 // POST /list-unconfirmed-transactions
210 func (a *API) listUnconfirmedTxs(ctx context.Context) Response {
211         txIDs := []bc.Hash{}
212
213         txPool := a.chain.GetTxPool()
214         txs := txPool.GetTransactions()
215         for _, txDesc := range txs {
216                 txIDs = append(txIDs, bc.Hash(txDesc.Tx.ID))
217         }
218
219         return NewSuccessResponse(&unconfirmedTxsResp{
220                 Total: uint64(len(txIDs)),
221                 TxIDs: txIDs,
222         })
223 }
224
225 // RawTx is the tx struct for getRawTransaction
226 type RawTx struct {
227         ID        bc.Hash                  `json:"tx_id"`
228         Version   uint64                   `json:"version"`
229         Size      uint64                   `json:"size"`
230         TimeRange uint64                   `json:"time_range"`
231         Inputs    []*query.AnnotatedInput  `json:"inputs"`
232         Outputs   []*query.AnnotatedOutput `json:"outputs"`
233         Fee       uint64                   `json:"fee"`
234 }
235
236 // POST /decode-raw-transaction
237 func (a *API) decodeRawTransaction(ctx context.Context, ins struct {
238         Tx types.Tx `json:"raw_transaction"`
239 }) Response {
240         tx := &RawTx{
241                 ID:        ins.Tx.ID,
242                 Version:   ins.Tx.Version,
243                 Size:      ins.Tx.SerializedSize,
244                 TimeRange: ins.Tx.TimeRange,
245                 Inputs:    []*query.AnnotatedInput{},
246                 Outputs:   []*query.AnnotatedOutput{},
247         }
248
249         for i := range ins.Tx.Inputs {
250                 tx.Inputs = append(tx.Inputs, a.wallet.BuildAnnotatedInput(&ins.Tx, uint32(i)))
251         }
252         for i := range ins.Tx.Outputs {
253                 tx.Outputs = append(tx.Outputs, a.wallet.BuildAnnotatedOutput(&ins.Tx, i))
254         }
255
256         tx.Fee = txbuilder.CalculateTxFee(&ins.Tx)
257         return NewSuccessResponse(tx)
258 }
259
260 // POST /list-unspent-outputs
261 func (a *API) listUnspentOutputs(ctx context.Context, filter struct {
262         AccountID     string `json:"account_id"`
263         AccountAlias  string `json:"account_alias"`
264         ID            string `json:"id"`
265         Unconfirmed   bool   `json:"unconfirmed"`
266         SmartContract bool   `json:"smart_contract"`
267         From          uint   `json:"from"`
268         Count         uint   `json:"count"`
269 }) Response {
270         accountID := filter.AccountID
271         if filter.AccountAlias != "" {
272                 acc, err := a.wallet.AccountMgr.FindByAlias(filter.AccountAlias)
273                 if err != nil {
274                         return NewErrorResponse(err)
275                 }
276                 accountID = acc.ID
277         }
278         accountUTXOs := a.wallet.GetAccountUtxos(accountID, filter.ID, filter.Unconfirmed, filter.SmartContract)
279
280         UTXOs := []query.AnnotatedUTXO{}
281         for _, utxo := range accountUTXOs {
282                 UTXOs = append([]query.AnnotatedUTXO{{
283                         AccountID:           utxo.AccountID,
284                         OutputID:            utxo.OutputID.String(),
285                         SourceID:            utxo.SourceID.String(),
286                         AssetID:             utxo.AssetID.String(),
287                         Amount:              utxo.Amount,
288                         SourcePos:           utxo.SourcePos,
289                         Program:             fmt.Sprintf("%x", utxo.ControlProgram),
290                         ControlProgramIndex: utxo.ControlProgramIndex,
291                         Address:             utxo.Address,
292                         ValidHeight:         utxo.ValidHeight,
293                         Alias:               a.wallet.AccountMgr.GetAliasByID(utxo.AccountID),
294                         AssetAlias:          a.wallet.AssetReg.GetAliasByID(utxo.AssetID.String()),
295                         Change:              utxo.Change,
296                 }}, UTXOs...)
297         }
298         start, end := getPageRange(len(UTXOs), filter.From, filter.Count)
299         return NewSuccessResponse(UTXOs[start:end])
300 }
301
302 // return gasRate
303 func (a *API) gasRate() Response {
304         gasrate := map[string]int64{"gas_rate": consensus.VMGasRate}
305         return NewSuccessResponse(gasrate)
306 }
307
308 // PubKeyInfo is structure of pubkey info
309 type PubKeyInfo struct {
310         Pubkey string               `json:"pubkey"`
311         Path   []chainjson.HexBytes `json:"derivation_path"`
312 }
313
314 // AccountPubkey is detail of account pubkey info
315 type AccountPubkey struct {
316         RootXPub    chainkd.XPub `json:"root_xpub"`
317         PubKeyInfos []PubKeyInfo `json:"pubkey_infos"`
318 }
319
320 func getPubkey(account *account.Account, change bool, index uint64) (*ed25519.PublicKey, []chainjson.HexBytes, error) {
321         rawPath, err := signers.Path(account.Signer, signers.AccountKeySpace, change, index)
322         if err != nil {
323                 return nil, nil, err
324         }
325         derivedXPub := account.XPubs[0].Derive(rawPath)
326         pubkey := derivedXPub.PublicKey()
327         var path []chainjson.HexBytes
328         for _, p := range rawPath {
329                 path = append(path, chainjson.HexBytes(p))
330         }
331
332         return &pubkey, path, nil
333 }
334
335 // POST /list-pubkeys
336 func (a *API) listPubKeys(ctx context.Context, ins struct {
337         AccountID    string `json:"account_id"`
338         AccountAlias string `json:"account_alias"`
339         PublicKey    string `json:"public_key"`
340 }) Response {
341         var err error
342         account := &account.Account{}
343         if ins.AccountAlias != "" {
344                 account, err = a.wallet.AccountMgr.FindByAlias(ins.AccountAlias)
345         } else {
346                 account, err = a.wallet.AccountMgr.FindByID(ins.AccountID)
347         }
348
349         if err != nil {
350                 return NewErrorResponse(err)
351         }
352
353         pubKeyInfos := []PubKeyInfo{}
354         if account.DeriveRule == signers.BIP0032 {
355                 idx := a.wallet.AccountMgr.GetContractIndex(account.ID)
356                 for i := uint64(1); i <= idx; i++ {
357                         pubkey, path, err := getPubkey(account, false, i)
358                         if err != nil {
359                                 return NewErrorResponse(err)
360                         }
361                         if ins.PublicKey != "" && ins.PublicKey != hex.EncodeToString(*pubkey) {
362                                 continue
363                         }
364                         pubKeyInfos = append(pubKeyInfos, PubKeyInfo{
365                                 Pubkey: hex.EncodeToString(*pubkey),
366                                 Path:   path,
367                         })
368                 }
369         } else if account.DeriveRule == signers.BIP0044 {
370                 idx := a.wallet.AccountMgr.GetBip44ContractIndex(account.ID, true)
371                 for i := uint64(1); i <= idx; i++ {
372                         pubkey, path, err := getPubkey(account, true, i)
373                         if err != nil {
374                                 return NewErrorResponse(err)
375                         }
376                         if ins.PublicKey != "" && ins.PublicKey != hex.EncodeToString(*pubkey) {
377                                 continue
378                         }
379                         pubKeyInfos = append(pubKeyInfos, PubKeyInfo{
380                                 Pubkey: hex.EncodeToString(*pubkey),
381                                 Path:   path,
382                         })
383                 }
384
385                 idx = a.wallet.AccountMgr.GetBip44ContractIndex(account.ID, false)
386                 for i := uint64(1); i <= idx; i++ {
387                         pubkey, path, err := getPubkey(account, false, i)
388                         if err != nil {
389                                 return NewErrorResponse(err)
390                         }
391                         if ins.PublicKey != "" && ins.PublicKey != hex.EncodeToString(*pubkey) {
392                                 continue
393                         }
394                         pubKeyInfos = append(pubKeyInfos, PubKeyInfo{
395                                 Pubkey: hex.EncodeToString(*pubkey),
396                                 Path:   path,
397                         })
398                 }
399         }
400
401         if len(pubKeyInfos) == 0 {
402                 return NewErrorResponse(errors.New("Not found publickey for the account"))
403         }
404
405         return NewSuccessResponse(&AccountPubkey{
406                 RootXPub:    account.XPubs[0],
407                 PubKeyInfos: pubKeyInfos,
408         })
409 }