8 log "github.com/sirupsen/logrus"
9 "github.com/tendermint/tmlibs/db"
11 "github.com/bytom/account"
12 "github.com/bytom/asset"
13 "github.com/bytom/blockchain/query"
14 "github.com/bytom/crypto/sha3pool"
15 chainjson "github.com/bytom/encoding/json"
16 "github.com/bytom/protocol/bc"
17 "github.com/bytom/protocol/bc/types"
21 //TxPrefix is wallet database transactions prefix
23 //TxIndexPrefix is wallet database tx index prefix
24 TxIndexPrefix = "TID:"
27 func formatKey(blockHeight uint64, position uint32) string {
28 return fmt.Sprintf("%016x%08x", blockHeight, position)
31 func calcAnnotatedKey(formatKey string) []byte {
32 return []byte(TxPrefix + formatKey)
35 func calcDeleteKey(blockHeight uint64) []byte {
36 return []byte(fmt.Sprintf("%s%016x", TxPrefix, blockHeight))
39 func calcTxIndexKey(txID string) []byte {
40 return []byte(TxIndexPrefix + txID)
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()
50 if err := json.Unmarshal(txIter.Value(), &tmpTx); err == nil {
51 batch.Delete(calcTxIndexKey(tmpTx.ID.String()))
53 batch.Delete(txIter.Key())
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()
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)
78 // Summary is the struct of transaction's input and output summary
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"`
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"`
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)
103 for _, tx := range annotatedTxs {
104 rawTx, err := json.Marshal(tx)
106 log.WithField("err", err).Error("inserting annotated_txs to db")
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))))
113 // delete unconfirmed transaction
114 batch.Delete(calcUnconfirmedTxKey(tx.ID.String()))
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))
124 for pos, tx := range b.Transactions {
125 statusFail, _ := txStatus.GetStatus(pos)
126 for _, v := range tx.Outputs {
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
135 for _, v := range tx.Inputs {
136 outid, err := v.SpentOutputID()
140 if bytes := w.DB.Get(account.StandardUTXOKey(outid)); bytes != nil {
141 annotatedTxs = append(annotatedTxs, w.buildAnnotatedTransaction(tx, b, statusFail, pos))
142 continue transactionLoop
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)
157 annotatedTx := &query.AnnotatedTx{}
158 txInfo := w.DB.Get(calcAnnotatedKey(string(formatKey)))
159 if err := json.Unmarshal(txInfo, annotatedTx); err != nil {
162 annotateTxsAsset(w, []*query.AnnotatedTx{annotatedTx})
164 return annotatedTx, nil
167 // GetTransactionsSummary get transactions summary
168 func (w *Wallet) GetTransactionsSummary(transactions []*query.AnnotatedTx) []TxSummary {
171 for _, annotatedTx := range transactions {
172 tmpTxSummary := TxSummary{
173 Inputs: make([]Summary, len(annotatedTx.Inputs)),
174 Outputs: make([]Summary, len(annotatedTx.Outputs)),
176 Timestamp: annotatedTx.Timestamp,
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
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
197 Txs = append(Txs, tmpTxSummary)
203 func findTransactionsByAccount(annotatedTx *query.AnnotatedTx, accountID string) bool {
204 for _, input := range annotatedTx.Inputs {
205 if input.AccountID == accountID {
210 for _, output := range annotatedTx.Outputs {
211 if output.AccountID == accountID {
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{}
223 txIter := w.DB.IteratorPrefix([]byte(TxPrefix))
224 defer txIter.Release()
226 annotatedTx := &query.AnnotatedTx{}
227 if err := json.Unmarshal(txIter.Value(), &annotatedTx); err != nil {
231 if accountID == "" || findTransactionsByAccount(annotatedTx, accountID) {
232 annotateTxsAsset(w, []*query.AnnotatedTx{annotatedTx})
233 annotatedTxs = append([]*query.AnnotatedTx{annotatedTx}, annotatedTxs...)
237 return annotatedTxs, nil
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))
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"`
255 func (w *Wallet) indexBalances(accountUTXOs []*account.UTXO) ([]AccountBalance, error) {
256 accBalance := make(map[string]map[string]uint64)
257 balances := []AccountBalance{}
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
265 accBalance[accountUTXO.AccountID][assetID] = accountUTXO.Amount
268 accBalance[accountUTXO.AccountID] = map[string]uint64{assetID: accountUTXO.Amount}
272 var sortedAccount []string
273 for k := range accBalance {
274 sortedAccount = append(sortedAccount, k)
276 sort.Strings(sortedAccount)
278 for _, id := range sortedAccount {
279 var sortedAsset []string
280 for k := range accBalance[id] {
281 sortedAsset = append(sortedAsset, k)
283 sort.Strings(sortedAsset)
285 for _, assetID := range sortedAsset {
286 alias := w.AccountMgr.GetAliasByID(id)
287 targetAsset, err := w.AssetReg.GetAsset(assetID)
292 assetAlias := *targetAsset.Alias
293 balances = append(balances, AccountBalance{
297 AssetAlias: assetAlias,
298 Amount: accBalance[id][assetID],
299 AssetDefinition: targetAsset.DefinitionMap,