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 write the code of a simple block chain program implemented by Java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

The main content of this article is to explain "Java to achieve a simple block chain program code how to write", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "Java to achieve a simple block chain program code how to write" it!

What is a blockchain?

So, let's take a look at what the blockchain is.

Well, its origins can be traced back to Satoshi Nakamoto's 2008 white paper on bitcoin.

Blockchain is a decentralized information ledger. It consists of data blocks connected by using cryptography. It belongs to a network of nodes connected through a public network. We will better understand this when we try to build a basic tutorial later.

We must understand some important attributes, let's take a look at:

Tamper-proof: first of all, data is tamper-proof as part of a block. Each block is referenced by an encrypted digest (often called a hash), making the block tamper-proof.

Decentralization: the entire block chain is completely decentralized on the network. This means that there is no primary node, and each node in the network has the same copy.

Transparency: each node participating in the network verifies its chain and adds a new block by agreeing with other nodes. Therefore, each node has full visibility of the data.

How does the blockchain work?

Now, let's take a look at how blockchains work.

The basic unit of a block chain is a block. A single block can encapsulate multiple transactions or other valuable data:

Mining block

We use hash values to represent a block. The hash value of the generated block is called the "mining" block. Mining a block is usually costly because it is a "proof of work".

The hash of a block usually consists of the following data:

First, the hash of a block consists of the transactions it encapsulates

The hash also includes the timestamp of the block creation

It also includes a nonce, an arbitrary number for cryptography

Finally, the hash of the current block also includes the hash of the previous block

Multiple nodes in the network can compete for mining blocks at the same time. In addition to generating a hash, the node must also verify that the transaction added to the block is legal. The first digger wins the game!

Add blocks to the block chain

Although the computational cost of mining blocks is high, it is relatively easy to verify whether the blocks are legal or not. All nodes in the network participate in verifying newly mined blocks.

Therefore, if the nodes are consistent, a newly mined block is added to the block chain.

Now, there are several consensus agreements that we can use to verify. Nodes in the network use the same protocol to detect malicious branches of the chain. Therefore, even if malicious branches are introduced, they will soon be rejected by most nodes.

Basic Block chain in Java

Now we have enough context to start building a basic application with Java.

Our simple example here will illustrate the basic concepts we have just seen. Production applications need to consider a number of issues that are beyond the scope of this tutorial. However, we will discuss some advanced topics later.

Implementation block

First, we need to define a simple POJO to hold the block data:

Public class Block {private String hash; private String previousHash; private String data; private long timeSt private int nonce; public Block (String data, String previousHash, long timeStamp) {this.data = data; this.previousHash = previousHash; this.timeStamp = timeSt this.hash = calculateBlockHash ();} / / standard getters and setters}

Let's take a look at what we're packing here:

Nonce

Computational hash

Now, how do we calculate the hash of blocks? We've used the calculateBlockHash method, but we haven't seen the implementation yet. Before we implement this approach, it's worth taking some time to understand what a hash is.

A hash is the output of a hash function. The hash function maps input data of any size to output data of a fixed size. Hashes are very sensitive to any changes in the input data, no matter how small the changes are.

In addition, it is not possible to get input data only from the hash. These attributes make hash functions very useful in cryptography.

So, let's take a look at how to generate a hash of blocks in Java:

Public String calculateBlockHash () {String dataToHash = previousHash + Long.toString (timeStamp) + Integer.toString (nonce) + data; MessageDigest digest = null; byte [] bytes = null; try {digest = MessageDigest.getInstance ("SHA-256"); bytes = digest.digest (dataToHash.getBytes (UTF_8));} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {logger.log (Level.SEVERE, ex.getMessage ()) } StringBuffer buffer = new StringBuffer (); for (byte b: bytes) {buffer.append (String.format ("x", b));} return buffer.toString ();} public String calculateBlockHash () {String dataToHash = previousHash + Long.toString (timeStamp) + Integer.toString (nonce) + data; MessageDigest digest = null; byte [] bytes = null Try {digest = MessageDigest.getInstance ("SHA-256"); bytes = digest.digest (dataToHash.getBytes (UTF_8));} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {logger.log (Level.SEVERE, ex.getMessage ());} StringBuffer buffer = new StringBuffer (); for (byte b: bytes) {buffer.append (String.format ("x", b));} return buffer.toString ();}

There's a lot going on here, let's take a closer look at it:

MessageDigest

Did we dig on that piece of land?

So far, everything sounds simple and elegant, but we haven't mined the block yet. So, exactly need to dig a block, which has attracted the imagination of developers for some time!

Well, digging a block means solving a computationally complex task for that block. Although calculating the hash of a block is a bit trivial, finding a hash that starts with five zeros is not. What's more complicated is to find a hash that starts with ten zeros, and we get a general idea.

So, what exactly are we supposed to do? To be honest, this solution is not that fancy! We use brute force to achieve this goal. We use nonce here:

Public String mineBlock (int prefix) {String prefixString = new String (new char [prefix]). Replace (','0'); while (! hash.substring (0, prefix) .equals (prefixString)) {nonce++; hash = calculateBlockHash ();} return hash;}

Let's see what we need to do:

Nonce

Let's start with the default value nonce and increment it by 1. However, in real-world applications, there are more complex strategies to start and add a moment. In addition, we do not validate our data here, which is usually an important part.

Let's run this example

Now that we have defined the block and its functions, we can use it to create a simple block chain. We store this in ArrayList:

List blockchain = new ArrayList (); int prefix = 4x string prefixString = new String (new char [prefix]) .replace ('','0')

In addition, we define a prefix of 4, which actually means that we want the hash to start with 4 zeros.

Let's see how to add blocks here:

@ Testpublic void givenBlockchain_whenNewBlockAdded_thenSuccess () {Block newBlock = newBlock ("The is a New Block.", blockchain.get (blockchain.size ()-1). GetHash (), new Date (). GetTime (); newBlock.mineBlock (prefix); assertTrue (newBlock.getHash (). Substring (0, prefix) .equals (prefixString)); blockchain.add (newBlock);} Block chain verification

How does the node verify the validity of the blockchain? While this may be quite complex, let's consider a simple version:

@ Testpublic void givenBlockchain_whenValidated_thenSuccess () {boolean flag = true; for (int I = 0; I < blockchain.size (); iTunes +) {String previousHash = iTunes 0? "0": blockchain.get (I-1) .getHash () Flag = blockchain.get (I). GetHash (). Equals (blockchain.get (I). CalculateBlockHash ()) & & previousHash.equals (blockchain.get (I). GetPreviousHash ()) & & blockchain.get (I). GetHash (). Substring (0, prefix) .equals (prefixString); if (! flag) break;} assertTrue (flag);}

As a result, we conducted three specific checks on each block:

The hash value stored in the current block is actually the value it calculates.

The hash of the previous block stored in the current block is the hash of the previous block.

The current block has been mined

Some advanced concepts

Although our basic example introduces the basic concept of blockchain, it is certainly incomplete. In order to put this technology into practical application, several other factors need to be considered.

Although it is impossible to elaborate on all of these issues, let's take a look at some of the important ones:

Transaction verification

Calculating the hash of the block and finding the desired hash is only part of the mining. Data blocks are made up of data, usually in the form of multiple transactions. It must be verified before it can be exploited as part of the block.

A typical implementation of a blockchain sets limits on how much data a chunk can contain. It also sets rules for how transactions are validated. Multiple nodes in the network participate in the verification process.

Alternative consensus Protocol

We see consensus algorithms such as work proof being used to mine and validate a block. However, this is not the only consistency algorithm available.

There are several other consensus algorithms to choose from, such as interest proof, authority proof and weight proof. All of this has its advantages and disadvantages. Which one to use depends on the type of application we intend to design.

Mining reward

Blockchain networks are usually made up of voluntary nodes. Now, why would anyone want to contribute to this complex process and maintain its legitimacy and growth?

This is because the node is rewarded for validating transactions and mining blocks. These awards are usually in the form of coins associated with the application. But an application can decide that the reward is anything of value.

Node Typ

Blockchain relies entirely on its network to operate. In theory, the network is completely decentralized and every node is equal. In practice, however, a network consists of multiple types of nodes.

The full node has a complete list of transactions, while the lightweight node has only a partial list. In addition, not all nodes participate in verification and validation.

Secure communication

One of the characteristics of blockchain technology is its openness and anonymity. But how does it provide security for internal transactions? This is based on cryptography and public key infrastructure.

The initiator of the transaction uses their private key to protect it and attach it to the receiver's public key. The node can use the participant's public key to authenticate the transaction.

Practical Application of Block chain

As a result, blockchain seems to be an exciting technology, but it must also prove useful. This technology has been around for some time and, needless to say, it has proved to be destructive in many areas.

Its application in many other fields is being actively carried out. Let's take a look at the most popular applications:

Currency: due to the success of Bitcoin, this is by far the oldest and most well-known blockchain application. They provide safe and frictionless funding for people around the world without any central authority or government intervention.

Identity: digital identity is rapidly becoming the norm in today's world. However, this is mired in security problems and tampering. It is inevitable that blockchain will revolutionize this field with a completely secure and tamper-proof identity.

Health care: the health care industry is full of data, mainly handled by the central authorities. This reduces the transparency, security, and efficiency of processing such data. Blockchain technology can provide a system in which no third party provides much-needed trust.

Government: this may be an area that is easily undermined by blockchain technology. The government is usually the center of citizen services, which are often rife with inefficiency and corruption. Blockchain can help build a better relationship between government and citizens.

Industry tools

While our basic implementation here helps lead to the concept, it is impractical to develop the product on the blockchain from scratch. Thankfully, this field is now mature, and we do have some very useful tools to get started.

Let's take a look at some popular tools to work in this space:

Solidity: Solidity is a statically typed object-oriented programming language for writing smart contracts. It can be used to write intelligent contracts on various blockchain platforms such as Etay Fong.

RemixIDE: Remix is a powerful open source tool that can steadily write smart contracts. In this way, users can write smart contracts directly from the browser.

Truffle Suite: Truffle provides a range of tools to help developers start developing distributed applications. This includes truffles, Ganache and drizzle.

Ethlint/Solium: Solium allows developers to ensure that the smart contracts they write on Solidity are free of style and security issues. Solium also helps to solve these problems.

Parity: Parity helps to build a development environment for ethernet smart contracts. It provides a fast and secure way to interact with block chains.

At this point, I believe that everyone on the "Java to achieve a simple block chain program code how to write" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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

Development

Wechat

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

12
Report