剥开比原看代码16:比原是如何通过/list-transactions显示交易信息的
作者:freewind
比原项目仓库:
Github地址:https://github.com/Bytom/bytom
Gitee地址:https://gitee.com/BytomBlockchain/bytom
在前一篇文章中,我们试图理解比原是如何交易的,但是由于内容太多,我们把它分成了几个小问题,并在前一篇解决了“在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接口后,我们就很容易的在比原的主项目仓库中找到下面的代码:
func (a *API) buildHandler() {
    // ...
    if a.wallet != nil {
        // ...
        m.Handle("/list-transactions", jsonHandler(a.listTransactions))
        // ...
}
可以看到,list-transactions对应的handler是a.listTransactions:
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:
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):
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)的定义是:
func calcTxIndexKey(txID string) []byte {
    return []byte(TxIndexPrefix + txID)
}
其中TxIndexPrefix是TID:。
calcAnnotatedKey(formatKey)的定义是:
func calcAnnotatedKey(formatKey string) []byte {
    return []byte(TxPrefix + formatKey)
}
其中TxPrefix的值是TXS:。
我们再进入listTransactions的第2处,即detail那里。如果detail为false,则只需要摘要,所以会调用a.wallet.GetTransactionsSummary(transactions):
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返回给前端。
那么今天的这个小问题就算解决了,由于有之前的经验可以利用,所以感觉就比较简单了。
剥开比原看代码16:比原是如何通过/list-transactions显示交易信息的的更多相关文章
- 剥开比原看代码13:比原是如何通过/list-balances显示帐户余额的?
		
作者:freewind 比原项目仓库: Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchai ...
 - 剥开比原看代码12:比原是如何通过/create-account-receiver创建地址的?
		
作者:freewind 比原项目仓库: Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchai ...
 - 剥开比原看代码11:比原是如何通过接口/create-account创建帐户的
		
作者:freewind 比原项目仓库: Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchai ...
 - 剥开比原看代码03:比原是如何监听p2p端口的
		
作者:freewind 比原项目仓库: Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchai ...
 - 剥开比原看代码10:比原是如何通过/create-key接口创建密钥的
		
作者:freewind 比原项目仓库: Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchai ...
 - 剥开比原看代码09:通过dashboard创建密钥时,前端的数据是如何传到后端的?
		
作者:freewind 比原项目仓库: Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchai ...
 - 剥开比原看代码08:比原的Dashboard是怎么做出来的?
		
作者:freewind 比原项目仓库: Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchai ...
 - Derek解读Bytom源码-protobuf生成比原核心代码
		
作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...
 - 《C++编程思想》第四章 初始化与清除(原书代码+习题+解答)
		
相关代码: 1. #include <stdio.h> class tree { int height; public: tree(int initialHeight); ~tree(); ...
 
随机推荐
- JSP FreeMarker Velocity 原理
			
JSP原理 JSP的运行原理:JSP 本质上是一个Servlet. 每个JSP 页面在第一次被访问时,JSP引擎将它翻译成一个Servlet 程序,然后再把这个 Servlet 源程序编译成Servl ...
 - 设计模式之State(状态)(转)
			
State的定义: 不同的状态,不同的行为;或者说,每个状态有着相应的行为. 何时使用? State模式在实际使用中比较多,适合"状态的切换".因为我们经常会使用If elseif ...
 - python的print函数自动换行及其避免
			
print函数自带换行功能,即在输出内容后会自动换行,但是有时我们并不需要这个功能,那怎么办呢?这时候就需要用到end这个参数了,使用方法参考下面这段打印$矩阵的代码: i = 1 while i&l ...
 - Kylin, Mondrian, Saiku系统的整合
			
本文主要介绍有赞数据团队为了满足在不同维度查看.分析重点指标的需求而搭建的OLAP分析工具.这个工具对Kylin.Mondrian以及Saiku做了一个整合,主要工作包括一些定制化的修改以及环境的配置 ...
 - TCP客户端图片上传服务端保存本地示例
			
//TCP客户端public class TCPClient { public static void main(String[] args)throws IOException { Socket s ...
 - Radio中REG
			
Auto REG/REG OFF在广播接收质量不好时,收音机首先仅调整到该广播电台当前发射的可选频率.但是,如果接收质量差到“该发射电台濒临消失”的程度,则收音机也会接收德国NDR1(北德意志广播电台 ...
 - Service_name 和Sid的区别
			
Service_name:该参数是由oracle8i引进的.在8i以前,使用SID来表示标识数据库的一个实例,但是在Oracle的并行环境中,一个数据库对应多个实例,这样就需要多个网络服务名,设置繁琐 ...
 - ELK日志分析系统
			
部署环境 192.168.1.147 kibana.logstash.Escluster-node-1 192.168.1.151 filebeat.Escluster-node-2.nginx 软件 ...
 - dell win 10笔记本关闭多媒体键,启用功能键的快捷方式
			
自从使用win 10之后,在使用快捷键方面就没有win 7之前来的顺手,比如F8切换投影仪,F5/F6调试等等.特地搜了下,使用Fn+Esc可以在功能键和多媒体键之间切换.
 - centos6下jbd2进程占用大量IO处理
			
刚在尝试重现一个bug时,好像在killed mysql一段时间之后,io一直很高,如下: 12:40:01 PM CPU %user %nice %system %iowait %steal %id ...