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

Understanding the concept of Block chain with java examples

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

Share

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

The core of blockchain is decentralized storage. Traditional database solutions, including relational database and non-relational database, belong to centralized storage. Decentralized storage means that the data has no center, and each data node contains the information of the previous data node. An example is used to understand the data storage form of the block chain:

Package com.weihua.blockchains.blackchain

Import java.util.Date

Public class BlockMan {

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 BlockMan (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;} / / Increases nonce value until hash target is reached.public void mineBlock (int difficulty) {String target = StringUtil.getDificultyString (difficulty) / / Create a string with difficulty * "0" while (! hash.substring (0, difficulty) .equals (target)) {nonce + +; hash = calculateHash ();} System.out.println ("Block Minedulars!:" + hash);}

}

Package com.weihua.blockchains.blackchain

Import java.security.MessageDigest

Import com.google.gson.GsonBuilder

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; iTunes +) {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);} / / Short hand helper to turn Object into a json stringpublic static String getJson (Object o) {return new GsonBuilder (). SetPrettyPrinting (). Create (). ToJson (o) } / / Returns difficulty string target, to compare to hash. Eg difficulty of 5 will return "00000" public static String getDificultyString (int difficulty) {return new String (new char [difficulty]) .replace ('\ 0mm,'0');}

}

Package com.weihua.blockchains.blackchain

Import java.util.ArrayList

Public class TestBlockChain {

Public static ArrayList blockchain = new ArrayList (); public static int difficulty = 5 * * public static void main (String [] args) {/ / add our blocks to the blockchain ArrayList: System.out.println ("Trying to Mine block 1... ); addBlock (new BlockMan ("Hi im the first block", "0")); System.out.println ("Trying to Mine block 2... ); addBlock (new BlockMan ("Yo im the second block", blockchain.get (blockchain.size ()-1) .hash); System.out.println ("Trying to Mine block 3... ); addBlock (new BlockMan ("Hey im the third block", blockchain.get (blockchain.size ()-1) .hash); System.out.println ("\ nBlockchain is Valid:" + isChainValid ()); String blockchainJson = StringUtil.getJson (blockchain); System.out.println ("\ nThe blockchain:"); System.out.println (blockchainJson);} public static Boolean isChainValid () {BlockMan currentBlock; BlockMan 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;} public static void addBlock (BlockMan newBlock) {newBlock.mineBlock (difficulty); blockchain.add (newBlock);}

}

4.0.0

Com.weihua.blockchainsblackchain0.0.1-SNAPSHOTjarblackchain http://maven.apache.org UTF-8 junit junit 3.8.1 test com.google.code.gson gson 2.1

To run, take a look at the output:

Trying to Mine block 1...

Block Mined!!!: 000005b9947556fa4b14d24349728a58418c1517f8073d10a37ba3daf0ceee9c

Trying to Mine block 2...

Block Mined!!!: 00000015d3f53bd8545a3a9586aaef26abe26d78fce2da6584aac025c60c21e3

Trying to Mine block 3...

Block Mined!!!: 000000d224711a1e308e98c317cc7c900c7f4196d585266262b54e42288da65b

Blockchain is Valid: true

The block chain:

[

{

"hash": "000005b9947556fa4b14d24349728a58418c1517f8073d10a37ba3daf0ceee9c"

"previousHash": "0"

"data": "Hi im the first block"

"timeStamp": 1557928459188

"nonce": 347042

}

{

"hash": "00000015d3f53bd8545a3a9586aaef26abe26d78fce2da6584aac025c60c21e3"

"previousHash": "000005b9947556fa4b14d24349728a58418c1517f8073d10a37ba3daf0ceee9c"

"data": "Yo im the second block"

"timeStamp": 1557928460017

"nonce": 1394831

}

{

"hash": "000000d224711a1e308e98c317cc7c900c7f4196d585266262b54e42288da65b"

"previousHash": "00000015d3f53bd8545a3a9586aaef26abe26d78fce2da6584aac025c60c21e3"

"data": "Hey im the third block"

"timeStamp": 1557928462949

"nonce": 81919

}

]

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: 233

*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