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 implement Block chain with java Code

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

Share

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

This article introduces the relevant knowledge of "how to use java code to implement block chain". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

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 realized by 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 changes in data will produce a large number of unpredictable changes in the hash value, which is used as a unique value that represents a fixed size of a large amount of data. 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 hexidecimal for (int I = 0; I < hash.length) String hex +) {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);}

You may not fully understand the meaning of the above code, but you just need to understand that all inputs call this method to generate a unique hash value (digital signature), and this hash value is very important in the block chain.

Next, let's apply the method applySha256 method to the Block class. Its main purpose is to calculate the hash value. The hash value we calculated should include all the data in the block that we do not want to be maliciously tampered with. PreviousHash,data and timeStamp must be included in the Block class listed above.

Public String calculateHash () {String calculatedhash = StringUtil.applySha256 (previousHash + Long.toString (timeStamp) + data); return calculatedhash;}

Then add this method to the constructor of 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. } Test

In the main method, let's create some blocks and print out their hash values to see if everything is under our control.

The first block is called the Genesis block, and because it is a header block, we only need to enter "0" as the previous hash of the previous block.

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);}}

Printout results:

Hash for block 1: f6d1bc5f7b0016eab53ec022db9a5d9e1873ee78513b1c666696e66777fe55fbHash for block 2: 6936612b3380660840f22ee6cb8b72ffc01dbca5369f305b92018321d883f4a3Hash for block 3: f3e58f74b5adbd59a7a1fc68c97055d42e94d33f6c322d87b29ab20d3c959b8f

Each chunk must have its own data signature, namely hash value, which depends on its own information (data) and the digital signature (previousHash) of the previous chunk, but this is not a blockchain yet. Let's store chunks into an array. Here I will introduce the gson package to view the entire blockchain structure in 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);}}

This output structure is more similar to what we expect the blockchain to look like.

Check the integrity of the block chain

Add an isChainValid () method to the main method to loop through all blocks in the block chain and compare hash values. This method is used to check whether the hash value is equal to the calculated hash value, and whether the previoushash value is equal to the hash value of the previous block. You may have the following questions: we create blocks in the block chain in a main function, so there is no possibility of being modified, but you should note that one of the core concepts in the block chain is decentralization. Each block may be generated in a node in the network, so it is very likely that a node has modified the data in its own node. Then according to the above theoretical data changes will lead to the rupture of the entire block chain, that is, the block chain will be invalid.

Public static Boolean isChainValid () {Block currentBlock; Block previousBlock; / / 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 hash if (! previousBlock.hash.equals (currentBlock.previousHash)) {System.out.println ("Previous Hashes not equal"); return false;}} return true;}

The slightest change in any blockchain will cause this function to return false, which proves that the blockchain is invalid.

All the nodes in the Bitcoin network share their respective blockchains, but the longest valid blockchain is universally recognized by the whole network. What should we do if someone maliciously tampers with the previous data and then creates a longer blockchain and publishes it across the network? This involves another important concept in the blockchain, workload proof, and here we have to mention hashcash, which originated from a paper by Adam Back and is mainly used to prevent double payments in email filtering and bitcoin.

Digging ore

Here we ask the miner to do workload proof by trying different parameter values in the block until its hash value starts with a series of zeros. Let's add an int type named nonce to include in our calculatehash () method, as well as the required mineblock () method

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. 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 ('\ 0mm,'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; 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 (iMul) / / 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;}}

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, adding a new block, that is, mining must take a certain amount of time, about 3 seconds, and you can increase the difficulty of difficulty to see how it affects the time spent on data puzzles.

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.

This is the end of the content of "how to use java code to implement block chain". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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