();
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中:
ListtempTxList = new ArrayList();
tempTxList.add('a');
tempTxList.add('b');
tempTxList.add('c');
tempTxList.add('d');
tempTxList.add('e');准备交易数据
计算出每个数据的hash值,从左到右逐步组成树的左右节点
执行循环知道最后只剩下一个数据
private ListgetNewTxList(ListtempTxList) {
ListnewTxList = 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);
newTxList.add(sha2HexValue);
index++;
}
下面我们进行一个简单的测试
package test;
import java.util.ArrayList;
import java.util.List;
public class App {
public static void main(String [] args) {
ListtempTxList = new ArrayList();
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());
}
}