A Simple Blockchain in Java

I鈥檓 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鈥檚 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 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 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鈥檚 it for now. Hope it helps. Happy Coding!

文章来源于互联网:A Simple Blockchain in Java

发布者:小站,转转请注明出处:http://blog.gzcity.top/4243.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022年5月3日 18:09
下一篇 2022年5月3日 18:09

相关推荐

  • Go Application Vulnerability Cheatsheet

    Securing applications is not the easiest thing to do. An application has many components: server-side logic, client-side logic, data storage, data transportation, API, and more. Wi…

    安全 2022年5月3日
    1.2K30
  • Scalable JWT Token Revokation in Spring Boot

    With stateless JWT Tokens for security, short TTLs (1 min) can be used. These tokens are then refreshed during their time to live. If the server does not get to know when a user ha…

    2022年5月3日
    46560
  • OAuth 2.0 Beginner’s Guide

    This article provides an overview of OAuth 2.0 protocol. It discusses the different actors and steps involved in the process of OAuth 2.0 implementation. Introduction: OAuth stands…

    2022年5月3日
    5.1K13460
  • Angular + React: Vulnerability Cheatsheet

    Securing applications is not the easiest thing to do. An application has many components: server-side logic, client-side logic, data storage, data transportation, API, and more. Wi…

    安全 2022年5月3日
    686100
  • Everything About HTTPS and SSL (Java)

    Many articles, papers, and blogs have already talked about HTTPS, SSL, and web security. Nevertheless, people still miss the basics. In this article, I tried to put all things toge…

    2022年5月3日
    48810

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

评论列表(4条)

  • Binance referal code
    Binance referal code 2024年8月2日 08:32

    Your point of view caught my eye and was very interesting. Thanks. I have a question for you.

  • Реферальный код на binance

    Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  • Clydethuse
    Clydethuse 2024年12月28日 15:52

    Лучшие 10 программ https://www.cctvfocus.ru для видеонаблюдения. Программное обеспечение для видеонаблюдения. При выборе программного обеспечения важно учитывать наличие функции обнаружения объектов с использованием искусственного интеллекта.

  • Clydethuse
    Clydethuse 2024年12月28日 17:10

    Лучшие 10 программ https://www.cctvfocus.ru для видеонаблюдения. Программное обеспечение для видеонаблюдения. При выборе программного обеспечения важно учитывать наличие функции обнаружения объектов с использованием искусственного интеллекта.