OSDN Git Service

merge unconfirmed trsanction into transactions
authoroysheng <oysheng@bytom.io>
Tue, 5 Jun 2018 03:29:25 +0000 (11:29 +0800)
committeroysheng <oysheng@bytom.io>
Tue, 5 Jun 2018 03:29:25 +0000 (11:29 +0800)
api/api.go
api/query.go
cmd/bytomcli/commands/bytomcli.go
cmd/bytomcli/commands/transaction.go
wallet/indexer.go
wallet/unconfirmed.go
wallet/wallet_test.go

index 461aabb..5a69318 100644 (file)
@@ -192,9 +192,6 @@ func (a *API) buildHandler() {
                m.Handle("/get-transaction", jsonHandler(a.getTransaction))
                m.Handle("/list-transactions", jsonHandler(a.listTransactions))
 
-               m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
-               m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
-
                m.Handle("/list-balances", jsonHandler(a.listBalances))
                m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
 
@@ -221,8 +218,8 @@ func (a *API) buildHandler() {
        m.Handle("/submit-transaction", jsonHandler(a.submit))
        m.Handle("/estimate-transaction-gas", jsonHandler(a.estimateTxGas))
 
-       m.Handle("/get-mempool-transaction", jsonHandler(a.getMemPoolTx))
-       m.Handle("/list-mempool-transactions", jsonHandler(a.listMemPoolTxs))
+       m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
+       m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
        m.Handle("/decode-raw-transaction", jsonHandler(a.decodeRawTransaction))
 
        m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
index af06702..9405b48 100644 (file)
@@ -71,7 +71,7 @@ func (a *API) listBalances(ctx context.Context) Response {
 func (a *API) getTransaction(ctx context.Context, txInfo struct {
        TxID string `json:"tx_id"`
 }) Response {
-       transaction, err := a.wallet.GetTransactionByTxID(txInfo.TxID)
+       transaction, err := a.wallet.GetTransaction(txInfo.TxID)
        if err != nil {
                log.Errorf("getTransaction error: %v", err)
                return NewErrorResponse(err)
@@ -82,17 +82,33 @@ func (a *API) getTransaction(ctx context.Context, txInfo struct {
 
 // POST /list-transactions
 func (a *API) listTransactions(ctx context.Context, filter struct {
-       ID        string `json:"id"`
-       AccountID string `json:"account_id"`
-       Detail    bool   `json:"detail"`
+       ID          string `json:"id"`
+       AccountID   string `json:"account_id"`
+       Detail      bool   `json:"detail"`
+       Unconfirmed bool   `json:"unconfirmed"`
 }) Response {
        transactions := []*query.AnnotatedTx{}
        var err error
+       var transaction *query.AnnotatedTx
 
-       if filter.AccountID != "" {
-               transactions, err = a.wallet.GetTransactionsByAccountID(filter.AccountID)
+       if filter.ID != "" {
+               if filter.Unconfirmed {
+                       transaction, err = a.wallet.GetUnconfirmedTxByTxID(filter.ID)
+               } else {
+                       transaction, err = a.wallet.GetTransactionByTxID(filter.ID)
+               }
+
+               if err != nil {
+                       log.Errorf("GetTransaction: %v", err)
+                       return NewErrorResponse(err)
+               }
+               transactions = []*query.AnnotatedTx{transaction}
        } else {
-               transactions, err = a.wallet.GetTransactionsByTxID(filter.ID)
+               if filter.Unconfirmed {
+                       transactions, err = a.wallet.GetUnconfirmedTxs(filter.AccountID)
+               } else {
+                       transactions, err = a.wallet.GetTransactions(filter.AccountID)
+               }
        }
 
        if err != nil {
@@ -108,36 +124,7 @@ func (a *API) listTransactions(ctx context.Context, filter struct {
 }
 
 // POST /get-unconfirmed-transaction
-func (a *API) getUnconfirmedTx(ctx context.Context, txInfo struct {
-       TxID string `json:"tx_id"`
-}) Response {
-       transaction, err := a.wallet.GetUnconfirmedTxByTxID(txInfo.TxID)
-       if err != nil {
-               log.Errorf("getTransaction error: %v", err)
-               return NewErrorResponse(err)
-       }
-
-       return NewSuccessResponse(transaction)
-}
-
-// POST /list-unconfirmed-transactions
-func (a *API) listUnconfirmedTxs(ctx context.Context, filter struct {
-       AccountID string `json:"account_id"`
-}) Response {
-       transactions := []*query.AnnotatedTx{}
-       var err error
-
-       transactions, err = a.wallet.GetUnconfirmedTxs(filter.AccountID)
-       if err != nil {
-               log.Errorf("listTransactions: %v", err)
-               return NewErrorResponse(err)
-       }
-
-       return NewSuccessResponse(transactions)
-}
-
-// POST /get-mempool-transaction
-func (a *API) getMemPoolTx(ctx context.Context, filter struct {
+func (a *API) getUnconfirmedTx(ctx context.Context, filter struct {
        TxID chainjson.HexBytes `json:"tx_id"`
 }) Response {
        var tmpTxID [32]byte
@@ -175,8 +162,8 @@ type unconfirmedTxsResp struct {
        TxIDs []bc.Hash `json:"tx_ids"`
 }
 
-// POST /list-mempool-transactions
-func (a *API) listMemPoolTxs(ctx context.Context) Response {
+// POST /list-unconfirmed-transactions
+func (a *API) listUnconfirmedTxs(ctx context.Context) Response {
        txIDs := []bc.Hash{}
 
        txPool := a.chain.GetTxPool()
index f7efc4f..dd1abf9 100644 (file)
@@ -128,9 +128,6 @@ func AddCommands() {
 
        BytomcliCmd.AddCommand(getUnconfirmedTransactionCmd)
        BytomcliCmd.AddCommand(listUnconfirmedTransactionsCmd)
-
-       BytomcliCmd.AddCommand(getMemPoolTransactionCmd)
-       BytomcliCmd.AddCommand(listMemPoolTransactionsCmd)
        BytomcliCmd.AddCommand(decodeRawTransactionCmd)
 
        BytomcliCmd.AddCommand(listUnspentOutputsCmd)
@@ -198,10 +195,6 @@ func AddTemplateFunc() {
 
                getTransactionCmd.Name(),
                listTransactionsCmd.Name(),
-
-               getUnconfirmedTransactionCmd.Name(),
-               listUnconfirmedTransactionsCmd.Name(),
-
                listUnspentOutputsCmd.Name(),
                listBalancesCmd.Name(),
        }
index abbbd01..38b5101 100644 (file)
@@ -30,8 +30,6 @@ func init() {
        listTransactionsCmd.PersistentFlags().StringVar(&txID, "id", "", "transaction id")
        listTransactionsCmd.PersistentFlags().StringVar(&account, "account_id", "", "account id")
        listTransactionsCmd.PersistentFlags().BoolVar(&detail, "detail", false, "list transactions details")
-
-       listUnconfirmedTransactionsCmd.PersistentFlags().StringVar(&account, "account_id", "", "account id")
 }
 
 var (
@@ -368,49 +366,7 @@ var listUnconfirmedTransactionsCmd = &cobra.Command{
        Short: "list unconfirmed transactions hashes",
        Args:  cobra.NoArgs,
        Run: func(cmd *cobra.Command, args []string) {
-               filter := struct {
-                       AccountID string `json:"account_id"`
-               }{AccountID: account}
-
-               data, exitCode := util.ClientCall("/list-unconfirmed-transactions", &filter)
-               if exitCode != util.Success {
-                       os.Exit(exitCode)
-               }
-
-               printJSONList(data)
-       },
-}
-
-var getMemPoolTransactionCmd = &cobra.Command{
-       Use:   "get-mempool-transaction <hash>",
-       Short: "get mempool transaction by matching the given transaction hash",
-       Args:  cobra.ExactArgs(1),
-       Run: func(cmd *cobra.Command, args []string) {
-               txID, err := hex.DecodeString(args[0])
-               if err != nil {
-                       jww.ERROR.Println(err)
-                       os.Exit(util.ErrLocalExe)
-               }
-
-               txInfo := &struct {
-                       TxID chainjson.HexBytes `json:"tx_id"`
-               }{TxID: txID}
-
-               data, exitCode := util.ClientCall("/get-mempool-transaction", txInfo)
-               if exitCode != util.Success {
-                       os.Exit(exitCode)
-               }
-
-               printJSON(data)
-       },
-}
-
-var listMemPoolTransactionsCmd = &cobra.Command{
-       Use:   "list-mempool-transactions",
-       Short: "list mempool transactions hashes",
-       Args:  cobra.NoArgs,
-       Run: func(cmd *cobra.Command, args []string) {
-               data, exitCode := util.ClientCall("/list-mempool-transactions")
+               data, exitCode := util.ClientCall("/list-unconfirmed-transactions")
                if exitCode != util.Success {
                        os.Exit(exitCode)
                }
index 72ce8af..0073274 100644 (file)
@@ -20,6 +20,11 @@ import (
        "github.com/bytom/protocol/bc/types"
 )
 
+var (
+       // ErrNotFoundTx means errors occurred in actions
+       ErrNotFoundTx = errors.New("not found transaction in the wallet db")
+)
+
 type rawOutput struct {
        OutputID bc.Hash
        bc.AssetAmount
@@ -406,11 +411,26 @@ transactionLoop:
        return annotatedTxs
 }
 
+// GetTransaction search confirmed or unconfirmed transaction by txID
+func (w *Wallet) GetTransaction(txID string) (*query.AnnotatedTx, error) {
+       annotatedTx, err := w.GetTransactionByTxID(txID)
+       if errors.Root(err) != ErrNotFoundTx {
+               return nil, err
+       }
+
+       annotatedTx, err = w.GetUnconfirmedTxByTxID(txID)
+       if err != nil {
+               return nil, err
+       }
+
+       return annotatedTx, nil
+}
+
 // GetTransactionByTxID get transaction by txID
 func (w *Wallet) GetTransactionByTxID(txID string) (*query.AnnotatedTx, error) {
        formatKey := w.DB.Get(calcTxIndexKey(txID))
        if formatKey == nil {
-               return nil, fmt.Errorf("No transaction(tx_id=%s) ", txID)
+               return nil, errors.WithData(ErrNotFoundTx, "not found tx=%s from blockchain", txID)
        }
 
        annotatedTx := &query.AnnotatedTx{}
@@ -422,33 +442,6 @@ func (w *Wallet) GetTransactionByTxID(txID string) (*query.AnnotatedTx, error) {
        return annotatedTx, nil
 }
 
-// GetTransactionsByTxID get account txs by account tx ID
-func (w *Wallet) GetTransactionsByTxID(txID string) ([]*query.AnnotatedTx, error) {
-       annotatedTxs := []*query.AnnotatedTx{}
-       formatKey := ""
-
-       if txID != "" {
-               rawFormatKey := w.DB.Get(calcTxIndexKey(txID))
-               if rawFormatKey == nil {
-                       return nil, fmt.Errorf("No transaction(txid=%s) ", txID)
-               }
-               formatKey = string(rawFormatKey)
-       }
-
-       txIter := w.DB.IteratorPrefix(calcAnnotatedKey(formatKey))
-       defer txIter.Release()
-       for txIter.Next() {
-               annotatedTx := &query.AnnotatedTx{}
-               if err := json.Unmarshal(txIter.Value(), annotatedTx); err != nil {
-                       return nil, err
-               }
-               annotateTxsAsset(w, []*query.AnnotatedTx{annotatedTx})
-               annotatedTxs = append([]*query.AnnotatedTx{annotatedTx}, annotatedTxs...)
-       }
-
-       return annotatedTxs, nil
-}
-
 // GetTransactionsSummary get transactions summary
 func (w *Wallet) GetTransactionsSummary(transactions []*query.AnnotatedTx) []TxSummary {
        Txs := []TxSummary{}
@@ -501,9 +494,10 @@ func findTransactionsByAccount(annotatedTx *query.AnnotatedTx, accountID string)
        return false
 }
 
-// GetTransactionsByAccountID get account txs by account ID
-func (w *Wallet) GetTransactionsByAccountID(accountID string) ([]*query.AnnotatedTx, error) {
+// GetTransactions get all walletDB transactions, and filter transactions by accountID optional
+func (w *Wallet) GetTransactions(accountID string) ([]*query.AnnotatedTx, error) {
        annotatedTxs := []*query.AnnotatedTx{}
+       annotatedAccTxs := []*query.AnnotatedTx{}
 
        txIter := w.DB.IteratorPrefix([]byte(TxPrefix))
        defer txIter.Release()
@@ -513,12 +507,16 @@ func (w *Wallet) GetTransactionsByAccountID(accountID string) ([]*query.Annotate
                        return nil, err
                }
 
+               annotateTxsAsset(w, []*query.AnnotatedTx{annotatedTx})
+               annotatedTxs = append(annotatedTxs, annotatedTx)
                if findTransactionsByAccount(annotatedTx, accountID) {
-                       annotateTxsAsset(w, []*query.AnnotatedTx{annotatedTx})
-                       annotatedTxs = append(annotatedTxs, annotatedTx)
+                       annotatedAccTxs = append(annotatedAccTxs, annotatedTx)
                }
        }
 
+       if accountID != "" {
+               return annotatedAccTxs, nil
+       }
        return annotatedTxs, nil
 }
 
@@ -595,11 +593,11 @@ func (w *Wallet) indexBalances(accountUTXOs []account.UTXO) ([]AccountBalance, e
 
                        assetAlias := *targetAsset.Alias
                        balances = append(balances, AccountBalance{
-                               Alias: alias,
-                               AccountID: id,
-                               AssetID: assetID,
-                               AssetAlias: assetAlias,
-                               Amount: accBalance[id][assetID],
+                               Alias:           alias,
+                               AccountID:       id,
+                               AssetID:         assetID,
+                               AssetAlias:      assetAlias,
+                               Amount:          accBalance[id][assetID],
                                AssetDefinition: targetAsset.DefinitionMap,
                        })
                }
index 6e261db..2941023 100644 (file)
@@ -7,6 +7,7 @@ import (
        log "github.com/sirupsen/logrus"
 
        "github.com/bytom/blockchain/query"
+       "github.com/bytom/errors"
        "github.com/bytom/protocol/bc/types"
 )
 
@@ -96,6 +97,10 @@ func (w *Wallet) RescanWalletTxPool() []string {
 func (w *Wallet) GetUnconfirmedTxByTxID(txID string) (*query.AnnotatedTx, error) {
        annotatedTx := &query.AnnotatedTx{}
        txInfo := w.DB.Get(calcUnconfirmedKey(txID))
+       if txInfo == nil {
+               return nil, errors.WithData(ErrNotFoundTx, "not found tx=%s from txpool", txID)
+       }
+
        if err := json.Unmarshal(txInfo, annotatedTx); err != nil {
                return nil, err
        }
index 1da96f3..29d39d5 100644 (file)
@@ -89,12 +89,11 @@ func TestWalletUpdate(t *testing.T) {
                t.Fatal(err)
        }
 
-       want, err := w.GetTransactionsByTxID(tx.ID.String())
-       if len(want) != 1 {
+       if _, err := w.GetTransactionByTxID(tx.ID.String()); err != nil {
                t.Fatal(err)
        }
 
-       wants, err := w.GetTransactionsByTxID("")
+       wants, err := w.GetTransactions("")
        if len(wants) != 1 {
                t.Fatal(err)
        }
@@ -138,10 +137,10 @@ func mockTxData(utxos []*account.UTXO, testAccount *account.Account) (*txbuilder
 
 func mockWallet(walletDB dbm.DB, account *account.Manager, asset *asset.Registry, chain *protocol.Chain) *Wallet {
        wallet := &Wallet{
-               DB:                  walletDB,
-               AccountMgr:          account,
-               AssetReg:            asset,
-               chain:               chain,
+               DB:         walletDB,
+               AccountMgr: account,
+               AssetReg:   asset,
+               chain:      chain,
        }
        return wallet
 }