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

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

 区块链基础架构模型

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

 区块链的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;

}

}

98
110
0
31

相关资讯

  1. 1、天龙八部3D手游新资料片上线125等级上限调整4450
  2. 2、君海游戏《代号F》CJ确定终版名字痴恋手游终有归属2481
  3. 3、《乱轰三国志》新资料片“富可敌国”首曝805
  4. 4、《霹雳江湖》逆转乾坤魔吞十二宫苍鹰能力解析3260
  5. 5、为什么中国玩家比较强?《巨龙之战》国际服观察2719
  6. 6、《纯情女仆坏少爷》新版本亮点介绍翅膀技能酷炫拽263
  7. 7、红色经典网游传承抗战3D正式更名《抗战:枪战传说》869
  8. 8、《白发魔女传》新版本来袭橙装称号结婚你要的都有321
  9. 9、《驯龙三国》炫富活动来袭这组服务器我罩的4776
  10. 10、《暖暖环游世界》百美图再度来袭古风美装来啦3548
全部评论(0)
我也有话说
0
收藏
点赞
顶部