區塊鏈是分佈式數據存儲、點對點傳輸、共識機制、加密算法等計算機技術的新型應用模式。所謂共識機制是區塊鏈系統中實現不一樣節點之間創建信任、獲取權益的數學算法 。java
本系列教程旨在幫助你瞭解如何開發區塊鏈技術。git
本章目標github
(我會假設你對面向對象編程有基本的瞭解)算法
值得注意的是,這裏建立的區塊鏈並非功能徹底的徹底適合應用與生產的區塊鏈,相反只是爲了幫助你更好的理解區塊鏈的概念。編程
區塊鏈就是一串或者是一系列區塊的集合,相似於鏈表的概念,每一個區塊都指向於後面一個區塊,而後順序的鏈接在一塊兒。那麼每一個區塊中的內容是什麼呢?在區塊鏈中的每個區塊都存放了不少頗有價值的信息,主要包括三個部分:本身的數字簽名,上一個區塊的數字簽名,還有一切須要加密的數據(這些數據在比特幣中就至關因而交易的信息,它是加密貨幣的本質)。每一個數字簽名不但證實了本身是特有的一個區塊,並且指向了前一個區塊的來源,讓全部的區塊在鏈條中能夠串起來,而數據就是一些特定的信息,你能夠按照業務邏輯來保存業務數據。json
這裏的hash指的就是數字簽名小程序
因此每個區塊不只包含前一個區塊的hash值,同時包含自身的一個hash值,自身的hash
值是經過以前的hash
值和數據data
經過hash
計算出來的。若是前一個區塊的數據一旦被篡改了,那麼前一個區塊的hash值也會一樣發生變化(由於數據也被計算在內),這樣也就致使了全部後續的區塊中的hash
值。因此計算和比對hash值會讓咱們檢查到當前的區塊鏈是不是有效的,也就避免了數據被惡意篡改的可能性,由於篡改數據就會改變hash值並破壞整個區塊鏈。微信小程序
import java.util.Date;
public class Block {
public String hash;
public String previousHash;
private String data; //our data will be a simple message.
private long timeStamp; //as number of milliseconds since 1/1/1970.
//Block Constructor.
public Block(String data,String previousHash ) {
this.data = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
}
}
複製代碼
正如你能夠看到咱們的基本塊包含String hash
,它將保存咱們的數字簽名。變量previoushash
保存前一個塊的hash
和String data
來保存咱們的塊數據數組
熟悉加密算法的朋友們,Java方式能夠實現的加密方式有不少,例如BASE、MD、RSA、SHA等等,我在這裏選用了SHA256
這種加密方式,SHA(Secure Hash Algorithm)安全散列算法,這種算法的特色是數據的少許更改會在Hash值中產生不可預知的大量更改,hash值用做表示大量數據的固定大小的惟一值,而SHA256算法的hash值大小爲256位。之因此選用SHA256是由於它的大小正合適,一方面產生重複hash值的可能性很小,另外一方面在區塊鏈實際應用過程當中,有可能會產生大量的區塊,而使得信息量很大,那麼256位的大小就比較恰當了。安全
下面我建立了一個StringUtil
方法來方便調用SHA256算法
import java.security.MessageDigest;
public class StringUtil {
//Applies Sha256 to a string and returns the result.
public static String applySha256(String input){
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
//Applies sha256 to our input,
byte[] hash = digest.digest(input.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer(); // This will contain hash as hexidecimal
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
catch(Exception e) {
throw new RuntimeException(e);
}
}
}
複製代碼
或許你徹底不理解上述代碼的含義,可是你只要理解全部的輸入調用此方法後均會生成一個獨一無二的hash值(數字簽名),而這個hash值在區塊鏈中是很是重要的。
接下來讓咱們在Block
類中應用 方法 applySha256 方法,其主要的目的就是計算hash值,咱們計算的hash值應該包括區塊中全部咱們不但願被惡意篡改的數據,在咱們上面所列的Block
類中就必定包括previousHash
,data
和timeStamp
,
public String calculateHash() {
String calculatedhash = StringUtil.applySha256(
previousHash +
Long.toString(timeStamp) +
data
);
return calculatedhash;
}
複製代碼
而後把這個方法加入到Block
的構造函數中去
public Block(String data,String previousHash ) {
this.data = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
this.hash = calculateHash(); //Making sure we do this after we set the other values.
}
複製代碼
在主方法中讓咱們建立一些區塊,並把其hash值打印出來,來看看是否一切都在咱們的掌控中。
第一個塊稱爲創世紀區塊,由於它是頭區塊,因此咱們只需輸入「0」做爲前一個塊的previous hash
。
public class NoobChain {
public static void main(String[] args) {
Block genesisBlock = new Block("Hi im the first block", "0");
System.out.println("Hash for block 1 : " + genesisBlock.hash);
Block secondBlock = new Block("Yo im the second block",genesisBlock.hash);
System.out.println("Hash for block 2 : " + secondBlock.hash);
Block thirdBlock = new Block("Hey im the third block",secondBlock.hash);
System.out.println("Hash for block 3 : " + thirdBlock.hash);
}
}
複製代碼
打印:
Hash for block 1: f6d1bc5f7b0016eab53ec022db9a5d9e1873ee78513b1c666696e66777fe55fb
Hash for block 2: 6936612b3380660840f22ee6cb8b72ffc01dbca5369f305b92018321d883f4a3
Hash for block 3: f3e58f74b5adbd59a7a1fc68c97055d42e94d33f6c322d87b29ab20d3c959b8f
複製代碼
每個區塊都必需要有本身的數據簽名即hash值,這個hash值依賴於自身的信息(data)和上一個區塊的數字簽名(previousHash),但這個還不是區塊鏈,下面讓咱們存儲區塊到數組中,這裏我會引入gson包,目的是能夠用json方式查看整個一條區塊鏈結構。
import java.util.ArrayList;
import com.google.gson.GsonBuilder;
public class NoobChain {
public static ArrayList<Block> blockchain = new ArrayList<Block>();
public static void main(String[] args) {
//add our blocks to the blockchain ArrayList:
blockchain.add(new Block("Hi im the first block", "0"));
blockchain.add(new Block("Yo im the second block",blockchain.get(blockchain.size()-1).hash));
blockchain.add(new Block("Hey im the third block",blockchain.get(blockchain.size()-1).hash));
String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
System.out.println(blockchainJson);
}
}
複製代碼
這樣的輸出結構就更相似於咱們所期待的區塊鏈的樣子。
在主方法中增長一個isChainValid()方法,目的是循環區塊鏈中的全部區塊而且比較hash值,這個方法用來檢查hash值是不是於計算出來的hash值相等,同時previousHash值是否和前一個區塊的hash值相等。或許你會產生以下的疑問,咱們就在一個主函數中建立區塊鏈中的區塊,因此不存在被修改的可能性,可是你要注意的是,區塊鏈中的一個核心概念就是去中心化,每個區塊多是在網絡中的某一個節點中產生的,因此頗有可能某個節點把本身節點中的數據修改了,那麼根據上述的理論數據改變會致使整個區塊鏈的破裂,也就是區塊鏈就無效了。
public static Boolean isChainValid() {
Block currentBlock;
Block previousBlock;
//loop through blockchain to check hashes:
for(int i=1; i < blockchain.size(); i++) {
currentBlock = blockchain.get(i);
previousBlock = blockchain.get(i-1);
//compare registered hash and calculated hash:
if(!currentBlock.hash.equals(currentBlock.calculateHash()) ){
System.out.println("Current Hashes not equal");
return false;
}
//compare previous hash and registered previous hash
if(!previousBlock.hash.equals(currentBlock.previousHash) ) {
System.out.println("Previous Hashes not equal");
return false;
}
}
return true;
}
複製代碼
任何區塊鏈中區塊的一絲一毫改變都會致使這個函數返回false,也就證實了區塊鏈無效了。
在比特幣網絡中全部的網絡節點都分享了它們各自的區塊鏈,然而最長的有效區塊鏈是被全網所統一認可的,若是有人惡意來篡改以前的數據,而後建立一條更長的區塊鏈並全網發佈呈如今網絡中,咱們該怎麼辦呢?這就涉及到了區塊鏈中另一個重要的概念工做量證實,這裏就不得不說起一下hashcash,這個概念最先來自於Adam Back的一篇論文,主要應用於郵件過濾和比特幣中防止雙重支付。
這裏咱們要求挖礦者作工做量證實,具體的方式是在區塊中嘗試不一樣的參數值直到它的hash值是從一系列的0開始的。讓咱們添加一個名爲nonce
的int類型以包含在咱們的calculatehash()
方法中,以及須要的mineblock()
方法
import java.util.Date;
public class Block {
public String hash;
public String previousHash;
private String data; //our data will be a simple message.
private long timeStamp; //as number of milliseconds since 1/1/1970.
private int nonce;
//Block Constructor.
public Block(String data,String previousHash ) {
this.data = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
this.hash = calculateHash(); //Making sure we do this after we set the other values.
}
//Calculate new hash based on blocks contents
public String calculateHash() {
String calculatedhash = StringUtil.applySha256(
previousHash +
Long.toString(timeStamp) +
Integer.toString(nonce) +
data
);
return calculatedhash;
}
public void mineBlock(int difficulty) {
String target = new String(new char[difficulty]).replace('\0', '0'); //Create a string with difficulty * "0"
while(!hash.substring( 0, difficulty).equals(target)) {
nonce ++;
hash = calculateHash();
}
System.out.println("Block Mined!!! : " + hash);
}
}
複製代碼
mineBlock()方法中引入了一個int值稱爲difficulty難度,低的難度好比1和2,普通的電腦基本均可以立刻計算出來,個人建議是在4-6之間進行測試,普通電腦大概會花費3秒時間,在萊特幣中難度大概圍繞在442592左右,而在比特幣中每一次挖礦都要求大概在10分鐘左右,固然根據全部網絡中的計算能力,難度也會不斷的進行修改。
咱們在NoobChain
類 中增長difficulty
這個靜態變量。
public static int difficulty = 5;
複製代碼
這樣咱們必須修改主方法中讓建立每一個新區塊時必須觸發mineBlock()
方法,而isChainValid()
方法用來檢查每一個區塊的hash值是否正確,整個區塊鏈是不是有效的。
import java.util.ArrayList;
import com.google.gson.GsonBuilder;
public class NoobChain {
public static ArrayList<Block> blockchain = new ArrayList<Block>();
public static int difficulty = 5;
public static void main(String[] args) {
//add our blocks to the blockchain ArrayList:
blockchain.add(new Block("Hi im the first block", "0"));
System.out.println("Trying to Mine block 1... ");
blockchain.get(0).mineBlock(difficulty);
blockchain.add(new Block("Yo im the second block",blockchain.get(blockchain.size()-1).hash));
System.out.println("Trying to Mine block 2... ");
blockchain.get(1).mineBlock(difficulty);
blockchain.add(new Block("Hey im the third block",blockchain.get(blockchain.size()-1).hash));
System.out.println("Trying to Mine block 3... ");
blockchain.get(2).mineBlock(difficulty);
System.out.println("\nBlockchain is Valid: " + isChainValid());
String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
System.out.println("\nThe block chain: ");
System.out.println(blockchainJson);
}
public static Boolean isChainValid() {
Block currentBlock;
Block previousBlock;
String hashTarget = new String(new char[difficulty]).replace('\0', '0');
//loop through blockchain to check hashes:
for(int i=1; i < blockchain.size(); i++) {
currentBlock = blockchain.get(i);
previousBlock = blockchain.get(i-1);
//compare registered hash and calculated hash:
if(!currentBlock.hash.equals(currentBlock.calculateHash()) ){
System.out.println("Current Hashes not equal");
return false;
}
//compare previous hash and registered previous hash
if(!previousBlock.hash.equals(currentBlock.previousHash) ) {
System.out.println("Previous Hashes not equal");
return false;
}
//check if hash is solved
if(!currentBlock.hash.substring( 0, difficulty).equals(hashTarget)) {
System.out.println("This block hasn't been mined");
return false;
}
}
return true;
}
}
複製代碼
打印:
Connected to the target VM, address: '127.0.0.1:61863', transport: 'socket'
Trying to Mine block 1...
Block Mined!!! : 0000016667d4240e9c30f53015310b0ec6ce99032d7e1d66d670afc509cab082
Trying to Mine block 2...
Block Mined!!! : 000002ea55735bea4cac7e358c7b0d8d81e8ca24021f5f85211bf54fd4ac795a
Trying to Mine block 3...
Block Mined!!! : 000000576987e5e9afbdf19b512b2b7d0c56db0e6ca49b3a7e638177f617994b
Blockchain is Valid: true
[
{
"hash": "0000016667d4240e9c30f53015310b0ec6ce99032d7e1d66d670afc509cab082",
"previousHash": "0",
"data": "first",
"timeStamp": 1520659506042,
"nonce": 618139
},
{
"hash": "000002ea55735bea4cac7e358c7b0d8d81e8ca24021f5f85211bf54fd4ac795a",
"previousHash": "0000016667d4240e9c30f53015310b0ec6ce99032d7e1d66d670afc509cab082",
"data": "second",
"timeStamp": 1520659508825,
"nonce": 1819877
},
{
"hash": "000000576987e5e9afbdf19b512b2b7d0c56db0e6ca49b3a7e638177f617994b",
"previousHash": "000002ea55735bea4cac7e358c7b0d8d81e8ca24021f5f85211bf54fd4ac795a",
"data": "third",
"timeStamp": 1520659515910,
"nonce": 1404341
}
]
複製代碼
通過測試增長一個新的區塊即挖礦必須花費必定時間,大概是3秒左右,你能夠提升difficulty難度來看,它是如何影響數據難題所花費的時間的
若是有人在你的區塊鏈系統中惡意篡改數據:
由於篡改的區塊鏈將沒法遇上長鏈和有效鏈,除非他們比你網絡中全部的節點擁有更大的計算速度,多是將來的量子計算機或者是其餘什麼。
你的區塊鏈:
原文連接:Creating Your First Blockchain with Java. Part 1.
從個人 github 中下載,github.com/longfeizhen…
🙂🙂🙂關注微信小程序java架構師歷程 上下班的路上無聊嗎?還在看小說、新聞嗎?不知道怎樣提升本身的技術嗎?來吧這裏有你須要的java架構文章,1.5w+的java工程師都在看,你還在等什麼?