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 workload proof Mechanism in Java language

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

Share

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

This article mainly introduces "how to achieve workload proof mechanism in Java language". In daily operation, I believe that many people have doubts about how to achieve workload proof mechanism in Java language. 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 achieve workload proof mechanism in Java language". Next, please follow the editor to study!

Workload proof mechanism

One of the key ideas of the blockchain is that a large number of difficult calculations must be done to store the transaction data on the blockchain. This working mechanism can ensure the security and consistency of the whole block chain data. At the same time, miners who complete this calculation will receive the corresponding Token reward.

This mechanism is very similar to our real life: we have to work hard to earn money to maintain our lives. In the blockchain, the miners in the network work hard to maintain the blockchain network, add blocks to it, and receive certain Token awards. As a result of their work, a block is combined into the block chain in a secure way, thus ensuring the stability of the entire block chain database. It must also be noted that a miner who has completed the calculation must be recognized (proved to be correct) by all other miners before it can be considered complete.

This whole set of calculation and proof mechanism is called Proof-of-Work (workload proof). Computing is very difficult because it consumes a lot of computer power resources, and even very high-performance computers can not calculate the correct results very quickly. In addition, with the passage of time, the difficulty of this calculation will also increase, in order to ensure the block rate of 6 new blocks per hour. In Bitcoin, the goal of this work is to find a chunk Hash (hash) that meets a particular requirement. The hash value of this block is a proof of the result of the work. Therefore, the purpose of the calculation work is to find this proof value.

Finally, it is important to note that it is very difficult to calculate this particular Hash (hash value), but when others verify that the hash value is correct, it is very simple and can be done at once.

Hashing

Hash: hash | Hash

Let's talk about Hashing (hash). Friends who are very familiar with this area can skip this paragraph directly.

Hash is a computer algorithm that can calculate the hash value of any size of data, and the length of the hash value is fixed, 256bit. The calculated hash value can be used as the only representative of this data. The hash algorithm has several key features:

Irreversibility. The raw data cannot be deduced from a hash value. So, hashing is not encryption.

Uniqueness. Each data has one and only one unique hash value.

Very different. The slightest change in the original data will result in a completely different hash.

For example:

SHA256 ("wangwei1")-> 1e898b7c9adaad86c20139a302ccd5277f81040cab68dc2aecfc684773532652SHA256 ("wangwei2")-> c9cc7417c17318c8aab448cc8ace24c53b6dcf350f5c5fd8e91cbc3b011a179d

Hash algorithms are widely used to verify the consistency of files. For example, software providers usually attach a checksums to the installation package. After we download a software installation package, we can use the hash function to calculate the hash value of the software installation package, and then compare it with the check code of the software installation package to see whether the downloaded installation package is complete and whether there is any data loss.

In the block chain, the hash value is used to ensure the consistency of the block. The data used for hashing each block contains the hash value of the previous block chain, so it is almost impossible for anyone to modify the block data. He must recalculate all the hash values in the entire block chain, from the Genesis block to the latest block.

You can make up for the workload. According to the current computing power of the computer, it is almost impossible.

Hashcash

Bitcoin's workload proved to be using the Hashcash algorithm, an algorithm originally used for anti-spam, which can be broken down into the following steps:

Get some publicly known data data (in the case of email, the recipient's email address; in the case of Bitcoin, the block)

Add a counter counter with the initial value set to 0

Calculate the hash value of data and counter concatenation strings

Check whether the hash value of the previous step meets a certain condition, stop the calculation if it does, add 1 to counter if not, and then repeat steps 3 and 4 until this particular condition is met.

This is a rough algorithm: you change the counter, calculate a new hash, check it, increase the counter, calculate a new hash, and cycle over and over again, which is why it takes a lot of computer computing resources.

Let's take a closer look at what this particular condition refers to. In the original Hashcash algorithm, this special requirement means that the pre-20bit of the calculated hash value must all be zero.

In Bitcoin, the requirement for how many zeros to precede the hash is constantly adjusted over time, for design purposes, although one block per 10min is guaranteed as the computing power of the computer continues to improve and more and more miners join the network.

Let's demonstrate this algorithm.

# calculate the hash value SHA256 ("I like donuts") of the string'I like donuts''--> f80867f6efd4484c23b0e7184e53fe4af6ab49b97f5293fcd50d5b2bfa73a4d0# concatenate a counter value (ca07ca), and then perform Hash calculation SHA256 ("I like donutsca07ca")-- > 0000002f7c1fe31cb82acdc082cfec47620b7e4ab94f2bf9e096c436fc8cee06

Here ca07ca is the hexadecimal value of the counter, and he represents a decimal value of 13240266

That is, starting from 0, it took a total of 13240266 calculations to calculate the hash value of I like donuts, which satisfies that the first six bits (3 bytes) are all zero.

Code implementation

Train of thought:

1) Mining (Pow) should be carried out before each block is added to the block chain.

2) if the Hash value generated during mining is less than the target value of difficulty, it will be added to the block, otherwise the mining will continue until the correct Hash is found.

3) finally, verify whether the block Hash is valid

Define Pow class / * workload proof * * @ author wangwei * @ date 2018-02-04 * / @ Datapublic class ProofOfWork {/ * difficulty target bit * / public static final int TARGET_BITS = 20; / * * block * / private Block block; / * difficulty target value * / private BigInteger target Private ProofOfWork (Block block, BigInteger target) {this.block = block; this.target = target;} / * create a new workload certificate and set the difficulty target value *

* shift 1, move 1 to the left (256-TARGET_BITS) to get our difficulty target value * * @ param block * @ return * / public static ProofOfWork newProofOfWork (Block block) {BigInteger targetValue = BigInteger.valueOf (1). ShiftLeft ((256-TARGET_BITS)); return newProofOfWork (block, targetValue);}}

Set a difficulty target bit TARGET_BITS, indicating the final mining Hash value, converted to binary, compared with 256, the length is reduced by how much bit, that is, how many bit before the binary is zero.

The larger the TARGET_BITS, the smaller the final targetValue, which requires that the calculated Hash is getting smaller and smaller, that is, mining is becoming more and more difficult.

Our TARGET_BITS here is fixed, but in real Bitcoin, the difficulty goal is dynamically adjusted over time. For details, see Chapter 10 of being proficient in Bitcoin (second Edition).

Because of the large number, the BitInteger type is used here.

Prepare data / * prepare data *

* Note: when preparing chunk data, be sure to convert from the original data type to byte [], not directly from the string * @ param nonce * @ return * / private String prepareData (long nonce) {byte [] prevBlockHashBytes = {}; if (StringUtils.isNoneBlank (this.getBlock (). GetPrevBlockHash () {prevBlockHashBytes = new BigInteger (this.getBlock (). GetPrevBlockHash (), 16). ToByteArray () } return ByteUtils.merge (prevBlockHashBytes, this.getBlock (). GetData (). GetBytes (), ByteUtils.toBytes (this.getBlock (). GetTimeStamp ()), ByteUtils.toBytes (TARGET_BITS), ByteUtils.toBytes (nonce);}

The following information about participating in Hash operation:

The hash value of the previous block (parent block)

Transaction data in the block

Time when the block was generated

Difficulty goal

Counter for workload proof algorithm

For details, see Chapter 09 of being proficient in Bitcoin (second Edition).

Pow algorithm / * running workload proof, start mining and find Hash * * @ return * / public PowResult run () {long nonce = 0; String shaHex = ""; System.out.printf ("Mining the block containing:%s\ n", this.getBlock (). GetData ()); long startTime = System.currentTimeMillis () While (nonce < Long.MAX_VALUE) {String data = this.prepareData (nonce); shaHex = DigestUtils.sha256Hex (data); if (new BigInteger (shaHex, 16) .compareto (this.target) = =-1) {System.out.printf ("Elapsed Time:% s seconds\ n", (float) (System.currentTimeMillis ()-startTime) / 1000) System.out.printf ("correct hash Hex:% s\ n\ n", shaHex); break;} else {nonce++;}} return new PowResult (nonce, shaHex);}

There are four main steps in the loop body:

Prepare data

Perform sha256 operation

Convert to BigInter type

Compare with target

Finally, the correct hash value and the operation counter nonce are returned.

Verify the Hash validity of the block / * verify whether the block is valid * * @ return * / public boolean validate () {String data = this.prepareData (this.getBlock (). GetNonce ()); return new BigInteger (DigestUtils.sha256Hex (data), 16) .compareto (this.target) = =-1;} modify block add logic / * *

Create a new block

* * @ param previousHash * @ param data * @ return * / public static Block newBlock (String previousHash, String data) {Block block = newBlock ("", previousHash, data, Instant.now (). GetEpochSecond (), 0); ProofOfWork pow = ProofOfWork.newProofOfWork (block); PowResult powResult = pow.run (); block.setHash (powResult.getHash ()); block.setNonce (powResult.getNonce ()); return block;}

Create a block

Create Pow algorithm object

Execute Pow algorithm

Save the returned Hash and the operation counter

Test run / * author wangwei * @ date 2018-02-05 * / public class BlockchainTest {public static void main (String [] args) {Blockchain blockchain = Blockchain.newBlockchain (); blockchain.addBlock ("Send 1 BTC to Ivan"); blockchain.addBlock ("Send 2 more BTC to Ivan") For (Block block: blockchain.getBlockList ()) {System.out.println ("Prev.hash:" + block.getPrevBlockHash ()); System.out.println ("Data:" + block.getData ()); System.out.println ("Hash:" + block.getHash ()); System.out.println ("Nonce:" + block.getNonce ()) ProofOfWork pow = ProofOfWork.newProofOfWork (block); System.out.println ("Pow valid:" + pow.validate () + "\ n") }} / * * set TARGET_BITS = 20 The results are as follows: * / Mining the block containing:Genesis Block Elapsed Time: 2.118 seconds correct hash Hex: 00000828ee8289ef6381f297585ef8c952fde93fc2b673ff7cc655f699bb2442 Mining the block containing:Send 1 BTC to Ivan Elapsed Time: 1.069 seconds correct hash Hex: 00000a38c0d7f2ebbd20773e93770298aa8bc0cc6d85fca8756fe0646ae7fea5 Mining the block containing:Send 2 more BTC to Ivan Elapsed Time: 4.258 seconds correct hash Hex: 00000777f93efe91d9aabcba14ab3d8ab8e0255b89818cdb9b93cfa844ad0c7f Prev.hash: Data: Genesis BlockHash: 00000828ee8289ef6381f297585ef8c952fde93fc2b673ff7cc655f699bb2442Nonce: 522163Pow valid: truePrev.hash: 00000828ee8289ef6381f297585ef8c952fde93fc2b673ff7cc655f699bb2442Data: Send 1 BTC to IvanHash: 00000a38c0d7f2ebbd20773e93770298aa8bc0cc6d85fca8756fe0646ae7fea5Nonce: 474758Pow valid: truePrev.hash: 00000a38c0d7f2ebbd20773e93770298aa8bc0cc6d85fca8756fe0646ae7fea5Data: Send 2 more BTC to IvanHash: 00000777f93efe91d9aabcba14ab3d8ab8e0255b89818cdb9b93cfa844ad0c7fNonce: 1853839Pow valid: true so far The study on "how to implement the workload proof mechanism in Java language" 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