DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Game Theory in Blockchain: A Developer's Guide With Java Example
  • Deploying Smart Contract on Ethereum Blockchain
  • Your Go-to Guide to Develop Cryptocurrency Blockchain in Node.Js
  • How Java Apps Litter Beyond the Heap

Trending

  • DGS GraphQL and Spring Boot
  • Unlocking AI Coding Assistants: Generate Unit Tests
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • Measuring the Impact of AI on Software Engineering Productivity
  1. DZone
  2. Coding
  3. Java
  4. A Simple Blockchain in Java

A Simple Blockchain in Java

Popular blockchains like Ethereum are rather complicated. In this post, we strip blockchain down to the basic parts and create a blockchain using POJO in Java.

By 
Amit Rathi user avatar
Amit Rathi
·
Jun. 12, 18 · Tutorial
Likes (51)
Comment
Save
Tweet
Share
46.2K Views

Join the DZone community and get the full member experience.

Join For Free

I’m sure we all have heard about cryptocurrency and blockchain and how interrelated they are, which is true too, but they are actually very different and can exist independently. Cryptocurrency is more of a product, while blockchain is a technology to facilitate transactions among trust-less parties.

A complete production-ready blockchain application could be large and complicated, but, at its heart, it’s a very simple but powerful concept. A blockchain is a collection of blocks which can contain one or more transactions. Each block is hashed, and the hashes are then paired, hashed, paired again, and hashed again until a single hash remains, the Merkle root of a Merkle tree.

Each block stores the hash of the previous block, chaining the blocks together. This ensures a block cannot be modified without modifying all the following blocks. Below is the probably simplest (Hello World) blockchain in Java.

This is a simple block representation (POJO) in Java. It holds data as a string but it could be anything that you can imagine, including Ethereum style smart contracts.

package org.demo;

import lombok.Getter;
import lombok.ToString;

import java.util.Arrays;

@Getter
@ToString
public class Block {
    private int previousHash;
    private String data;
    private int hash;

    public Block(String data, int previousHash) {
        this.data = data;
        this.previousHash = previousHash;

        // Mix the content of this block with previous hash to create the hash of this new block
        // and that's what makes it block chain
        this.hash  = Arrays.hashCode(new Integer[]{data.hashCode(), previousHash});
    }
}

And below is a simple blockchain implementation with very basic validation functionality.

package org.demo;

import java.util.ArrayList;
import java.util.List;

public class BlockChain {
    public static void main(String[] args) {
        List<Block> blockChainList =  new ArrayList<>();

        Block genesis = new Block("BlockChain", 0);
        blockChainList.add(genesis);

        Block helloBlock = new Block("Hello", blockChainList.get(blockChainList.size()-1).getHash());
        blockChainList.add(helloBlock);

        Block worldBlock = new Block("World", blockChainList.get(blockChainList.size()-1).getHash());
        blockChainList.add(worldBlock);

        Block dZoneBlock = new Block("DZone", blockChainList.get(blockChainList.size()-1).getHash());
        blockChainList.add(dZoneBlock);

        System.out.println("---------------------");
        System.out.println("- BlockChain -");
        System.out.println("---------------------");
        blockChainList.forEach(System.out::println);
        System.out.println("---------------------");
        System.out.println("Is valid?: " + validate(blockChainList));
        System.out.println("---------------------");

        // corrupt block chain by modifying one of the block
        Block hiBlock = new Block("Hi", genesis.getHash());
        int index = blockChainList.indexOf(helloBlock);
        blockChainList.remove(index);
        blockChainList.add(index, hiBlock);
        System.out.println("Corrupted block chain by replacing 'Hello' block with 'Hi' Block");

        System.out.println("---------------------");
        System.out.println("- BlockChain -");
        System.out.println("---------------------");
        blockChainList.forEach(System.out::println);
        System.out.println("---------------------");
        System.out.println("Is valid?: " + validate(blockChainList));
        System.out.println("---------------------");


    }

    private static boolean validate(List<Block> blockChain) {
        boolean result = true;

        Block lastBlock = null;
        for(int i = blockChain.size() -1; i >= 0; i--) {
            if(lastBlock == null) {
                lastBlock = blockChain.get(i);
            }
            else {
                Block current = blockChain.get(i);
                if(lastBlock.getPreviousHash() != current.getHash()) {
                    result = false;
                    break;
                }
                lastBlock = current;
            }
        }

        return result;
    }
}

That’s it for now. Hope it helps. Happy Coding!

Blockchain Java (programming language) Blocks

Opinions expressed by DZone contributors are their own.

Related

  • Game Theory in Blockchain: A Developer's Guide With Java Example
  • Deploying Smart Contract on Ethereum Blockchain
  • Your Go-to Guide to Develop Cryptocurrency Blockchain in Node.Js
  • How Java Apps Litter Beyond the Heap

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: