Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop Block chain by Java

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how Java develops the block chain". In the daily operation, I believe many people have doubts about how to develop the block chain in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to develop the block chain in Java". Next, please follow the editor to study!

Create a blockchain

A block chain is a collection of a string or a series of blocks, similar to the concept of a linked list, in which each block points to the next block and is then connected sequentially. So what is the content of each block? Each block in the blockchain stores a lot of valuable information, which mainly includes three parts: your own digital signature, the digital signature of the previous block, and all the data that needs to be encrypted (this data is equivalent to transaction information in Bitcoin, which is the essence of cryptocurrency). Each digital signature not only proves that it is a unique block, but also points to the source of the previous block, so that all blocks can be strung together in the chain, and the data is some specific information. You can save business data according to business logic.

Hash here refers to a digital signature.

So each block contains not only the hash value of the previous block, but also its own hash value, which is calculated by hash through the previous hash value and the data data. If the data in the previous block is tampered with, the hash value of the previous block will also change (because the data is also counted), which leads to the hash value in all subsequent blocks. So calculating and comparing the hash value will let us check whether the current block chain is valid, and avoid the possibility of malicious tampering with the data, because tampering with the data will change the hash value and destroy the whole block chain.

Class Block that defines the blockchain:

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 timeSt / / 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 ();}}

As you can see, our basic block contains String hash, which will hold our digital signature. The variable previoushash saves the hash and String data of the previous block to save our block data

Create a digital signature

For those of you who are familiar with encryption algorithms, there are many encryption methods that can be implemented in Java, such as BASE, MD, RSA, SHA and so on. I choose SHA256 encryption here, SHA (Secure Hash Algorithm) secure hashing algorithm. The characteristic of this algorithm is that a small amount of data changes will result in a large number of unpredictable changes in the hash value. The hash value is used as the only value that represents the fixed size of a large amount of data, while the hash value of the SHA256 algorithm is 256 bits. The reason for choosing SHA256 is that it is the right size, on the one hand, the possibility of generating repeated hash values is very small, on the other hand, in the practical application of the block chain, it is possible to produce a large number of blocks, resulting in a large amount of information, so the size of 256bits is more appropriate.

Next I created a StringUtil method to make it easy to call the SHA256 algorithm

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: f6d1bc5f7b0016eab53ec022db9a5d9e1873ee78513b1c666696e66777fe55fbHash for block 2: 6936612b3380660840f22ee6cb8b72ffc01dbca5369f305b92018321d883f4a3Hash 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 blockchain = new ArrayList(); 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 Minedulars!:" + hash);}}

MineBlock () method introduces an int value called difficulty difficulty, low difficulty such as 1 and 2, ordinary computers can basically calculate immediately, my suggestion is to test between 4-6, the average computer will take about 3 seconds, the difficulty in Lettercoin is about 442592, and each mining in Bitcoin requires about 10 minutes, of course, according to the computing power of all networks. The difficulty will also be constantly modified.

We add the static variable difficulty to the NoobChain class.

Public static int difficulty = 5

So we have to modify the main method so that the mineBlock () method must be triggered when each new chunk is created, and the isChainValid () method is used to check whether the hash value of each chunk is correct and whether the entire chunk chain is valid.

Import java.util.ArrayList;import com.google.gson.GsonBuilder;public class NoobChain {public static ArrayList blockchain = new ArrayList (); public static int difficulty = 5 leading 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 blockchain: "); System.out.println (blockchainJson);} public static Boolean isChainValid () {Block currentBlock; Block previousBlock String hashTarget = new String (new char [difficulty]). Replace ('\ 0mm,'0'); / / loop through blockchain to check hashes:for (int iTun1; I < blockchain.size (); iTunes +) {currentBlock = blockchain.get (I); previousBlock = blockchain.get (iMur1) / / 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;}}

Print:

Connected to the target VM, address: '127.0.0.1 transport:' socket'Trying to Mine block 1. Block Mined!!!: 0000016667d4240e9c30f53015310b0ec6ce99032d7e1d66d670afc509cab082Trying to Mine block 2... Block Mined!!!: 000002ea55735bea4cac7e358c7b0d8d81e8ca24021f5f85211bf54fd4ac795aTrying to Mine block 3... Block 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}]

After testing to add a new block, that is, mining, it takes a certain amount of time, about 3 seconds, and you can make difficulty more difficult to see how it affects the time taken by the data puzzle. If someone maliciously tampers with data in your blockchain system:

Their blockchain is invalid.

They can't create longer blockchains.

Honest blockchain in the network will have more time advantage in the long chain.

Because tampered blockchains will not be able to catch up with long and valid chains unless they have higher computing speeds than all the nodes in your network, which could be future quantum computers or something.

At this point, the study on "how to develop the block chain in Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report