Blockchain & Solidity Program Lab Manual
ISBN 9788119221646

Highlights

Notes

  

Prog. 14: Blockchain creation program using Java

Source code

1. import java.security.*; 
import java.util.*;

public class Block

{

long timestamp; 
int index;

String currentHash;

String previousHash;

String data;

int nonce;

public Block(int index, String previousHash, String data)

{

try

{

this.index = index; this.previousHash = previousHash; 
this.data = data;

nonce = 0;

currentHash = calculateHash();

}catch(Exception e){}

} // close constructor

public String calculateHash() throws Exception

{

String input = index + timestamp + previousHash + data + nonce;

MessageDigest digest = MessageDigest.getInstance(“SHA-256”); 
byte [] hash = digest.digest(input.getBytes());

StringBuffer hexString = new StringBuffer();

for(int i=0;i<hash.length;i++)

{

String hex = Integer.toHexString(0xff & hash[i]); 
if(hex.length() == 1)

hexString.append(‘0’); 
hexString.append(hex);

}

return hexString.toString();

} // close calculateHash method

public void minBlock(int difficulty) throws Exception

{

nonce = 0;

String target = new String(new char[difficulty]).replace(‘\0’,’0’); // ‘\0’ -> replace with unicode char with difficulty charcter by character

while(!currentHash.substring(0,difficulty).equals(target))

{

nonce ++;

currentHash = calculateHash();

}

}

public String toString()

{

String s = “Block # “+index+”\r\n”;

s = s+”PreviousHash: “+previousHash+”\r\n”; 
s = s+”TimeStamp: “+timestamp+”\r\n”;

s = s+”Data: “+data+”\r\n”;

s = s+”Nonce: “+nonce+”\r\n”;

s = s+”CurrentHash: “+currentHash+”\r\n”; return s;

}

}

?>?>?>***

2. import java.util.*; 
public class Transaction { 
public String sender; 
public String recipient; 
public float value;

public Transaction(String from, String to, float value) { 
this.sender = from;

this.recipient = to; this.value = value;

}

}

3. BlockChainDemo.java import java.util.*;

public class BlockChainDemo

{

static ArrayList<Block> blockchain = new ArrayList<Block>(); static int difficulty = 5;

public static void main(String args[]) throws Exception

{

Block b = new Block(0,null,”My First Block”); 
b.minBlock(difficulty);

blockchain.add(b);

System.out.println(“ Block1 “+b.toString()); 
System.out.println(“?>?>?>?>?>***”);

Block b1 = new Block(1,b.currentHash,”My Second Block”); b1.minBlock(4);

blockchain.add(b1); System.out.println(“Block2 “+b1.toString());

}

}

Output:

4.

import java.security.*; 
import java.util.*; 
public class Wallet {

public String privateKey; 
public String publicKey; private float balance=100.0f;

private ArrayList<Block2> blockchain = new ArrayList<Block2>(); 
public Wallet(ArrayList<Block2> blockchain) {

generateKeyPair(); 
this.blockchain = blockchain;

}

public void generateKeyPair() {try {

KeyPair keyPair;

String algorithm = “RSA”; //DSA DH etc

keyPair = KeyPairGenerator.getInstance(algorithm). 
generateKeyPair();

privateKey = keyPair.getPrivate().toString(); 
publicKey = keyPair.getPublic().toString();

}catch(Exception e) {

throw new RuntimeException(e);

}

}

public float getBalance() { 
float total = balance;

for (int i=0; i<blockchain.size();i++){ 
Block2 currentBlock = blockchain.get(i);

for (int j=0; j<currentBlock.transactions.size();j++){ 
Transaction tr = currentBlock.transactions.get(j);

if (tr.recipient.equals(publicKey)){ 
total += tr.value;

}

if (tr.sender.equals(publicKey)){ 
total -= tr.value;

}

}

}

return total;

}

public Transaction send(String recipient,float value) { 
if(getBalance() < value) {

System.out.println(“!!!Not Enough funds. Transaction Discarded.”); 
return null;

}

Transaction newTransaction = new Transaction(publicKey, 
recipient, value);

return newTransaction;

}

}

5.

import java.util.*;

public class BlockChainMain4 {

public static ArrayList<Block2> blockchain = new 
ArrayList<Block2>();

public static ArrayList<Transaction> transactions = new 
ArrayList<Transaction>();

public static int difficulty = 5;

public static void main(String[] args) {Wallet A = new Wallet(blockchain); 
Wallet B = new Wallet(blockchain);

System.out.println(“Wallet A Balance: “ + A.getBalance()); 
System.out.println(“Wallet B Balance: “ + B.getBalance());

}

}

Ouput:

6. import java.util.*; 
import java.security.*;

public class Block2 
{ 
public int index; public long timestamp;

public String currentHash; public String previousHash; 
public String data;

public ArrayList<Transaction> transactions = new 
ArrayList<Transaction>(); //our data will be a simple message. public int nonce;

public Block2(int index, String previousHash, 
ArrayList<Transaction> transactions) 
{

this.index = index;

this.timestamp = System.currentTimeMillis(); 
this.previousHash = previousHash; 
this.transactions = transactions;

nonce = 0;

currentHash = calculateHash();

}

public String calculateHash() 
{ 
try 
{

data=““;

for (int j=0; j<transactions.size();j++) 
{ 
Transaction tr = transactions.get(j);

data = data + tr.sender+tr.recipient+tr.value;

}

String input = index + timestamp + previousHash + data + nonce;

MessageDigest digest = MessageDigest.getInstance(“SHA-256”); 
byte[] hash = digest.digest(input.getBytes(“UTF-8”)); 
StringBuffer hexString = new StringBuffer();

for (int i = 0; i < hash.length; i++) 
{

String hex = Integer.toHexString(0xff & hash[i]); 
if(hex.length() == 1) hexString.append(‘0’); 
hexString.append(hex);

}

return hexString.toString();

}

catch(Exception e) 
{

throw new RuntimeException(e);

}

}

public void mineBlock(int difficulty) 
{ 
nonce = 0;

String target = new String(new char[difficulty]).replace(‘\0’, ‘0’);

while (!currentHash.substring(0, difficulty).equals(target)) 
{ 
nonce++;

currentHash = calculateHash();

}

}

public String toString() 
{

String s = “Block #: “ + index + “\r\n”;

s = s + “PreviousHash: “ + previousHash + “\r\n”; 
s = s + “Timestamp: “ + timestamp + “\r\n”;

s = s + “Transactions: “ + data + “\r\n”; 
s = s + “Nonce: “ + nonce + “\r\n”;

s = s + “CurrentHash: “ +currentHash + “\r\n”;

return s;

}

}

7.  
import java.util.*;

public class BlockChainMain5

{

public static ArrayList<Block2> blockchain = new ArrayList<Block2>();

public static ArrayList<Transaction> transactions = new ArrayList<Transaction>(); 
public static int difficulty = 5;

public static void main(String[] args) throws Exception

{

Wallet A = new Wallet(blockchain); 
Wallet B = new Wallet(blockchain);

System.out.println(“Wallet A Balance: “ + A.getBalance()); 
System.out.println(“Wallet B Balance: “ + B.getBalance());

System.out.println(“Add two transactions... “); 
Transaction tran1 = A.send(B.publicKey, 10);

if (tran1!=null)

{

transactions.add(tran1);

}

Transaction tran2 = A.send(B.publicKey, 20); if (tran2!=null)

{

transactions.add(tran2);

}

Block2 b = new Block2(0, null, transactions); 
b.mineBlock(difficulty);

blockchain.add(b);

System.out.println(“Wallet A Balance: “ + A.getBalance()); 
System.out.println(“Wallet B Balance: “ + B.getBalance()); 
System.out.println(“Blockchain Valid: “ + validateChain(blockchain));

} 
// main closed

public static boolean validateChain(ArrayList<Block2> blockchain)

{

if (!validateBlock(blockchain.get(0), null))

{

return false;

}

for (int i = 1; i < blockchain.size(); i++)

{

Block2 currentBlock = blockchain.get(i); Block2 previousBlock = blockchain.get(i - 1);

if (!validateBlock(currentBlock, previousBlock))

{

return false;

}

}

//for closed return true;

}

// validateChain () closed

public static boolean validateBlock(Block2 newBlock, Block2 previousBlock)

{

//The same as before

if (previousBlock == null)

{

//The first block

if (newBlock.index!= 0)

{

return false;

}

if (newBlock.previousHash!= null)

{

return false;

}

if (newBlock.currentHash == null ||!newBlock.calculateHash().equals(newBlock.currentHash))

{

return false;

}

return true;

}

else

{

//The rest blocks

if (newBlock!= null)

{

if (previousBlock.index + 1!= newBlock.index)

{

return false;

}

if (newBlock.previousHash == null ||!newBlock.previousHash.equals(previousBlock.currentHash))

{

return false;

}

if (newBlock.currentHash == null ||!newBlock.calculateHash().equals(newBlock.currentHash))

{

return false;

}

return true;

}

return false;

}

}

}

Output: