优质服务商推荐更多服务商>

区块链的java实现(详细代码解析)

3500

 区块链原本是比特币等加密货币存储数据的一种独特方式,是一种自引用的数据结构,用来存储大量交易信息,每条记录从后向前有序链接起来,具备公开透明、无法篡改、方便追溯的特点。实际上,这种特性也直接体现了整个比特币的特点,因此使用区块链来概括加密货币背后的技术实现是非常直观和恰当的。区块链是一项技术,加密货币是其开发实现的一类产品(含有代币,也有不含代币的区块链产品),不能等同或混淆。与加密货币相比,区块链这个名字抛开了代币的概念,更加形象化、技术化、去政治化,更适合作为一门技术去研究、去推广。

 区块链基础架构模型

一般说来,区块链系统由数据层、网络层、共识层、激励层、合约层和应用层组成。 其中,数据层封装了底层数据区块以及相关的数据加密和时间戳等技术;网络层则包括分布式组网机制、数据传播机制和数据验证机制等;共识层主要封装网络节点的各类共识算法;激励层将经济因素集成到区块链技术体系中来,主要包括经济激励的发行机制和分配机制等;合约层主要封装各类脚本、算法和智能合约,是区块链可编程特性的基础;应用层则封装了区块链的各种应用场景和案例。该模型中,基于时间戳的链式区块结构、分布式节点的共识机制、基于共识算力的经济激励和灵活可编程的智能合约是区块链技术最具代表性的创新点。

 区块链的java实现(详细代码解析)_设计制作_接口/总线/驱动

 区块链代码实现

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

package test;

import java.security.MessageDigest;

import java.u  TI l.ArrayList;

import java.u  TI l.List;

public class MerkleTrees {

// transac  TI on List

List《String》 txList;

// Merkle Root

String root;

/**

* constructor

* @param txList transac  TI on 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;

}

}

特别声明:本文仅供交流学习 , 版权归属原作者,并不代表蚂蚜网赞同其观点和对其真实性负责。若文章无意侵犯到您的知识产权,损害了您的利益,烦请与我们联系vmaya_gz@126.com,我们将在24小时内进行修改或删除。

相关推荐: