OSDN Git Service

new repo
[bytom/vapor.git] / wallet / indexer.go
1 package wallet
2
3 import (
4         "encoding/json"
5         "fmt"
6         "sort"
7
8         log "github.com/sirupsen/logrus"
9         "github.com/tendermint/tmlibs/db"
10
11         "github.com/vapor/account"
12         "github.com/vapor/asset"
13         "github.com/vapor/blockchain/query"
14         "github.com/vapor/crypto/sha3pool"
15         chainjson "github.com/vapor/encoding/json"
16         "github.com/vapor/protocol/bc"
17         "github.com/vapor/protocol/bc/types"
18 )
19
20 const (
21         //TxPrefix is wallet database transactions prefix
22         TxPrefix = "TXS:"
23         //TxIndexPrefix is wallet database tx index prefix
24         TxIndexPrefix = "TID:"
25 )
26
27 func formatKey(blockHeight uint64, position uint32) string {
28         return fmt.Sprintf("%016x%08x", blockHeight, position)
29 }
30
31 func calcAnnotatedKey(formatKey string) []byte {
32         return []byte(TxPrefix + formatKey)
33 }
34
35 func calcDeleteKey(blockHeight uint64) []byte {
36         return []byte(fmt.Sprintf("%s%016x", TxPrefix, blockHeight))
37 }
38
39 func calcTxIndexKey(txID string) []byte {
40         return []byte(TxIndexPrefix + txID)
41 }
42
43 // deleteTransaction delete transactions when orphan block rollback
44 func (w *Wallet) deleteTransactions(batch db.Batch, height uint64) {
45         tmpTx := query.AnnotatedTx{}
46         txIter := w.DB.IteratorPrefix(calcDeleteKey(height))
47         defer txIter.Release()
48
49         for txIter.Next() {
50                 if err := json.Unmarshal(txIter.Value(), &tmpTx); err == nil {
51                         batch.Delete(calcTxIndexKey(tmpTx.ID.String()))
52                 }
53                 batch.Delete(txIter.Key())
54         }
55 }
56
57 // saveExternalAssetDefinition save external and local assets definition,
58 // when query ,query local first and if have no then query external
59 // details see getAliasDefinition
60 func saveExternalAssetDefinition(b *types.Block, walletDB db.DB) {
61         storeBatch := walletDB.NewBatch()
62         defer storeBatch.Write()
63
64         for _, tx := range b.Transactions {
65                 for _, orig := range tx.Inputs {
66                         if ii, ok := orig.TypedInput.(*types.IssuanceInput); ok {
67                                 if isValidJSON(ii.AssetDefinition) {
68                                         assetID := ii.AssetID()
69                                         if assetExist := walletDB.Get(asset.ExtAssetKey(&assetID)); assetExist == nil {
70                                                 storeBatch.Set(asset.ExtAssetKey(&assetID), ii.AssetDefinition)
71                                         }
72                                 }
73                         }
74                 }
75         }
76 }
77
78 // Summary is the struct of transaction's input and output summary
79 type Summary struct {
80         Type         string             `json:"type"`
81         AssetID      bc.AssetID         `json:"asset_id,omitempty"`
82         AssetAlias   string             `json:"asset_alias,omitempty"`
83         Amount       uint64             `json:"amount,omitempty"`
84         AccountID    string             `json:"account_id,omitempty"`
85         AccountAlias string             `json:"account_alias,omitempty"`
86         Arbitrary    chainjson.HexBytes `json:"arbitrary,omitempty"`
87 }
88
89 // TxSummary is the struct of transaction summary
90 type TxSummary struct {
91         ID        bc.Hash   `json:"tx_id"`
92         Timestamp uint64    `json:"block_time"`
93         Inputs    []Summary `json:"inputs"`
94         Outputs   []Summary `json:"outputs"`
95 }
96
97 // indexTransactions saves all annotated transactions to the database.
98 func (w *Wallet) indexTransactions(batch db.Batch, b *types.Block, txStatus *bc.TransactionStatus) error {
99         annotatedTxs := w.filterAccountTxs(b, txStatus)
100         saveExternalAssetDefinition(b, w.DB)
101         annotateTxsAccount(annotatedTxs, w.DB)
102
103         for _, tx := range annotatedTxs {
104                 rawTx, err := json.Marshal(tx)
105                 if err != nil {
106                         log.WithField("err", err).Error("inserting annotated_txs to db")
107                         return err
108                 }
109
110                 batch.Set(calcAnnotatedKey(formatKey(b.Height, uint32(tx.Position))), rawTx)
111                 batch.Set(calcTxIndexKey(tx.ID.String()), []byte(formatKey(b.Height, uint32(tx.Position))))
112
113                 // delete unconfirmed transaction
114                 batch.Delete(calcUnconfirmedTxKey(tx.ID.String()))
115         }
116         return nil
117 }
118
119 // filterAccountTxs related and build the fully annotated transactions.
120 func (w *Wallet) filterAccountTxs(b *types.Block, txStatus *bc.TransactionStatus) []*query.AnnotatedTx {
121         annotatedTxs := make([]*query.AnnotatedTx, 0, len(b.Transactions))
122
123 transactionLoop:
124         for pos, tx := range b.Transactions {
125                 statusFail, _ := txStatus.GetStatus(pos)
126                 for _, v := range tx.Outputs {
127                         var hash [32]byte
128                         sha3pool.Sum256(hash[:], v.ControlProgram)
129                         if bytes := w.DB.Get(account.ContractKey(hash)); bytes != nil {
130                                 annotatedTxs = append(annotatedTxs, w.buildAnnotatedTransaction(tx, b, statusFail, pos))
131                                 continue transactionLoop
132                         }
133                 }
134
135                 for _, v := range tx.Inputs {
136                         outid, err := v.SpentOutputID()
137                         if err != nil {
138                                 continue
139                         }
140                         if bytes := w.DB.Get(account.StandardUTXOKey(outid)); bytes != nil {
141                                 annotatedTxs = append(annotatedTxs, w.buildAnnotatedTransaction(tx, b, statusFail, pos))
142                                 continue transactionLoop
143                         }
144                 }
145         }
146
147         return annotatedTxs
148 }
149
150 // GetTransactionByTxID get transaction by txID
151 func (w *Wallet) GetTransactionByTxID(txID string) (*query.AnnotatedTx, error) {
152         formatKey := w.DB.Get(calcTxIndexKey(txID))
153         if formatKey == nil {
154                 return nil, fmt.Errorf("No transaction(tx_id=%s) ", txID)
155         }
156
157         annotatedTx := &query.AnnotatedTx{}
158         txInfo := w.DB.Get(calcAnnotatedKey(string(formatKey)))
159         if err := json.Unmarshal(txInfo, annotatedTx); err != nil {
160                 return nil, err
161         }
162         annotateTxsAsset(w, []*query.AnnotatedTx{annotatedTx})
163
164         return annotatedTx, nil
165 }
166
167 // GetTransactionsSummary get transactions summary
168 func (w *Wallet) GetTransactionsSummary(transactions []*query.AnnotatedTx) []TxSummary {
169         Txs := []TxSummary{}
170
171         for _, annotatedTx := range transactions {
172                 tmpTxSummary := TxSummary{
173                         Inputs:    make([]Summary, len(annotatedTx.Inputs)),
174                         Outputs:   make([]Summary, len(annotatedTx.Outputs)),
175                         ID:        annotatedTx.ID,
176                         Timestamp: annotatedTx.Timestamp,
177                 }
178
179                 for i, input := range annotatedTx.Inputs {
180                         tmpTxSummary.Inputs[i].Type = input.Type
181                         tmpTxSummary.Inputs[i].AccountID = input.AccountID
182                         tmpTxSummary.Inputs[i].AccountAlias = input.AccountAlias
183                         tmpTxSummary.Inputs[i].AssetID = input.AssetID
184                         tmpTxSummary.Inputs[i].AssetAlias = input.AssetAlias
185                         tmpTxSummary.Inputs[i].Amount = input.Amount
186                         tmpTxSummary.Inputs[i].Arbitrary = input.Arbitrary
187                 }
188                 for j, output := range annotatedTx.Outputs {
189                         tmpTxSummary.Outputs[j].Type = output.Type
190                         tmpTxSummary.Outputs[j].AccountID = output.AccountID
191                         tmpTxSummary.Outputs[j].AccountAlias = output.AccountAlias
192                         tmpTxSummary.Outputs[j].AssetID = output.AssetID
193                         tmpTxSummary.Outputs[j].AssetAlias = output.AssetAlias
194                         tmpTxSummary.Outputs[j].Amount = output.Amount
195                 }
196
197                 Txs = append(Txs, tmpTxSummary)
198         }
199
200         return Txs
201 }
202
203 func findTransactionsByAccount(annotatedTx *query.AnnotatedTx, accountID string) bool {
204         for _, input := range annotatedTx.Inputs {
205                 if input.AccountID == accountID {
206                         return true
207                 }
208         }
209
210         for _, output := range annotatedTx.Outputs {
211                 if output.AccountID == accountID {
212                         return true
213                 }
214         }
215
216         return false
217 }
218
219 // GetTransactions get all walletDB transactions, and filter transactions by accountID optional
220 func (w *Wallet) GetTransactions(accountID string) ([]*query.AnnotatedTx, error) {
221         annotatedTxs := []*query.AnnotatedTx{}
222
223         txIter := w.DB.IteratorPrefix([]byte(TxPrefix))
224         defer txIter.Release()
225         for txIter.Next() {
226                 annotatedTx := &query.AnnotatedTx{}
227                 if err := json.Unmarshal(txIter.Value(), &annotatedTx); err != nil {
228                         return nil, err
229                 }
230
231                 if accountID == "" || findTransactionsByAccount(annotatedTx, accountID) {
232                         annotateTxsAsset(w, []*query.AnnotatedTx{annotatedTx})
233                         annotatedTxs = append([]*query.AnnotatedTx{annotatedTx}, annotatedTxs...)
234                 }
235         }
236
237         return annotatedTxs, nil
238 }
239
240 // GetAccountBalances return all account balances
241 func (w *Wallet) GetAccountBalances(accountID string, id string) ([]AccountBalance, error) {
242         return w.indexBalances(w.GetAccountUtxos(accountID, "", false, false))
243 }
244
245 // AccountBalance account balance
246 type AccountBalance struct {
247         AccountID       string                 `json:"account_id"`
248         Alias           string                 `json:"account_alias"`
249         AssetAlias      string                 `json:"asset_alias"`
250         AssetID         string                 `json:"asset_id"`
251         Amount          uint64                 `json:"amount"`
252         AssetDefinition map[string]interface{} `json:"asset_definition"`
253 }
254
255 func (w *Wallet) indexBalances(accountUTXOs []*account.UTXO) ([]AccountBalance, error) {
256         accBalance := make(map[string]map[string]uint64)
257         balances := []AccountBalance{}
258
259         for _, accountUTXO := range accountUTXOs {
260                 assetID := accountUTXO.AssetID.String()
261                 if _, ok := accBalance[accountUTXO.AccountID]; ok {
262                         if _, ok := accBalance[accountUTXO.AccountID][assetID]; ok {
263                                 accBalance[accountUTXO.AccountID][assetID] += accountUTXO.Amount
264                         } else {
265                                 accBalance[accountUTXO.AccountID][assetID] = accountUTXO.Amount
266                         }
267                 } else {
268                         accBalance[accountUTXO.AccountID] = map[string]uint64{assetID: accountUTXO.Amount}
269                 }
270         }
271
272         var sortedAccount []string
273         for k := range accBalance {
274                 sortedAccount = append(sortedAccount, k)
275         }
276         sort.Strings(sortedAccount)
277
278         for _, id := range sortedAccount {
279                 var sortedAsset []string
280                 for k := range accBalance[id] {
281                         sortedAsset = append(sortedAsset, k)
282                 }
283                 sort.Strings(sortedAsset)
284
285                 for _, assetID := range sortedAsset {
286                         alias := w.AccountMgr.GetAliasByID(id)
287                         targetAsset, err := w.AssetReg.GetAsset(assetID)
288                         if err != nil {
289                                 return nil, err
290                         }
291
292                         assetAlias := *targetAsset.Alias
293                         balances = append(balances, AccountBalance{
294                                 Alias:           alias,
295                                 AccountID:       id,
296                                 AssetID:         assetID,
297                                 AssetAlias:      assetAlias,
298                                 Amount:          accBalance[id][assetID],
299                                 AssetDefinition: targetAsset.DefinitionMap,
300                         })
301                 }
302         }
303
304         return balances, nil
305 }