Simple blockchain implementation in Java

1. An overview of the

In this article, we will learn the basic concepts of blockchain technology. A basic application will also be implemented using Java based on the concept.

Further, we will discuss some advanced concepts and practical applications of this technology.

2. What is blockchain?

So let’s first understand what blockchain really is…

Its origins can be traced back to a white paper published on Bitcoin by Satoshi Nakamoto in 2008.

Blockchain is a decentralized ledger of information. It consists of blocks of data connected through the use of cryptography. It belongs to a network of nodes connected over a public network. We’ll understand this better later when we try to build a basic tutorial.

There are some important attributes that we need to understand, so let’s take a look at them:

  • First and foremost, ** data as part of a block is tamper-proof. ** Each block is referenced by a cryptographic digest, often called a hash, making the block tamper-proof.
  • The whole blockchain is Decentralized on the network. This means that there is no master node and that every node in the network has an identical copy.
  • Transparent: Each participating node in the network is verified by consensus with other nodes and adds a new block to its chain **. Therefore, each node has complete data visibility.

3. How does blockchain work?

Now, let’s see how blockchain works.

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

! [img](https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/11/13/16e6203d469d2372~tplv-t2oaga2asx-image.i mage)

We use a hash to represent a block. The hash value of the generated block is called a “mining” block. Mining blocks are often computationally expensive because they serve as “proof of work.”

A block hash usually consists of the following data:

  • First, the hash value of a block consists of encapsulated transactions.
  • Hashes also consist of timestamps created by blocks
  • It also includes a nonce, an arbitrary number used in cryptography
  • Finally, the hash of the current block also includes the hash of the previous block

Multiple nodes in the network can simultaneously mine data blocks. In addition to generating the hash, the node must verify that the transaction added to the block is valid. Dig one block first, win the race!

3.2. Add blocks to the blockchain

When mining a block is computationally expensive, verifying that the block is valid is relatively simple. All nodes on the network participate in validating the newly mined block.

! [img](https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/11/13/16e6203d9536ed02~tplv-t2oaga2asx-image.i mage)

Therefore, newly mined blocks are added to the blockchain when the nodes agree.

Now, we can use several consensus protocols for validation. Nodes in the network use the same protocol to detect malicious branches of the chain. Therefore, even if a malicious branch is introduced, most nodes will quickly reject it.

4. Basic blockchain in Java

We now have enough context to start building a basic application in Java.

Our simple example here demonstrates the basic concepts we just saw. Production-grade applications involve many considerations that are beyond the scope of this tutorial. However, we will discuss some advanced topics later.

4.1 blocks

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

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

Let’s take a look at what we packed here:

  • The hash of the previous block is an important part of building the chain
  • Actual data, any valuable information, such as contracts
  • Timestamp of block creation
  • Nonce is an arbitrary number used in cryptography
  • Finally, the hash of the block is computed from other data

4.2. Compute the hash

Now, how do we compute the hash of a block? We use method calculateBlockHash, but we haven’t seen the implementation yet. Before implementing this method, it’s worth taking the time to understand what a hash is.

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

Furthermore, it is impossible to get input data from its hash alone. These properties make hash functions very useful in cryptography.

So, let’s look at how to generate a block hash 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("%02x", b));
    }
    return buffer.toString();
}Copy the code

There’s a lot going on here, so let’s take a closer look:

  • First, we concatenate the different parts of the block to generate a hash
  • And then we go fromMessageDigestGets an instance of the SHA-256 hash function in
  • We then generate a hash of the input data, which is a byte array
  • Finally, we convert the byte array to a hexadecimal string, and the hash is usually represented as a 32-bit hexadecimal number

4.3. Have we dug it?

So far, it all sounds simple and elegant, except we haven’t mined the blocks yet. So what is it that needs to be mined for a block has intrigued developers for some time!

Thus, mining a block means solving a computationally complex task for the block. While calculating the hash of a block is relatively simple, finding a hash that begins with five zeros is not. Even more complicated is finding a hash that starts with 10 zeros, and we get a general idea.

So, what are we going to do? To be honest, this solution is not as good as it looks! We did it by brute force. We use nonce here:

public String mineBlock(int prefix) { String prefixString = new String(new char[prefix]).replace('\0', '0'); while (! hash.substring(0, prefix).equals(prefixString)) { nonce++; hash = calculateBlockHash(); } return hash; }Copy the code

Let’s see what we do:

  • We first define the prefix to look for
  • Then we check to see if we have the answer
  • If not, the nonce is increased and the hash is computed in the loop
  • The cycle continues until we hit the jackpot

We start with the default value of nonce and increment it by 1. In real applications, however, there are more sophisticated policies for starting and increasing nonce. In addition, we did not validate our data, which is usually an important part.

4.4. Run the example

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

List<Block> blockchain = new ArrayList<>();
int prefix = 4;
String prefixString = new String(new char[prefix]).replace('\0', '0');Copy the code

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

Let’s see how to add a block here:

@Test
public void givenBlockchain_whenNewBlockAdded_thenSuccess() {
    Block newBlock = new Block(
      "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);
}Copy the code

4.5. Blockchain verification

How does the node verify that the blockchain is valid? While this can be quite complicated, let’s consider a simple version:

@Test public void givenBlockchain_whenValidated_thenSuccess() { boolean flag = true; for (int i = 0; i < blockchain.size(); i++) { String previousHash = i==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); }Copy the code

So, here we perform three specific checks on each block:

  • The hash of the stored current block is actually what it evaluates
  • The hash of the previous block stored in the current block is the hash of the previous block
  • The current block has been mined

5. Some advanced concepts

While our basic example demonstrates the basic concepts of blockchain, it is certainly not complete. Several other factors need to be considered before the technology can be put into practical use.

While it’s impossible to go into all the details, let’s take a look at some of the important ones:

5.1. Transaction validation

Calculating the hash of a block and finding the desired hash is only part of the mining. Blocks are composed of data, usually in the form of multiple transactions. It must be verified before it becomes part of the block and can be mined.

A typical implementation of blockchain places limits on how much data can be contained in a block. It also sets rules for how transactions are validated. Multiple nodes in the network participate in the validation process.

5.2. Alternate consensus Agreement

The consistency algorithms we see, such as “proof of work”, are used to mine and validate blocks. However, this is not the only consistency algorithm available.

There are several other consistency algorithms to choose from, such as equity proof, authority proof, and weight proof. All of these have their advantages and disadvantages. Which one to use depends on the type of application we intend to design.

5.3. Dig for rewards

Blockchain networks typically consist of voluntary nodes. Now, why would anyone want to contribute to this complex process and keep it legitimate and growing?

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

5.4. Node type

Blockchain relies entirely on the network to operate. In theory, the network is completely decentralized and every node is equal. In practice, however, networks are made up of many types of nodes.

While a full node has a full list of transactions, a lightweight node has only a partial list. In addition, not all nodes participate in validation and validation.

5.5. Secure communications

One of the hallmarks of blockchain technology is its openness and anonymity. But how does it provide security for insider trading? This is based on encryption and public key infrastructure.

The transaction founder uses the private key to secure it and attaches it to the recipient’s public key. The node can use the public key participating in the validation transaction.

6. Practical application of blockchain

So blockchain seems like an exciting technology, but it also has to prove useful. The technology has been around for a while, and needless to say, it has proven disruptive in many areas.

Its applications in many other fields are actively underway. Let’s get to know the most popular apps:

  • Currency: Thanks to the success of Bitcoin, this is by far the oldest and best known blockchain application. They provide safe, frictionless finance to people around the world, without the need for any central government or government intervention.
  • Identity: Digital identities are fast becoming the norm in today’s world. However, this can get bogged down in security issues and tampering. Blockchain is inevitable in revolutionizing the field, with completely secure and tamper-proof identities.
  • Health care: The health care industry is awash with data, mostly handled by the central government. This reduces transparency, security, and efficiency in processing such data. Blockchain technology can provide a system without any third party providing much-needed trust.
  • Government: This is perhaps an area that could be easily disrupted by blockchain technology. Blockchain can build a better relationship between government and citizens. The government is usually the center of several civic services, which are often riddled with inefficiency and corruption.

7. Industry tools

While our basic implementation here helps to introduce concepts, developing products on blockchain from scratch is not practical. Thankfully, the field is now mature and we do have some very useful tools to start using.

Let’s take a look at some popular tools working in this area:

  • Solidity: Solidity is a statically typed and object-oriented programming language designed for writing smart contracts. It can be used to write smart contracts on a variety of blockchain platforms like Ethereum.
  • Remix IDE: Remix is a powerful open source tool for writing smart contracts using Solidity. This allows users to write smart contracts directly from the browser.
  • Truffle Suite: Truffle provides a number of tools to help developers start developing distributed applications.
  • Ethlint/Solium: Solium allows developers to ensure that smart contracts they write on Solidity are free of style and security issues. At the same time, Solium also helps to deal with these problems.
  • Parity: Parity helps set up the development environment for smart contracts on Etherium. It provides a fast and efficient way to interact with the blockchain.

Conclusion 8.

In summary, in this section, we have learned the basic concepts of blockchain technology. We understand how the network mines and adds new blocks to the blockchain. In addition, we implemented the basic concepts in Java. We also discussed some advanced concepts related to it.

Finally, we summarize some practical applications of blockchain and the tools available.

As always, the code can be found on GitHub.

Original: https://www.baeldung.com/java-blockchain

By Kumar Chandrakant

Translator: Queena ——

September welfare, concern public number background reply: 004, receive translation collection in August! Previous welfare reply: 001,002, 003 can be collected!