原文地址:http://blog.csdn.net/xiangzhihong8/article/details/53931213

本文90%来着于翻译,原文地址:http://java-lang-programming.com/en/articles/29

概述

MerkleTree被广泛的应用在比特币技术中,本文旨在通过代码实现一个简单的MerkleTree,并计算出Merkle tree的 TreeRoot。 
Merkle Tree 是一种数据结构,用于验证在计算机之间和之间存储,处理和传输的任何类型的数据。 
目前,Merkle树的主要用途是确保从对等网络中接收的数据块未受损和未改变,和检查其他对等网络没有撒谎发送假数据块。 

Merkle Tree应用举例

  • 比特币
  • Git
  • Amazon’s Dynamo
  • Gassandra

比特币中的应用

比特币中每个块中都包含了所有交易的集合签名,这个签名就是用Merkle tree实现的,Merkle树用于比特币以汇总块中的所有事务,产生整个事务集合的整体数字指纹,提供非常有效的过程来验证事务是否包括在块中。 
 
Merkle树一个很重要的用处是检查块中是否包含指定的交易,Merkle树是通过递归哈希节点对来构造的,直到只有一个哈希。 

Merkle tree 代码实现

哈希树的跟节点称为Merkle根,Merkle树可以仅用log2(N)的时间复杂度检查任何一个数据元素是否包含在树中:

package test;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
public class MerkleTrees {
// transaction List
List<String> txList;
// Merkle Root
String root; /**
* constructor
* @param txList transaction List 交易List
*/
public MerkleTrees(List<String> txList) {
this.txList = txList;
root = "";
} /**
* execute merkle_tree and set root.
*/
public void merkle_tree() { List<String> tempTxList = new ArrayList<String>(); for (int i = 0; i < this.txList.size(); i++) {
tempTxList.add(this.txList.get(i));
} List<String> newTxList = getNewTxList(tempTxList); while (newTxList.size() != 1) {
newTxList = getNewTxList(newTxList);
} this.root = newTxList.get(0);
} /**
* return Node Hash List.
* @param tempTxList
* @return
*/
private List<String> getNewTxList(List<String> tempTxList) { List<String> newTxList = new ArrayList<String>();
int index = 0;
while (index < tempTxList.size()) {
// left
String left = tempTxList.get(index);
index++;
// right
String right = "";
if (index != tempTxList.size()) {
right = tempTxList.get(index);
}
// sha2 hex value
String sha2HexValue = getSHA2HexValue(left + right);
newTxList.add(sha2HexValue);
index++; } return newTxList;
} /**
* Return hex string
* @param str
* @return
*/
public String getSHA2HexValue(String str) {
byte[] cipher_byte;
try{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(str.getBytes());
cipher_byte = md.digest();
StringBuilder sb = new StringBuilder(2 * cipher_byte.length);
for(byte b: cipher_byte) {
sb.append(String.format("%02x", b&0xff) );
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} return "";
} /**
* Get Root
* @return
*/
public String getRoot() {
return this.root;
} }

数据准备

我们将交易的数据,放入到List中:

List<String> tempTxList = new ArrayList<String>();
tempTxList.add("a");
tempTxList.add("b");
tempTxList.add("c");
tempTxList.add("d");
tempTxList.add("e");

实现过程

  • 准备交易数据
  • 计算出每个数据的hash值,从左到右逐步组成树的左右节点
  • 执行循环知道最后只剩下一个数据 

private List<String> getNewTxList(List<String> tempTxList) {
List<String> newTxList = new ArrayList<String>();
int index = 0;
while (index < tempTxList.size()) {
// left
String left = tempTxList.get(index);
index++;
// right
String right = "";
if (index != tempTxList.size()) {
right = tempTxList.get(index);
}
// sha2 hex value
String sha2HexValue = getSHA2HexValue(left + right);
newTxList.add(sha2HexValue);
index++;
}

测试

package test;
import java.util.ArrayList;
import java.util.List;
public class App {
public static void main(String [] args) {
List<String> tempTxList = new ArrayList<String>();
tempTxList.add("a");
tempTxList.add("b");
tempTxList.add("c");
tempTxList.add("d");
tempTxList.add("e"); MerkleTrees merkleTrees = new MerkleTrees(tempTxList);
merkleTrees.merkle_tree();
System.out.println("root : " + merkleTrees.getRoot());
}
}

执行结果 
 
本文从简单二叉树的形式实现了简单的MerkleTree,计算出TreeRoot,但是实际上的的MerkleTree不拘谨与二叉树还可能是多叉树。

区块链的java实现的更多相关文章

  1. 远光武汉研发中心区块链事业部Java面试总结

    面试在约定的时间准时进行,也是采用腾讯会议远程面试的方式.但是这是我第一次遇到面试官未打开摄像头的情况,后面经过沟通,双方都打开摄像头进行交流. 之前了解这个岗位主要是区块链相关的Java开发,所以事 ...

  2. 区块链使用Java,以太坊 Ethereum, web3j, Spring Boot

    Blockchain is one of the buzzwords in IT world during some last months. This term is related to cryp ...

  3. 创建自己的区块链合约java版web3接口——以太坊代币(四)

    texas-web3j-solidity项目是一个java版本的,使用web3j包和eth网络交互的小程序. 主要实现了以下功能: 1.发布合约 2.发起转账 3.查询交易 4.调用智能合约方法 te ...

  4. 以太坊区块链Java(EthereumJ)学习笔记:概述

    本系列文章介绍以太坊区块链基于Java语言的解决方案.通过介绍EthereumJ定义的主要模块和Class,希望为大家学习和使用EthereumJ提供一些帮助. 整体架构 以太坊的Java解决方案主要 ...

  5. 只用120行Java代码写一个自己的区块链

    区块链是目前最热门的话题,广大读者都听说过比特币,或许还有智能合约,相信大家都非常想了解这一切是如何工作的.这篇文章就是帮助你使用 Java 语言来实现一个简单的区块链,用不到 120 行代码来揭示区 ...

  6. java开发区块链只需150行代码

    本文目的是通过java实战开发教程理解区块链是什么.将通过实战入门学习,用Java自学开发一个很基本的区块链,并在此基础上能扩展如web框架应用等.这个基本的java区块链也实现简单的工作量证明系统. ...

  7. 【原】用Java编写第一个区块链(一)

    写这篇随笔主要是尝试帮助自己了解如何学习区块链技术开发. [本文禁止任何形式的全文粘贴式转载,本文来自 zacky31 的随笔] 目标: 创建一个最基本的"区块链" 实现一个简单的 ...

  8. 【原】用Java编写第一个区块链(二)

    这篇文章将去介绍如何使用区块链进行交易. [本文禁止任何形式的全文粘贴式转载,本文来自 zacky31 的随笔] 目标: 在上一篇文章中,我们已经创建了一个可信任的区块链.但是目前所创建的链中包含的有 ...

  9. 用Hyperledger Fabric(超级账本)来构建Java语言开发区块链的环境

    面向 Java 开发人员的链代码简介 您或许听说过区块链,但可能不确定它对 Java™ 开发人员有何用.本教程将帮助大家解惑.我将分步展示如何使用 Hyperledger Fabric v0.6 来构 ...

随机推荐

  1. SystemVerilog Event Scheduling Algorithm

    While simulating System Verilog design and its test-bench including assertions, events has to be dyn ...

  2. 【转载】Hybrid APP了解

    原文:http://uikoo9.com/blog/detail/hpp 不错的hybrid app框架:http://www.dcloud.io/case/#group-1 HPP hybirdAp ...

  3. guess-number-higher-or-lower-ii

    // https://discuss.leetcode.com/topic/51353/simple-dp-solution-with-explanation // https://en.wikipe ...

  4. 使用Java、Matlab画多边形闭合折线图

    由于写论文要将“哈密顿回路问题(TSP)”的求解中间结果表示出来,查了一下使用程序画多边形图形.现在在总结一下,这个图是“由给定节点首尾相连的”闭合多边形. 1.使用matlab作闭合多边形图 没有找 ...

  5. go语言之进阶篇非结构体匿名字段

    1.非结构体匿名字段 示例 : package main import "fmt" type mystr string //自定义类型,给一个类型改名 type Person st ...

  6. App优化 Systrace

    简介 trace [tres] vt.跟踪,追踪; 追溯,探索; 探索; 查找; n.痕迹; 痕迹,踪迹; 微量,极少量; 1 1   1 trace [tres] vt.跟踪,追踪; 追溯,探索; ...

  7. jQuery EasyUI 教程-Tooltip(提示框)

    <!DOCTYPE html> <html> <head> <title>jQuery Easy UI</title> <meta c ...

  8. oauth2-server-php for windows 的那些坑 (研究中...)

    oauth2-server-php for windows 的那些坑 在windwos 环境下,使用vs2017 for php 工具进行调试时,总是搞不出来, 于是分析了一下原因, 首先,oauth ...

  9. [Javascript] Function Expression Ex, Changing Declarations to Expressions

    Inside the Haunted Hickory House file, developers for the Forest of Function Expressions Theme Park ...

  10. 遭遇java.lang.NoClassDefFoundError: org/apache/tomcat/PeriodicEventListener

    前天还正常的程序,今天忽然无法启动了,MyEclipse的Console提醒我如下错误: 严重: Error deploying web application directory rttsbizja ...