区块:区块头+区块体
区块头:每个区块的前80个字节(640bits)。其中有6部分信息
version 版本号 4个字节
前一个区块的hash 32个字节
本区块所有交易产生的MerkleRoot 32个字节
时间戳 4个字节
新时间戳要大于11个区块平均时间戳;不超过当前网络时间2个小时。
难度目标bits 4个字节
随机数 Nonce 4个字节
区块体记载了交易详情、交易计数器、区块大小。
代码:
/**
* 〈UnixTimeStamp〉
* @author Michael
* @create 2017/7/25
* @since 1.0.0
*/
public class UnixTimeStamp {
public static void main(String[] args) {
long timestamp = System.currentTimeMillis();
System.out.println(timestamp);
}
}
//merkletrees
import java.util.List;
/**
* 〈merkleTrees〉
* @author Michael
* @create 2018/7/25
* @since 1.0.0
*/
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
public class MerkleTrees {
// transaction List List txList;
// Merkle Root
String root;
//构造函数
public MerkleTrees(List txList) {
this.txList = txList;
root = "";
}
public void merkle_tree() {
ListtempTxList = new ArrayList();
for (int i = 0; i < this.txList.size(); i++) {
tempTxList.add(this.txList.get(i));
}
List newTxList = getNewTxList(tempTxList);
while (newTxList.size() != 1) {
newTxList = getNewTxList(newTxList);
}
this.root = newTxList.get(0);
}
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++;
}
return newTxList;
}
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 "";
}
public String getRoot() {
return this.root;
}
}
import java.util.ArrayList;import java.util.List;
/**
參考地址: https://blog.csdn.net/xiangzhihong8/article/details/53931213
* *〈测试函数〉
* * @author Michael
* * @create 2018/7/25
** @since 1.0.0
*/
public class MerkleTreesTest {
public static void main(String [] args) {
ListtempTxList = new ArrayList();
tempTxList.add("a");
tempTxList.add("b");
tempTxList.add("c");
tempTxList.add("d");
MerkleTrees merkleTrees = new MerkleTrees(tempTxList);
merkleTrees.merkle_tree();
System.out.println("root : " + merkleTrees.getRoot());
}
}
网友评论