---
title: "用java简单分析下比特币区块链"
author: "it_node"
date: "2018-11-12T16:44:58Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2018-11-12T16:44:37Z"
id: 2433706
url: "https://it-node.iteye.com/blog/2433706"
---

我假设你已经对比特币的含义有一个模糊的概念，并且你对交易背后的机制有一个简单的理解：对地址进行支付（这是匿名的，因为它们不能直接链接到特定的个人），所有交易都是公开的。交易以块的形式收集，块在区块链中链接在一起。

你可以将区块链视为一个不断更新且可供所有人访问的大型数据库。你可以使用Bitcoin Core等软件下载完整的区块链。安装软件后，你的安装需要几周时间才能同步完成。请注意，在撰写本文时，区块链的大小超过130Gb，请考虑到这一点......

如果你有可用的区块链数据（不一定是整个区块链，你也可以使用它的子集），可以使用Java进行分析。你可以从头开始完成所有工作并从文件中读取原始数据等。让我们跳过此步骤并改为使用库。大多数编程语言都有几种选择。我将使用Java和bitcoinj库。这是一个大型库，可用于构建钱包，在线支付等应用程序。我将使用它的解析功能。

首先在[https://bitcoinj.github.io/](https://bitcoinj.github.io/)下载该库的jar文件（我正在使用[https://search.maven.org/remotecontent?filepath=org/bitcoinj/bitcoinj-core/0.14.4/bitcoinj-core-0.14.4-bundled.jar](https://search.maven.org/remotecontent?filepath=org%2Fbitcoinj%2Fbitcoinj-core%2F0.14.4%2Fbitcoinj-core-0.14.4-bundled.jar)）。然后，下载[SLF4J](https://www.slf4j.org/download.html)，解压缩，然后获取名为slf4j-simple-x.y.z.jar的文件（在我的例子中：slf4j-simple-1.7.25.jar）。将这两个jar文件添加到类路径中，你就可以开始了。

让我们从一个简单的例子开始：计算（然后绘制）每天的交易数量。这是代码，注释很多。

```
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
 
import org.bitcoinj.core.Block;
import org.bitcoinj.core.Context;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.utils.BlockFileLoader;
 
 
public class SimpleDailyTxCount {
 
    // Location of block files. This is where your blocks are located.
    // Check the documentation of Bitcoin Core if you are using
        // it, or use any other directory with blk*dat files. 
    static String PREFIX = "/path/to/your/bitcoin/blocks/";
 
        // A simple method with everything in it
    public void doSomething() {
 
        // Just some initial setup
        NetworkParameters np = new MainNetParams();
        Context.getOrCreate(MainNetParams.get());
 
        // We create a BlockFileLoader object by passing a list of files.
        // The list of files is built with the method buildList(), see
        // below for its definition.
        BlockFileLoader loader = new BlockFileLoader(np,buildList());
 
        // We are going to store the results in a map of the form 
                // day -> n. of transactions
        Map<String, Integer> dailyTotTxs = new HashMap<>();
 
        // A simple counter to have an idea of the progress
        int blockCounter = 0;
 
        // bitcoinj does all the magic: from the list of files in the loader
        // it builds a list of blocks. We iterate over it using the following
        // for loop
        for (Block block : loader) {
 
            blockCounter++;
            // This gives you an idea of the progress
            System.out.println("Analysing block "+blockCounter);
 
            // Extract the day from the block: we are only interested 
                        // in the day, not in the time. Block.getTime() returns 
                        // a Date, which is here converted to a string.
            String day = new SimpleDateFormat("yyyy-MM-dd").format(block.getTime());
 
            // Now we start populating the map day -> number of transactions.
            // Is this the first time we see the date? If yes, create an entry
            if (!dailyTotTxs.containsKey(day)) {
                dailyTotTxs.put(day, 0);
            }
 
            // The following is highly inefficient: we could simply do
            // block.getTransactions().size(), but is shows you
            // how to iterate over transactions in a block
            // So, we simply iterate over all transactions in the
            // block and for each of them we add 1 to the corresponding
            // entry in the map
            for ( Transaction tx: block.getTransactions() ) {               
                dailyTotTxs.put(day,dailyTotTxs.get(day)+1);
            }
        } // End of iteration over blocks
 
        // Finally, let's print the results
        for ( String d: dailyTotTxs.keySet()) {
            System.out.println(d+","+dailyTotTxs.get(d));
        }
    }  // end of doSomething() method.
 
 
    // The method returns a list of files in a directory according to a certain
    // pattern (block files have name blkNNNNN.dat)
    private List<File> buildList() {
            List<File> list = new LinkedList<File>();
            for (int i = 0; true; i++) {
                File file = new File(PREFIX + String.format(Locale.US, "blk%05d.dat", i));
                if (!file.exists())
                    break;
                list.add(file);
            }
        return list;
    }
 
 
    // Main method: simply invoke everything
    public static void main(String[] args) {
        SimpleDailyTxCount tb = new SimpleDailyTxCount();
        tb.doSomething();
    }
 
}
```

此代码将在屏幕上打印“日期，交易次数”形式的值列表。只需将输出重定向到文件并绘制它。你应该得到这样的东西（注意每日交易数量几乎呈指数增长）：

![](http://blog.hubwiz.com/2018/11/09/bitcoin-blockchain-java/dailyTxsLog.png)

我对这个库的性能印象非常深刻：使用上面的代码扫描整个区块链在我的笔记本电脑（2014 MacBook Pro）上花了大约35分钟，区块链存储在使用USB2端口连接的外部HD上。它最多占用了一个处理器和1 Gb RAM的大约100％。

一个稍微复杂的例子花了55分钟：计算交易规模的每日分布。这需要在上面的代码中添加另一个循环来检索所有交易输出（以及沿途的一些计数器）。区间是0-10美元，10-50美元，50-200美元，200-500美元，500-2000美元，2000+USD。

![](http://blog.hubwiz.com/2018/11/09/bitcoin-blockchain-java/TxSize.png)

======================================================================

分享一些以太坊、EOS、比特币等区块链相关的交互式在线编程实战教程：

> - [java以太坊开发教程](http://xc.hubwiz.com/course/5b2b6e82c02e6b6a59171de2?affid=1112juejin)，主要是针对java和android程序员进行区块链以太坊开发的web3j详解。
> - [python以太坊](http://xc.hubwiz.com/course/5b40462cc02e6b6a59171de4?affid=1112juejin)，主要是针对python工程师使用web3.py进行区块链以太坊开发的详解。
> - [php以太坊](http://xc.hubwiz.com/course/5b36629bc02e6b6a59171de3?affid=1112juejin)，主要是介绍使用php进行智能合约开发交互，进行账号创建、交易、转账、代币开发以及过滤器和交易等内容。
> - [以太坊入门教程](http://xc.hubwiz.com/course/5a952991adb3847553d205d1?affid=1112juejin)，主要介绍智能合约与dapp应用开发，适合入门。
> - [以太坊开发进阶教程](http://xc.hubwiz.com/course/5abbb7acc02e6b6a59171dd6?affid=1112juejin)，主要是介绍使用node.js、mongodb、区块链、ipfs实现去中心化电商DApp实战，适合进阶。
> - [C#以太坊](http://xc.hubwiz.com/course/5b6048c3c02e6b6a59171dee?affid=1112juejin)，主要讲解如何使用C#开发基于.Net的以太坊应用，包括账户管理、状态与交易、智能合约开发与交互、过滤器和交易等。
> - [EOS教程](http://xc.hubwiz.com/course/5b52c0a2c02e6b6a59171ded?affid=1112juejin)，本课程帮助你快速入门EOS区块链去中心化应用的开发，内容涵盖EOS工具链、账户与钱包、发行代币、智能合约开发与部署、使用代码与智能合约交互等核心知识点，最后综合运用各知识点完成一个便签DApp的开发。
> - [java比特币开发教程](http://xc.hubwiz.com/course/5bb35c90c02e6b6a59171df0?affid=1112juejin)，本课程面向初学者，内容即涵盖比特币的核心概念，例如区块链存储、去中心化共识机制、密钥与脚本、交易与UTXO等，同时也详细讲解如何在Java代码中集成比特币支持功能，例如创建地址、管理钱包、构造裸交易等，是Java工程师不可多得的比特币开发学习课程。
> - [php比特币开发教程](http://xc.hubwiz.com/course/5b9e779ac02e6b6a59171def?affid=1112juejin)，本课程面向初学者，内容即涵盖比特币的核心概念，例如区块链存储、去中心化共识机制、密钥与脚本、交易与UTXO等，同时也详细讲解如何在Php代码中集成比特币支持功能，例如创建地址、管理钱包、构造裸交易等，是Php工程师不可多得的比特币开发学习课程。
> - [tendermint区块链开发详解](http://xc.hubwiz.com/course/5bdec63ac02e6b6a59171df3?affid=1112iteye)，本课程适合希望使用tendermint进行区块链开发的工程师，课程内容即包括tendermint应用开发模型中的核心概念，例如ABCI接口、默克尔树、多版本状态库等，也包括代币发行等丰富的实操代码，是go语言工程师快速入门区块链开发的最佳选择。

这里是原文[用java简单分析下比特币区块链](http://blog.hubwiz.com/2018/11/09http://blog.hubwiz.com/2018/11/09/bitcoin-blockchain-java/)