區(qū)塊鏈原本是比特幣等加密貨幣存儲數(shù)據(jù)的一種獨特方式,是一種自引用的數(shù)據(jù)結(jié)構(gòu),用來存儲大量交易信息,每條記錄從后向前有序鏈接起來,具備公開透明、無法篡改、方便追溯的特點。實際上,這種特性也直接體現(xiàn)了整個比特幣的特點,因此使用區(qū)塊鏈來概括加密貨幣背后的技術(shù)實現(xiàn)是非常直觀和恰當(dāng)?shù)?。區(qū)塊鏈是一項技術(shù),加密貨幣是其開發(fā)實現(xiàn)的一類產(chǎn)品(含有代幣,也有不含代幣的區(qū)塊鏈產(chǎn)品),不能等同或混淆。與加密貨幣相比,區(qū)塊鏈這個名字拋開了代幣的概念,更加形象化、技術(shù)化、去政治化,更適合作為一門技術(shù)去研究、去推廣。
區(qū)塊鏈基礎(chǔ)架構(gòu)模型一般說來,區(qū)塊鏈系統(tǒng)由數(shù)據(jù)層、網(wǎng)絡(luò)層、共識層、激勵層、合約層和應(yīng)用層組成。 其中,數(shù)據(jù)層封裝了底層數(shù)據(jù)區(qū)塊以及相關(guān)的數(shù)據(jù)加密和時間戳等技術(shù);網(wǎng)絡(luò)層則包括分布式組網(wǎng)機制、數(shù)據(jù)傳播機制和數(shù)據(jù)驗證機制等;共識層主要封裝網(wǎng)絡(luò)節(jié)點的各類共識算法;激勵層將經(jīng)濟因素集成到區(qū)塊鏈技術(shù)體系中來,主要包括經(jīng)濟激勵的發(fā)行機制和分配機制等;合約層主要封裝各類腳本、算法和智能合約,是區(qū)塊鏈可編程特性的基礎(chǔ);應(yīng)用層則封裝了區(qū)塊鏈的各種應(yīng)用場景和案例。該模型中,基于時間戳的鏈式區(qū)塊結(jié)構(gòu)、分布式節(jié)點的共識機制、基于共識算力的經(jīng)濟激勵和靈活可編程的智能合約是區(qū)塊鏈技術(shù)最具代表性的創(chuàng)新點。
區(qū)塊鏈代碼實現(xiàn)
哈希樹的跟節(jié)點稱為Merkle根,Merkle樹可以僅用log2(N)的時間復(fù)雜度檢查任何一個數(shù)據(jù)元素是否包含在樹中:
package test;
import java.security.MessageDigest;
import java.uTIl.ArrayList;
import java.uTIl.List;
public class MerkleTrees {
// transacTIon List
List《String》 txList;
// Merkle Root
String root;
/**
* constructor
* @param txList transacTIon 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;
}
}