9 log "github.com/sirupsen/logrus"
11 "github.com/vapor/account"
12 "github.com/vapor/blockchain/query"
13 "github.com/vapor/consensus"
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"
20 func parseGlobalTxIdx(globalTxIdx []byte) (*bc.Hash, uint64) {
21 var hashBytes [32]byte
22 copy(hashBytes[:], globalTxIdx[:32])
23 hash := bc.NewHash(hashBytes)
24 position := binary.BigEndian.Uint64(globalTxIdx[32:])
25 return &hash, position
28 // saveExternalAssetDefinition save external and local assets definition,
29 // when query ,query local first and if have no then query external
30 // details see getAliasDefinition
31 func saveExternalAssetDefinition(b *types.Block, store WalletStore) error {
32 newStore := store.InitBatch()
34 for _, tx := range b.Transactions {
35 for _, orig := range tx.Inputs {
36 if cci, ok := orig.TypedInput.(*types.CrossChainInput); ok {
37 if cci.AssetId.String() == consensus.BTMAssetID.String() {
40 assetID := cci.AssetId
41 if _, err := newStore.GetAsset(assetID); err == nil {
43 } else if err != ErrGetAsset {
47 newStore.SetAssetDefinition(assetID, cci.AssetDefinition)
51 if err := newStore.CommitBatch(); err != nil {
58 // Summary is the struct of transaction's input and output summary
60 Type string `json:"type"`
61 AssetID bc.AssetID `json:"asset_id,omitempty"`
62 AssetAlias string `json:"asset_alias,omitempty"`
63 Amount uint64 `json:"amount,omitempty"`
64 AccountID string `json:"account_id,omitempty"`
65 AccountAlias string `json:"account_alias,omitempty"`
66 Arbitrary chainjson.HexBytes `json:"arbitrary,omitempty"`
69 // TxSummary is the struct of transaction summary
70 type TxSummary struct {
71 ID bc.Hash `json:"tx_id"`
72 Timestamp uint64 `json:"block_time"`
73 Inputs []Summary `json:"inputs"`
74 Outputs []Summary `json:"outputs"`
77 // indexTransactions saves all annotated transactions to the database.
78 func (w *Wallet) indexTransactions(b *types.Block, txStatus *bc.TransactionStatus, annotatedTxs []*query.AnnotatedTx, store WalletStore) error {
79 for _, tx := range annotatedTxs {
80 if err := w.Store.SetTransaction(b.Height, tx); err != nil {
84 store.DeleteUnconfirmedTransaction(tx.ID.String())
91 for position, globalTx := range b.Transactions {
92 blockHash := b.BlockHeader.Hash()
93 store.SetGlobalTransactionIndex(globalTx.ID.String(), &blockHash, uint64(position))
99 // filterAccountTxs related and build the fully annotated transactions.
100 func (w *Wallet) filterAccountTxs(b *types.Block, txStatus *bc.TransactionStatus) []*query.AnnotatedTx {
101 annotatedTxs := make([]*query.AnnotatedTx, 0, len(b.Transactions))
104 for pos, tx := range b.Transactions {
105 statusFail, _ := txStatus.GetStatus(pos)
106 for _, v := range tx.Outputs {
108 sha3pool.Sum256(hash[:], v.ControlProgram())
109 if _, err := w.AccountMgr.GetControlProgram(bc.NewHash(hash)); err == nil {
110 annotatedTxs = append(annotatedTxs, w.buildAnnotatedTransaction(tx, b, statusFail, pos))
111 continue transactionLoop
112 } else if err != account.ErrFindCtrlProgram {
113 log.WithFields(log.Fields{"module": logModule, "err": err, "hash": hex.EncodeToString(hash[:])}).Error("filterAccountTxs fail.")
117 for _, v := range tx.Inputs {
118 outid, err := v.SpentOutputID()
120 log.WithFields(log.Fields{"module": logModule, "err": err, "outputID": outid.String()}).Error("filterAccountTxs fail.")
123 if _, err = w.Store.GetStandardUTXO(outid); err == nil {
124 annotatedTxs = append(annotatedTxs, w.buildAnnotatedTransaction(tx, b, statusFail, pos))
125 continue transactionLoop
126 } else if err != ErrGetStandardUTXO {
127 log.WithFields(log.Fields{"module": logModule, "err": err, "outputID": outid.String()}).Error("filterAccountTxs fail.")
135 // GetTransactionByTxID get transaction by txID
136 func (w *Wallet) GetTransactionByTxID(txID string) (*query.AnnotatedTx, error) {
137 if annotatedTx, err := w.getAccountTxByTxID(txID); err == nil {
138 return annotatedTx, nil
139 } else if !w.TxIndexFlag {
143 return w.getGlobalTxByTxID(txID)
146 func (w *Wallet) getAccountTxByTxID(txID string) (*query.AnnotatedTx, error) {
147 annotatedTx, err := w.Store.GetTransaction(txID)
152 annotateTxsAsset(w, []*query.AnnotatedTx{annotatedTx})
153 return annotatedTx, nil
156 func (w *Wallet) getGlobalTxByTxID(txID string) (*query.AnnotatedTx, error) {
157 globalTxIdx := w.Store.GetGlobalTransactionIndex(txID)
158 if globalTxIdx == nil {
159 return nil, fmt.Errorf("No transaction(tx_id=%s) ", txID)
162 blockHash, pos := parseGlobalTxIdx(globalTxIdx)
163 block, err := w.Chain.GetBlockByHash(blockHash)
168 txStatus, err := w.Chain.GetTransactionStatus(blockHash)
173 statusFail, err := txStatus.GetStatus(int(pos))
178 tx := block.Transactions[int(pos)]
179 return w.buildAnnotatedTransaction(tx, block, statusFail, int(pos)), nil
182 // GetTransactionsSummary get transactions summary
183 func (w *Wallet) GetTransactionsSummary(transactions []*query.AnnotatedTx) []TxSummary {
186 for _, annotatedTx := range transactions {
187 tmpTxSummary := TxSummary{
188 Inputs: make([]Summary, len(annotatedTx.Inputs)),
189 Outputs: make([]Summary, len(annotatedTx.Outputs)),
191 Timestamp: annotatedTx.Timestamp,
194 for i, input := range annotatedTx.Inputs {
195 tmpTxSummary.Inputs[i].Type = input.Type
196 tmpTxSummary.Inputs[i].AccountID = input.AccountID
197 tmpTxSummary.Inputs[i].AccountAlias = input.AccountAlias
198 tmpTxSummary.Inputs[i].AssetID = input.AssetID
199 tmpTxSummary.Inputs[i].AssetAlias = input.AssetAlias
200 tmpTxSummary.Inputs[i].Amount = input.Amount
201 tmpTxSummary.Inputs[i].Arbitrary = input.Arbitrary
203 for j, output := range annotatedTx.Outputs {
204 tmpTxSummary.Outputs[j].Type = output.Type
205 tmpTxSummary.Outputs[j].AccountID = output.AccountID
206 tmpTxSummary.Outputs[j].AccountAlias = output.AccountAlias
207 tmpTxSummary.Outputs[j].AssetID = output.AssetID
208 tmpTxSummary.Outputs[j].AssetAlias = output.AssetAlias
209 tmpTxSummary.Outputs[j].Amount = output.Amount
212 Txs = append(Txs, tmpTxSummary)
218 func FindTransactionsByAccount(annotatedTx *query.AnnotatedTx, accountID string) bool {
219 for _, input := range annotatedTx.Inputs {
220 if input.AccountID == accountID {
225 for _, output := range annotatedTx.Outputs {
226 if output.AccountID == accountID {
234 // GetTransactions get all walletDB transactions or unconfirmed transactions, and filter transactions by accountID and StartTxID optional
235 func (w *Wallet) GetTransactions(accountID string, StartTxID string, count uint, unconfirmed bool) ([]*query.AnnotatedTx, error) {
236 annotatedTxs := []*query.AnnotatedTx{}
237 annotatedTxs, err := w.Store.ListTransactions(accountID, StartTxID, count, unconfirmed)
242 newAnnotatedTxs := []*query.AnnotatedTx{}
243 for _, annotatedTx := range annotatedTxs {
244 annotateTxsAsset(w, []*query.AnnotatedTx{annotatedTx})
245 newAnnotatedTxs = append([]*query.AnnotatedTx{annotatedTx}, newAnnotatedTxs...)
249 sort.Sort(SortByTimestamp(newAnnotatedTxs))
251 sort.Sort(SortByHeight(newAnnotatedTxs))
254 return newAnnotatedTxs, nil
257 // GetAccountBalances return all account balances
258 func (w *Wallet) GetAccountBalances(accountID string, id string) ([]AccountBalance, error) {
259 return w.indexBalances(w.GetAccountUtxos(accountID, "", false, false, false))
262 // AccountBalance account balance
263 type AccountBalance struct {
264 AccountID string `json:"account_id"`
265 Alias string `json:"account_alias"`
266 AssetAlias string `json:"asset_alias"`
267 AssetID string `json:"asset_id"`
268 Amount uint64 `json:"amount"`
269 AssetDefinition map[string]interface{} `json:"asset_definition"`
272 func (w *Wallet) indexBalances(accountUTXOs []*account.UTXO) ([]AccountBalance, error) {
273 accBalance := make(map[string]map[string]uint64)
274 balances := []AccountBalance{}
276 for _, accountUTXO := range accountUTXOs {
277 assetID := accountUTXO.AssetID.String()
278 if _, ok := accBalance[accountUTXO.AccountID]; ok {
279 if _, ok := accBalance[accountUTXO.AccountID][assetID]; ok {
280 accBalance[accountUTXO.AccountID][assetID] += accountUTXO.Amount
282 accBalance[accountUTXO.AccountID][assetID] = accountUTXO.Amount
285 accBalance[accountUTXO.AccountID] = map[string]uint64{assetID: accountUTXO.Amount}
289 var sortedAccount []string
290 for k := range accBalance {
291 sortedAccount = append(sortedAccount, k)
293 sort.Strings(sortedAccount)
295 for _, id := range sortedAccount {
296 var sortedAsset []string
297 for k := range accBalance[id] {
298 sortedAsset = append(sortedAsset, k)
300 sort.Strings(sortedAsset)
302 for _, assetID := range sortedAsset {
303 alias := w.AccountMgr.GetAliasByID(id)
304 targetAsset, err := w.AssetReg.GetAsset(assetID)
309 assetAlias := *targetAsset.Alias
310 balances = append(balances, AccountBalance{
314 AssetAlias: assetAlias,
315 Amount: accBalance[id][assetID],
316 AssetDefinition: targetAsset.DefinitionMap,
324 // GetAccountVotes return all account votes
325 func (w *Wallet) GetAccountVotes(accountID string, id string) ([]AccountVotes, error) {
326 return w.indexVotes(w.GetAccountUtxos(accountID, "", false, false, true))
329 type voteDetail struct {
330 Vote string `json:"vote"`
331 VoteNumber uint64 `json:"vote_number"`
334 // AccountVotes account vote
335 type AccountVotes struct {
336 AccountID string `json:"account_id"`
337 Alias string `json:"account_alias"`
338 TotalVoteNumber uint64 `json:"total_vote_number"`
339 VoteDetails []voteDetail `json:"vote_details"`
342 func (w *Wallet) indexVotes(accountUTXOs []*account.UTXO) ([]AccountVotes, error) {
343 accVote := make(map[string]map[string]uint64)
344 votes := []AccountVotes{}
346 for _, accountUTXO := range accountUTXOs {
347 if accountUTXO.AssetID != *consensus.BTMAssetID || accountUTXO.Vote == nil {
350 xpub := hex.EncodeToString(accountUTXO.Vote)
351 if _, ok := accVote[accountUTXO.AccountID]; ok {
352 accVote[accountUTXO.AccountID][xpub] += accountUTXO.Amount
354 accVote[accountUTXO.AccountID] = map[string]uint64{xpub: accountUTXO.Amount}
359 var sortedAccount []string
360 for k := range accVote {
361 sortedAccount = append(sortedAccount, k)
363 sort.Strings(sortedAccount)
365 for _, id := range sortedAccount {
366 var sortedXpub []string
367 for k := range accVote[id] {
368 sortedXpub = append(sortedXpub, k)
370 sort.Strings(sortedXpub)
372 voteDetails := []voteDetail{}
373 voteTotal := uint64(0)
374 for _, xpub := range sortedXpub {
375 voteDetails = append(voteDetails, voteDetail{
377 VoteNumber: accVote[id][xpub],
379 voteTotal += accVote[id][xpub]
381 alias := w.AccountMgr.GetAliasByID(id)
382 votes = append(votes, AccountVotes{
385 VoteDetails: voteDetails,
386 TotalVoteNumber: voteTotal,