日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java开发区块链只需150行代码

發布時間:2023/11/29 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java开发区块链只需150行代码 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文目的是通過java實戰開發教程理解區塊鏈是什么。將通過實戰入門學習,用Java自學開發一個很基本的區塊鏈,并在此基礎上能擴展如web框架應用等。這個基本的java區塊鏈也實現簡單的工作量證明系統。本文用一個java例子,演示了開發一個區塊鏈應用的過程,涉及到所有區塊鏈的概念和基本實現方法。本文閱讀對象,主要是希望和即將從事區塊鏈開發的項目架構師。需要指出的是,我們用150行java代碼構建的區塊鏈達不到生產級別的,它只是為了幫助你更好的理解區塊鏈的概念。

Java源代碼保存在Github

創建區塊鏈

區塊鏈就是一串或者是一系列區塊的集合,類似于鏈表的概念,每個區塊都指向于后面一個區塊,然后順序的連接在一起。那么每個區塊中的內容是什么呢?在區塊鏈中的每一個區塊都存放了很多很有價值的信息,主要包括三個部分:自己的數字簽名,上一個區塊的數字簽名,還有一切需要加密的數據(這些數據在比特幣中就相當于是交易的信息,它是加密貨幣的本質)。每個數字簽名不但證明了自己是特有的一個區塊,而且指向了前一個區塊的來源,讓所有的區塊在鏈條中可以串起來,而數據就是一些特定的信息,你可以按照業務邏輯來保存業務數據。

這里的hash指的就是數字簽名

所以每一個區塊不僅包含前一個區塊的hash值,同時包含自身的一個hash值,自身的hash值是通過之前的hash值和數據data通過hash計算出來的。如果前一個區塊的數據一旦被篡改了,那么前一個區塊的hash值也會同樣發生變化(因為數據也被計算在內),這樣也就導致了所有后續的區塊中的hash值。所以計算和比對hash值會讓我們檢查到當前的區塊鏈是否是有效的,也就避免了數據被惡意篡改的可能性,因為篡改數據就會改變hash值并破壞整個區塊鏈。

定義區塊鏈的類Block:

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 hexidecimalfor (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 hashif(!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 contentspublic 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 hashif(!previousBlock.hash.equals(currentBlock.previousHash) ) {System.out.println("Previous Hashes not equal");return false;}//check if hash is solvedif(!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!!! : 000000576987e5e9afbdf19b512b2b7d0c56db0e6ca49b3a7e638177f617994bBlockchain 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難度來看,它是如何影響數據難題所花費的時間的。如果有人在你的區塊鏈系統中惡意篡改數據:

  • 他們的區塊鏈是無效的。
  • 他們無法創建更長的區塊鏈
  • 網絡中誠實的區塊鏈會在長鏈中更有時間的優勢

因為篡改的區塊鏈將無法趕上長鏈和有效鏈,除非他們比你網絡中所有的節點擁有更大的計算速度,可能是未來的量子計算機或者是其他什么。

你已經完成了你的基本區塊鏈!

另外安利下:

1.以太坊DApp開發入門實戰

2.以太坊區塊鏈電商DApp實戰

3.java開發以太坊區塊鏈的教程,web3j開發詳解:http://t.cn/RrpULLJ

轉載于:https://www.cnblogs.com/helloworld2018/p/9011369.html

總結

以上是生活随笔為你收集整理的java开发区块链只需150行代码的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。