merkle树 java,如何通过java代码实现一个区块链MerkleTree

package test;

import java.security.MessageDigest;

import java.util.ArrayList;

import java.util.List;

public class MerkleTrees {

// transaction List

List txList;

// Merkle Root

String root;

/**

* constructor

* @param txList transaction List 交易List

*/

public MerkleTrees(List txList) {

txList = txList;

root = “”;

}

/**

* execute merkle_tree and set root.

*/

public void merkle_tree() {

List tempTxList = new ArrayList();

for (int i = 0; i < this.txList.size(); i++) {

add(this.txList.get(i));

}

List newTxList = getNewTxList(tempTxList);

while (newTxList.size() != 1) {

newTxList = getNewTxList(newTxList);

}

root = newTxList.get(0);

}

/**

* return Node Hash List.

* @param tempTxList

* @return

*/

private List getNewTxList(List tempTxList) {

List newTxList = new ArrayList();

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);

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”);

update(str.getBytes());

cipher_byte = md.digest();

StringBuilder sb = new StringBuilder(2 * cipher_byte.length);

for(byte b: cipher_byte) {

append(String.format(“%02x”, b&0xff) );

}

return sb.toString();

} catch (Exception e) {

printStackTrace();

}

return “”;

}

/**

* Get Root

* @return

*/

public String getRoot() {

return this.root;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值