Skip to content

Instantly share code, notes, and snippets.

@AllanJunLi
Last active November 6, 2018 05:50
Show Gist options
  • Save AllanJunLi/81fa1ed6a95d7c6170ddb066a548ce5e to your computer and use it in GitHub Desktop.
Save AllanJunLi/81fa1ed6a95d7c6170ddb066a548ce5e to your computer and use it in GitHub Desktop.
Java implementation of blockchain concept
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.List;
public class BlockChain {
static class Block {
private long index;
private LocalDateTime timeStamp;
private String data;
private String previousBlockHash;
private String currentHash;
public Block(long index, LocalDateTime timeStamp, String data, String previousBlockHash) {
super();
this.index = index;
this.timeStamp = timeStamp;
this.data = data;
this.previousBlockHash = previousBlockHash;
String blockDetails = index + timeStamp.toString() + data + previousBlockHash;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(blockDetails.getBytes(StandardCharsets.UTF_8));
currentHash = Base64.getEncoder().encodeToString(hash);
} catch (NoSuchAlgorithmException e) {
// if setup is correct this will not happen, do nothing
}
}
public long getIndex() {
return index;
}
public LocalDateTime getTimeStamp() {
return timeStamp;
}
public String getData() {
return data;
}
public String getPreviousBlockHash() {
return previousBlockHash;
}
public String getCurrentHash() {
return currentHash;
}
@Override
public String toString() {
return "Block [index=" + index + ", timeStamp=" + timeStamp + ", data=" + data + ", previousBlockHash="
+ previousBlockHash + ", currentHash=" + currentHash + "]";
}
}
Block genesis = new Block(0, LocalDateTime.now(), "Genesis Block", "0");
List<Block> chain = new ArrayList<>();
BlockChain() {
chain.add(genesis);
}
Block getGenesisBlock() {
return genesis;
}
int getSize() {
return chain.size();
}
Collection<Block> getChain() {
return chain;
}
Block createNextBlock(Block lastBlock) {
long currentIndex = lastBlock.getIndex() + 1;
Block block = new Block(currentIndex, LocalDateTime.now(), "new block #" + currentIndex, lastBlock.getCurrentHash());
chain.add(block);
return block;
}
public static void main(String[] args) {
BlockChain blockChain = new BlockChain();
int numberOfBlocks = 20;
Block last = blockChain.getGenesisBlock();
for (int i = 0; i < numberOfBlocks; i++) {
Block next = blockChain.createNextBlock(last);
System.out.println("Block " + next.getIndex() + " added: " + next.getCurrentHash());
last = next;
}
System.out.println();
System.out.println("Block chain length: " + blockChain.getSize());
for (Block block : blockChain.getChain()) {
System.out.println(block);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment