剥开比原看代码16:比原是如何经过/list-transactions显示交易信息的

做者:freewind前端

比原项目仓库:git

Github地址:https://github.com/Bytom/bytomgithub

Gitee地址:https://gitee.com/BytomBlockchain/bytom数据库

在前一篇文章中,咱们试图理解比原是如何交易的,可是因为内容太多,咱们把它分红了几个小问题,并在前一篇解决了“在dashboard中如何提交交易信息”,以及“比原后台是如何操做的”。json

在本文咱们继续研究下一个问题:在提交的交易成功完成后,前端会以列表的方式显示交易信息,它是如何拿到后台的数据的?也就是下图是如何实现的:后端

因为它同时涉及到了前端和后端,因此咱们一样把它分红了两个小问题:api

  1. 前端是如何获取交易数据并显示出来的?
  2. 后端是如何找到交易数据的?

下面依次解决。app

前端是如何获取交易数据并显示出来的?

咱们先在比原的前端代码库中寻找。因为这个功能是“列表分页”显示,这让我想起了前面有一个相似的功能是分页显示余额,那里用的是src/features/shared/components/BaseList提供的通用组件,因此这边应该也是同样。函数

通过查看,果真在src/features/transactions/components/下面发现了List.jsx文件,且目录结构跟src/features/balances/components/很是类似,再大略看一下代码,就能肯定使用了同样的方法。ui

可是若是回想一下,过程彷佛仍是有点不一样。在显示余额那里,是咱们手动点击了左侧栏的菜单,使得前端的路由转到了/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)
}

从这个方法的参数能够看到,前端是能够传过来idaccount_iddetail这三个参数的。而在本文的例子中,由于是直接跳转到/transactions的路由,因此什么参数也没有传上来。

我把代码分红了两块,一些错误处理的部分被我省略了。依次讲解:

  1. 第1处是想根据参数来获取transactions。若是account_id有值,则拿它去取,即某个账户拥有的交易;不然的话,用id去取,这个id指的是交易的id。若是这两个都没有值,应该是在第二个分支中处理,即a.wallet.GetTransactionsByTxID应该也能够处理参数为空字符串的状况
  2. 第2处代码,若是detailfalse(若是前端没传值,也应该是默认值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. 第1处代码是遍历数据库中以TxPrefix为前缀的值,其中TxPrefixTXS:,下面要进行遍历。这里的DB无疑是wallet这个leveldb
  2. 第2处开始进行遍历
  3. 第3处是把每个元素的Value拿出来,它是JSON格式的,把它转成AnnotatedTx对象。txIter的每个元素是一个key-pair,有Key(),也有Value(),这里只用到了Value()
  4. 第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)
}

其中TxIndexPrefixTID:

calcAnnotatedKey(formatKey)的定义是:

wallet/indexer.go#L53-L55

func calcAnnotatedKey(formatKey string) []byte {
    return []byte(TxPrefix + formatKey)
}

其中TxPrefix的值是TXS:

咱们再进入listTransactions的第2处,即detail那里。若是detailfalse,则只须要摘要,因此会调用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返回给前端。

那么今天的这个小问题就算解决了,因为有以前的经验能够利用,因此感受就比较简单了。

相关文章
相关标签/搜索