Blockchain simple java implementation       -part 2-

Blockchain simple java implementation -part 2-

Welcome to the second part of the blockchain series, for all the reader who came from the part one, I deeply apologize for the late, but I wanted the second part to be more of technical way to view this technology, if you are like me, I learn by implementing the abstract, a trial and error way to learn if you would allow me to say.

without further adue I'd like to present you my own modest implementation sort of a chain of blocks which is in java 8 language, used spring boot just to interect with it a bit and make it a bit at REST if you know what I mean...

the code in the below link.

Distributed Ledger Technology DLT

We all know that all the hype that the Blockchain is, it's about its system of recording information (transactions) in a way that makes it difficult or impossible to modify, hack, or cheat the system.

A blockchain is a digital ledger of transactions that is duplicated and distributed across the entire network of computer systems on the blockchain.

Each block in the chain contains a number of transactions, and every time a new transaction occurs on the blockchain, a record of that transaction is added to every participant’s ledger. The decentralised database managed by multiple participants is known as Distributed Ledger Technology (DLT).

Blockchain is a type of DLT in which transactions are recorded with an immutable cryptographic signature called a?HASH.

Here its properties for more insight.

Aucun texte alternatif pour cette image

In this article I'll try to implement these properties, for the code that I'll share here has more or less covered 5 out of 7 which are :

Anonymous, Secure : for the indivdual encryption, Time-stamped : a timestamped block, Immutable : can't be changed, Unanimous: with a simple simulated mining process for adding blocks

I'll start with the Block class, I added 2 constructors, the first to create the blocks including the genesis block which the first block of the blockchain, the second one is to make it easy for adding blocks, you'll see what I mean when I get to the controller part, the block will be created with his own hash and a previous block's hash (linking and immutability), adding a block needs a mining simulated through the miningBlock method with a difficulty setting to solve "puzzle", if you're curious how this mining goes, it's just a rehashing of the block until the first 2 or 3 characters of the hash are consecutive 0s.

public class Block {

    private int index;
    private String data;
    private Date timestamp;
    private String previousHash;
    private String hash;
    private int nonce;

    public Block(int index, String data, Date timestamp, String previousHash) {
        this.index = index;
        this.data = data;
        this.timestamp = timestamp;
        this.previousHash = previousHash;
        this.hash = this.calculateHash();
        this.nonce = 0;

    }

    public Block(int index, String data, Date timestamp) {
        this.index = index;
        this.data = data;
        this.timestamp = timestamp;
        this.hash = this.calculateHash();
        this.nonce = 0;
    }

    public String calculateHash(){
        try {
            MessageDigest msgDigest = MessageDigest.getInstance("SHA-256");
            String input = this.index + this.timestamp.toString() + this.previousHash + this.data + this.nonce;
            byte[] inputDigest = msgDigest.digest(input.getBytes());
            BigInteger inputDigestBigInt = new BigInteger(1, inputDigest);
            String hashtext = inputDigestBigInt.toString(16);
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        }

        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

    }

    public String miningTheBlock(int difficulty){

        while(!(this.hash.substring(1, difficulty).equals(Arrays.toString(new int[difficulty - 1])
                .replace("[", "")
                .replace("]", "")
                .replace(",", "")
                .replace(" ", "")))){

            this.nonce++;
            this.hash = calculateHash();
            System.out.println(this.hash.substring(1, difficulty));

        }

        System.out.println("block mined = " + this.hash);
        return this.hash;

    }

    //getters & setters
    ...

}
        

Blockchain class, is basically the service, responsable for linking the blocks together , the method isChainValid() makes sure that the blocks haven't been tampered with

public class BlockChain {

    private int difficulty = 3;
    private int miningReward = 30;
    private ArrayList<Transaction> transactions = new ArrayList<>();
    private ArrayList<Block> chain = new ArrayList<Block>();

    public BlockChain() {
        this.chain.add(creatGenesisBlock());
    }

    private Block creatGenesisBlock(){
        return new Block(0, "Genesis Block", new Date(), "0" );
    }

    private Block getLastBlock(){
        return chain.get(chain.size() - 1);
    }

    public void addBlock(Block newBlock){

        newBlock.setPreviousHash(getLastBlock().getHash());
        newBlock.setHash(newBlock.miningTheBlock(this.difficulty));
        chain.add(newBlock);
    }

    public boolean isChainValid(){
        for(int i = 1; i < chain.size(); i++){
            Block currentBlock = chain.get(i);
            Block previousBlock = chain.get(i - 1);

            if(currentBlock.getHash() != currentBlock.calculateHash())
                return false;

            if(currentBlock.getPreviousHash() != previousBlock.getHash())
                return false;
        }

        return true;
    }

    public ArrayList<Block> getChain() {
        return chain;
    }

    public void setChain(ArrayList<Block> chain) {
        this.chain = chain;
    }
}
        

The controller, I decided to add it just to make it open to visualize it in a next iteration of part 3 maybe

@RestController
public class BlockChainController {


    @GetMapping("rest/add-block")
    public ResponseEntity<List<Block>> addBlock() {
        BlockChain pragmaCoin = new BlockChain();
        Block newBlock = new Block(1, "this is the first transaction", new Date());
        Block newBlock1 = new Block(2, "this is the second transaction", new Date());
        Block newBlock2 = new Block(3, "this is the third transaction", new Date());
        Block newBlock3 = new Block(4, "this is the fourth transaction", new Date());

        System.out.println("mining in process ...");
        pragmaCoin.addBlock(newBlock);
        System.out.println("mining in process ...");
        pragmaCoin.addBlock(newBlock1);
        System.out.println("mining in process ...");
        pragmaCoin.addBlock(newBlock2);
        System.out.println("mining in process ...");
        pragmaCoin.addBlock(newBlock3);

        //newBlock1.setData("this is a tampered data");

        //System.out.println("Is this blockchain valid = " + pragmaCoin.isChainValid());



        return new ResponseEntity(pragmaCoin.getChain(), HttpStatus.OK);
    }


}
        

add-block endpoint

Aucun texte alternatif pour cette image

You'll find this modest code in the link below, Thank you for your time.

https://github.com/pragmatic-consulting/blockchain-java-impl

@author ~KK~

要查看或添加评论,请登录

PRAGMATIC Consulting的更多文章