作者:freewind
比原項目倉庫:
Github地址:https://github.com/Bytom/bytom
Gitee地址:https://gitee.com/BytomBlockc...
在前一篇文章中,我們試圖理解比原是如何交易的,但是由於內容太多,我們把它分成了幾個小問題,並在前一篇解決了“在dashboard中如何提交交易資訊”,以及“比原後台是如何操作的”。
在本文我們繼續研究下一個問題:在提交的交易成功完成後,前端會以列表的方式顯示交易資訊,它是如何拿到背景資料的?也就是是如何?的:
由於它同時涉及到了前端和後端,所以我們同樣把它分成了兩個小問題:
- 前端是如何擷取交易資料並顯示出來的?
- 後端是如何找到交易資料的?
下面依次解決。
前端是如何擷取交易資料並顯示出來的?
我們先在比原的前端程式碼程式庫中尋找。由於這個功能是“列表分頁”顯示,這讓我想起了前面有一個類似的功能是分頁顯示餘額,那裡用的是src/features/shared/components/BaseList提供的萬用群組件,所以這邊應該也是一樣。
經過查看,果然在src/features/transactions/components/下面發現了List.jsx檔案,且目錄結構跟src/features/balances/components/非常相似,再大略看一下代碼,就能確定使用了一樣的方法。
但是如果回想一下,過程似乎還是有點不同。在顯示餘額那裡,是我們手動點擊了左側欄的菜單,使得前端的路由轉到了/balances,然後由
src/features/shared/routes.js#L5-L44
const makeRoutes = (store, type, List, New, Show, options = {}) => { // ... return { path: options.path || type + 's', component: RoutingContainer, name: options.name || humanize(type + 's'), name_zh: options.name_zh, indexRoute: { component: List, onEnter: (nextState, replace) => { loadPage(nextState, replace) }, onChange: (_, nextState, replace) => { loadPage(nextState, replace) } }, childRoutes: childRoutes }}
中的onEnter或者onChange觸發了loadPage,最後一步步調用了後台介面/list-balances。而這次在本文的例子中,它是在提交了“提交交易”表單成功後,自動轉到了“列表顯示交易”的頁面,會不會同樣觸發onEnter或者onChange呢?
答案是會的,因為在前文中,當submitForm執行後,向背景最後一個請求/submit-transaction成功以後,會調用dealSignSubmitResp這個函數,而它的定義是:
src/features/transactions/actions.js#L120-L132
const dealSignSubmitResp = resp => { // ... dispatch(push({ pathname: '/transactions', state: { preserveFlash: true } }))}
可以看到,它最後也會切換前端路由到/transactions,跟顯示餘額那裡就是完全一樣的路線了。所以按照那邊的經驗,到最後一定會訪問背景/list-transactions介面。
這過程中的推導就不再詳說,需要的話可以看前面講解“比原是如何顯示餘額的”那篇文章。
最後拿到了後台返回的資料如何以表格形式顯示出來,在那篇文章中也提到,這裡也跳過。
後端是如何找到交易資料的?
當我們知道了前端會訪問背景/list-transactions介面後,我們就很容易的在比原的主專案倉庫中找到下面的代碼:
api/api.go#L164-L244
func (a *API) buildHandler() { // ... if a.wallet != nil { // ... m.Handle("/list-transactions", jsonHandler(a.listTransactions)) // ...}
可以看到,list-transactions對應的handler是a.listTransactions:
api/query.go#L83-L107
func (a *API) listTransactions(ctx context.Context, filter struct { ID string `json:"id"` AccountID string `json:"account_id"` Detail bool `json:"detail"`}) Response { transactions := []*query.AnnotatedTx{} var err error // 1. if filter.AccountID != "" { transactions, err = a.wallet.GetTransactionsByAccountID(filter.AccountID) } else { transactions, err = a.wallet.GetTransactionsByTxID(filter.ID) } // ... // 2. if filter.Detail == false { txSummary := a.wallet.GetTransactionsSummary(transactions) return NewSuccessResponse(txSummary) } return NewSuccessResponse(transactions)}
從這個方法的參數可以看到,前端是可以傳過來id,account_id和detail這三個參數的。而在本文的例子中,因為是直接跳轉到/transactions的路由,所以什麼參數也沒有傳上來。
我把代碼分成了兩塊,一些錯誤處理的部分被我省略了。依次講解:
- 第1處是想根據參數來擷取
transactions。如果account_id有值,則拿它去取,即某個帳戶擁有的交易;否則的話,用id去取,這個id指的是交易的id。如果這兩個都沒有值,應該是在第二個分支中處理,即a.wallet.GetTransactionsByTxID應該也可以處理參數為空白字串的情況
- 第2處代碼,如果
detail為false(如果前端沒傳值,也應該是預設值false,則將前面拿到的transactions變成摘要,只返回部分資訊;否則的話,返回完整資訊。
我們先進第1處代碼中的a.wallet.GetTransactionsByAccountID:
wallet/indexer.go#L505-L523
func (w *Wallet) GetTransactionsByAccountID(accountID string) ([]*query.AnnotatedTx, error) { annotatedTxs := []*query.AnnotatedTx{} // 1. txIter := w.DB.IteratorPrefix([]byte(TxPrefix)) defer txIter.Release() // 2. for txIter.Next() { // 3. annotatedTx := &query.AnnotatedTx{} if err := json.Unmarshal(txIter.Value(), &annotatedTx); err != nil { return nil, err } // 4. if findTransactionsByAccount(annotatedTx, accountID) { annotateTxsAsset(w, []*query.AnnotatedTx{annotatedTx}) annotatedTxs = append(annotatedTxs, annotatedTx) } } return annotatedTxs, nil}
這裡把代碼分成了4塊:
- 第1處代碼是遍曆資料庫中以
TxPrefix為首碼的值,其中TxPrefix為TXS:,下面要進行遍曆。這裡的DB無疑是wallet這個leveldb
- 第2處開始進行遍曆
- 第3處是把每一個元素的
Value拿出來,它是JSON格式的,把它轉成AnnotatedTx對象。txIter的每一個元素是一個key-pair,有Key(),也有Value(),這裡只用到了Value()
- 第4處是在當前的這個
annotatedTx對象中尋找,如果它的input或者output中包含的帳戶的id等於accountId,則它是我們需要的。後面再使用annotateTxsAsset方法把annotatedTx對象中的asset相關的屬性(比如alias等)補全。
其中AnnotatedTx的定義值得一看:
blockchain/query/annotated.go#L12-L22
type AnnotatedTx struct { ID bc.Hash `json:"tx_id"` Timestamp uint64 `json:"block_time"` BlockID bc.Hash `json:"block_hash"` BlockHeight uint64 `json:"block_height"` Position uint32 `json:"block_index"` BlockTransactionsCount uint32 `json:"block_transactions_count,omitempty"` Inputs []*AnnotatedInput `json:"inputs"` Outputs []*AnnotatedOutput `json:"outputs"` StatusFail bool `json:"status_fail"`}
它其實就是為了持有最後返回給前端的資料,通過給每個欄位添加JSON相關的annotation方便轉換成JSON。
如果前端沒有傳account_id參數,則會進入另一個分支,對應a.wallet.GetTransactionsByTxID(filter.ID):
wallet/indexer.go#L426-L450
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}
這個方法看起來挺長,實際上邏輯比較簡單。如果前端傳了txID,則會在wallet中尋找指定的id的交易對象;否則的話,取出全部(也就是本文的情況)。其中calcTxIndexKey(txID)的定義是:
wallet/indexer.go#L61-L63
func calcTxIndexKey(txID string) []byte { return []byte(TxIndexPrefix + txID)}
其中TxIndexPrefix是TID:。
calcAnnotatedKey(formatKey)的定義是:
wallet/indexer.go#L53-L55
func calcAnnotatedKey(formatKey string) []byte { return []byte(TxPrefix + formatKey)}
其中TxPrefix的值是TXS:。
我們再進入listTransactions的第2處,即detail那裡。如果detail為false,則只需要摘要,所以會調用a.wallet.GetTransactionsSummary(transactions):
wallet/indexer.go#L453-L486
func (w *Wallet) GetTransactionsSummary(transactions []*query.AnnotatedTx) []TxSummary { Txs := []TxSummary{} for _, annotatedTx := range transactions { tmpTxSummary := TxSummary{ Inputs: make([]Summary, len(annotatedTx.Inputs)), Outputs: make([]Summary, len(annotatedTx.Outputs)), ID: annotatedTx.ID, Timestamp: annotatedTx.Timestamp, } for i, input := range annotatedTx.Inputs { tmpTxSummary.Inputs[i].Type = input.Type tmpTxSummary.Inputs[i].AccountID = input.AccountID tmpTxSummary.Inputs[i].AccountAlias = input.AccountAlias tmpTxSummary.Inputs[i].AssetID = input.AssetID tmpTxSummary.Inputs[i].AssetAlias = input.AssetAlias tmpTxSummary.Inputs[i].Amount = input.Amount tmpTxSummary.Inputs[i].Arbitrary = input.Arbitrary } for j, output := range annotatedTx.Outputs { tmpTxSummary.Outputs[j].Type = output.Type tmpTxSummary.Outputs[j].AccountID = output.AccountID tmpTxSummary.Outputs[j].AccountAlias = output.AccountAlias tmpTxSummary.Outputs[j].AssetID = output.AssetID tmpTxSummary.Outputs[j].AssetAlias = output.AssetAlias tmpTxSummary.Outputs[j].Amount = output.Amount } Txs = append(Txs, tmpTxSummary) } return Txs}
這一段的代碼相當直白,就是從transactions的元素中取出部分比較重要的資訊,組成新的TxSummary對象,返回過去。最後,這些對象再變成JSON返回給前端。
那麼今天的這個小問題就算解決了,由於有之前的經驗可以利用,所以感覺就比較簡單了。