区块链的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、陈晓陈妍希夫妻俩久违同框,看向老公的脸都是羞涩和崇拜3860
  2. 2、谢贤与前妻现身,在狄波拉丈夫面前开玩笑,一个举动暴露三人关系245
  3. 3、小柯凭《北爱》主题曲获赞舒淇叹“爱情奢侈”4211
  4. 4、1921晒角色海报,刘昊然穿长衫温润儒雅,我却被王俊凯的造型圈粉3612
  5. 5、张允珠将出演韩剧版《纸钞屋》翻牌自西班牙同名电视剧5071
  6. 6、郑嘉颖小22岁娇妻信基督,遵守婚前守贞,却疑与老公奉子成婚?4911
  7. 7、是枝裕和等日本演艺圈各界人士纷纷致辞悼念老戏骨树木希林973
  8. 8、林允4年前《美人鱼》选秀照被扒出,身材火辣,那时候她清纯惊艳4500
  9. 9、网传《山河令》有两版结局,编剧透露最后是和:要让观众开心一点2725
  10. 10、肖战杨紫新剧有确切消息!腾讯视频经理透露时间,说完后迅速删博3204
全部评论(0)
我也有话说
0
收藏
点赞
顶部