Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

CLASSES where you add code: Miner doProofOfWork method: The logic behind this will be reviewed in class. This method should first create a string that

CLASSES where you add code:

Miner

doProofOfWork method: The logic behind this will be reviewed in class.

This method should first create a string that has as many zeros in it as oBlock.getDifficulty() equals.

Hint: use a while loop here that keeps looping while the length of this string youre creating is less than the target difficulty length.

Then, this method should have another while loop that keeps looping until a valid nonce is found.

There needs to be an if --- else in this while loop.

If bAbortPoW (an instance variable youll see at the top of the class) equals true, then this means another miner solved the block and this miner received it, so you need to:

Set bAbortPoW back to false.

Print out something to the user like:

"[miner] Aborted mining block, probably because another confirmed block received."

Return false so the method ends.

Else perform another attempt at a valid nonce:

The nonce should start at 0 before the while loop and increment each loop.

A valid nonce, after its added to the blocks properties and the block is hashed, should result in a hash that has as many leading zeros as the string you created above (use Strings startsWith method for this check).

So remember that on oBlock you have to call:

Set nonce.

Compute hash.

Set hash to whatever came back from compute hash.

Then check if hash on oBlock now begins with your leading zeroes string you created above.

If it does, then return true.

Block

computeMerkleRoot:

Choose which approach you want to take:

The 90% approach is much easier and is based on what weve done in class but your max score for the project can only reach 90%.

The 100% approach is much trickier, and you must figure out on your own.

90% Project Score Logic: This logic needs to account for possibly 2 or 4 items in lstItems that are passed in.

This means your code should have 2 or 4 Merkle Tree leaves depending on how many items are passed in.

100% Project Score Logic: You can only get 90% on this project if everything else is done perfectly. To get 100%, you must make this method flexible to accept any power of 2 items. So lstItems could be 2,4,8,16,32, etc. and your code would be able to compute the Merkle Root.

IMPORTANT: If you choose this route, youll have to show me your logic in class one week before the project is due.

NOTE: There is a main method at the bottom of this class that you can use to test 2 and 4 items simply by right clicking on the tab for this class and selecting Run Block.main()

populateMerkleNode:

This method will work just as we did in class set the left and right nodes and then call generateHash in the BlockchainUtil class and set the nodes hash.

BlockchainUtil

generateHash:

This method generates a SHA-256 hash of the string passed in.

Code for this was reviewed in class and doesnt need to be changed.

P2PMessageQueue

enqueue:

This adds a node to the queue.

Code will be reviewed in class.

dequeue:

This removes and returns a node from the queue.

Code will be reviewed in class.

hasNodes:

This returns true or false depending on if any nodes exist in queue.

Code will be reviewed in class.

P2PUtil

connectForOneMessage:

This method will connect to a given server via Socket for a one-time sending of a message to that server and it will return the reply from the server and disconnect.

Code for the Socket communication will be reviewed in class.

Testing Your Code

You need to run two instances of this app so that they can communicate with each other.

One app can be run from your IDE like you normally do.

The other app must be ran from a PowerShell window or other command line tool as explained below.

Running a separate instance of your app:

Jar file generation

You first need to build your code into a JAR file.

Instructions are included with the project online and will be reviewed in class.

Classes need for project!!

Block

import java.util.ArrayList;

/**

* This holds the values for a Block in the Blockchain, and it has methods to compute the Merkle Root and generate a hash.

*/

public class Block {

private String sMerkleRoot;

private int iDifficulty = 5; // Mining seconds in testing 5: 6,10,15,17,20,32 | testing 6: 12,289,218

private String sNonce;

private String sMinerUsername;

private String sHash;

/**

* This computes the Merkle Root. It either accepts 2 or 4 items, or if made to be dynamic, then accepts any

* multiple of 2 (2,4,8.16.32,etc.) items.

* @param lstItems

* @return

*/

public synchronized String computeMerkleRoot(ArrayList lstItems) {

ADD CODE HERE ###

}

/**

* This method populates a Merkle node's left, right, and hash variables.

* @param oNode

* @param oLeftNode

* @param oRightNode

*/

private void populateMerkleNode(MerkleNode oNode, MerkleNode oLeftNode, MerkleNode oRightNode){

ADD CODE HERE ###

}

// Hash this block, and hash will also be next block's previous hash.

/**

* This generates the hash for this block by combining the properties and hashing them.

* @return

*/

public String computeHash() {

return new BlockchainUtil().generateHash(sMerkleRoot + iDifficulty + sMinerUsername + sNonce);

}

public int getDifficulty() {

return iDifficulty;

}

public String getNonce() {

return sNonce;

}

public void setNonce(String nonce) {

this.sNonce = nonce;

}

public void setMinerUsername(String sMinerUsername) {

this.sMinerUsername = sMinerUsername;

}

public String getHash() { return sHash; }

public void setHash(String h) {

this.sHash = h;

}

public synchronized void setMerkleRoot(String merkleRoot) { this.sMerkleRoot = merkleRoot; }

/**

* Run this to test your merkle tree logic.

* @param args

*/

public static void main(String[] args){

ArrayList lstItems = new ArrayList<>();

Block oBlock = new Block();

String sMerkleRoot;

// These merkle root hashes based on "t1","t2" for two items, and then "t3","t4" added for four items.

String sExpectedMerkleRoot_2Items = "3269f5f93615478d3d2b4a32023126ff1bf47ebc54c2c96651d2ac72e1c5e235";

String sExpectedMerkleRoot_4Items = "e08f7b0331197112ff8aa7acdb4ecab1cfb9497cbfb84fb6d54f1cfdb0579d69";

lstItems.add("t1");

lstItems.add("t2");

// *** BEGIN TEST 2 ITEMS ***

sMerkleRoot = oBlock.computeMerkleRoot(lstItems);

if(sMerkleRoot.equals(sExpectedMerkleRoot_2Items)){

System.out.println("Merkle root method for 2 items worked!");

}

else{

System.out.println("Merkle root method for 2 items failed!");

System.out.println("Expected: " + sExpectedMerkleRoot_2Items);

System.out.println("Received: " + sMerkleRoot);

}

// *** BEGIN TEST 4 ITEMS ***

lstItems.add("t3");

lstItems.add("t4");

sMerkleRoot = oBlock.computeMerkleRoot(lstItems);

if(sMerkleRoot.equals(sExpectedMerkleRoot_4Items)){

System.out.println("Merkle root method for 4 items worked!");

}

else{

System.out.println("Merkle root method for 4 items failed!");

System.out.println("Expected: " + sExpectedMerkleRoot_4Items);

System.out.println("Received: " + sMerkleRoot);

}

}

}

BlockChainBasics

/**

* This class manages the main thread, kicks off the Blockchain management classes, and controls the UI interaction.

*/

public class BlockchainBasics {

public static String sRemoteMinerIP = null;

public static int iRemoteMinerPort = 0;

/**

* This method manages the UI interaction and spawns off the Miner and P2PServer threads.

* @param args

*/

public static void main(String[] args){

BlockchainUtil u = new BlockchainUtil();

// Kick off miner.

String sUsername = u.promptUser("Username for this miner? ");

Miner oMiner = new Miner();

oMiner.sUsername = sUsername;

Thread oMinerThread = new Thread(oMiner);

oMinerThread.start();

// Sleep here so that miner thread can get up and running completely.

u.sleep(500);

// Start server after getting port from user.

String sPort = u.promptUser("What port do you want to start server on? ");

int iPort = Integer.parseInt(sPort);

P2PServer oServer = new P2PServer(iPort);

Thread oServerThread = new Thread(oServer);

oServerThread.start();

// Sleep here so that server thread can get up and running completely.

u.sleep(500);

String sSend = u.promptUser("Send transactions to another miner (y,n)? ");

if(sSend.equals("y")){

sRemoteMinerIP = u.promptUser("Miner's IP address? " );

String sTempPort = u.promptUser("Miner's Port? ");

iRemoteMinerPort = Integer.parseInt(sTempPort);

}

// Looping Menu: create & send TX OR create only.

while(true){

String sTransaction = u.promptUser("Enter Transaction: ");

if(sSend.equals("y")) {

String sReply = P2PUtil.connectForOneMessage(sRemoteMinerIP, iRemoteMinerPort, sTransaction);

u.p("[main] Reply from server: " + sReply);

}

Miner.lstTransactionPool.add(sTransaction);

}

}

}

BlockchainUtil

import java.nio.charset.StandardCharsets;

import java.security.MessageDigest;

import java.util.Scanner;

/**

* This class has utility methods used by the Blockchain logic.

*/

public class BlockchainUtil {

/**

* This method produces an SHA-256 hash of the string input.

* @param sOriginal

* @return

*/

public static synchronized String generateHash(String sOriginal){

ADD CODE HERE ###

}

/**

* This method can either use Scanner or JOptionPane approaches to get user input.

* @param sQuestion

* @return

*/

public String promptUser(String sQuestion){

// Using input dialog:

//return JOptionPane.showInputDialog(sQuestion);

// Using Scanner:

System.out.print(sQuestion);

Scanner oCommandInput = new Scanner(System.in);

return oCommandInput.nextLine();

}

/**

* This method allows user to avoid extra typing and efficient code, especially if this class variable is one letter

* such as u, thus:

* u.p("hello");

* @param sMessage

*/

public void p(String sMessage){

System.out.println(sMessage);

}

/**

* This is used by any thread that needs to sleep to allow updating of static variables or to alleviate

* CPU usage on continuous looping.

* @param lMillis

*/

public void sleep(long lMillis){

try{

Thread.sleep(lMillis);

}

catch(Exception ex){

// do nothing.

}

}

}

MerkleNode

/**

* This class simply holds a single Merkle Node's values.

*/

public class MerkleNode {

String sHash;

MerkleNode oLeft;

MerkleNode oRight;

}

MIner

import java.util.ArrayList;

/**

* This class runs on separate thread and manages the transaction queue and Block mining.

*/

public class Miner implements Runnable{

public static volatile P2PMessageQueue oIncomingMessageQueue = new P2PMessageQueue();

public static volatile boolean bAbortPoW = false;

public static volatile ArrayList lstTransactionPool = new ArrayList<>();

int iBlockTxSize = 4;

public String sUsername;

/**

* PoW is where miner keeps trying incrementing nonce until hash begins with as many 0s as the difficulty specifies.

* @param oBlock

* @return

*/

public boolean doProofOfWork(Block oBlock) {

ADD CODE HERE ### }

/**

* This thread monitors incoming messages, monitors the transaction queue, and mines Block if enough transactions collected.

* Called as part of Runnable interface and shouldn't be called directly by code.

*/

public void run() {

BlockchainUtil u = new BlockchainUtil();

u.p("Miner thread started.");

// *****************************

// *** Eternal Mining Loop *****

// Because miner always checking for next block to immediately work on.

while(true){

u.sleep(500);

while(oIncomingMessageQueue.hasNodes()){

P2PMessage oMessage = oIncomingMessageQueue.dequeue();

lstTransactionPool.add(oMessage.getMessage());

}

// Check if transaction pool full and lock if it is.

if (lstTransactionPool.size() >= iBlockTxSize) {

Block oBlock = new Block();

oBlock.setMinerUsername(sUsername);

oBlock.computeHash();

String sMerkleRoot = oBlock.computeMerkleRoot(lstTransactionPool);

oBlock.setMerkleRoot(sMerkleRoot);

boolean bMined = doProofOfWork(oBlock);

if(bMined){

// Notify connected node.

if(BlockchainBasics.sRemoteMinerIP != null){

P2PUtil.connectForOneMessage(BlockchainBasics.sRemoteMinerIP, BlockchainBasics.iRemoteMinerPort,

"mined");

}

u.p("");

u.p("***********");

u.p("BLOCK MINED");

u.p("nonce: " + oBlock.getNonce());

u.p("hash: " + oBlock.getHash());

u.p("");

u.p("Transactions:");

for(int x=0; x < lstTransactionPool.size(); x++){

u.p("Tx " + x + ": " + lstTransactionPool.get(x));

}

u.p("***********");

}

else{

u.p("[miner] Mining block failed.");

}

// Clear tx pool.

lstTransactionPool.clear();

}

}

}

}

P2PMessage

/**

* This class holds incoming messages to this node.

*/

public class P2PMessage {

private String sMessage;

// Used for queue.

public P2PMessage next = null;

public void setMessage(String sMessage){

this.sMessage = sMessage;

}

public String getMessage(){

return sMessage;

}

}

P2PMessageQueuw

/**

* This Queue maintains the queue of messages coming from connected clients.

*/

public class P2PMessageQueue {

private P2PMessage head = null;

private P2PMessage tail = null;

/**

* This method allows adding a message object to the existing queue.

* @param oMessage

*/

public synchronized void enqueue(P2PMessage oMessage){

ADD CODE HERE ### }

/**

* This method allows removing a message object from the existing queue.

* @return

*/

public synchronized P2PMessage dequeue(){

ADD CODE HERE ###

}

public boolean hasNodes(){

ADD CODE HERE ###

}

}

P2PServer

import java.io.*;

import java.net.ServerSocket;

import java.net.Socket;

/**

* This class is a separate thread that listens for messages from connecting clients and adds messages to queue.

*/

public class P2PServer implements Runnable {

private int thisServerPort;

/**

* This constructor forces port to be passed in that is necessary for startup of ServerSocket.

* @param iPort

*/

public P2PServer(int iPort){

thisServerPort = iPort;

}

/**

* This thread listens for connecting clients and receives messages to add to Blockchain's transaction queue.

*/

public void run() {

BlockchainUtil u = new BlockchainUtil();

try (ServerSocket oServerSocket = new ServerSocket(thisServerPort)) {

System.out.println("Server is listening on port " + thisServerPort);

while(true) {

Socket oSocket = oServerSocket.accept();

u.p("[server]: New client connected: " + oSocket.getRemoteSocketAddress());

InputStream input = oSocket.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(input));

OutputStream output = oSocket.getOutputStream();

PrintWriter writer = new PrintWriter(output, true);

// Get one time message from client.

String sReceivedMessage = reader.readLine();

u.p("[server]: Server received message: " + sReceivedMessage);

if (sReceivedMessage.startsWith("mined")) {

u.p("[server]: Block has been mined by other node.");

Miner.bAbortPoW = true;

writer.println("Server received: " + sReceivedMessage);

writer.flush();

}

else {

P2PMessage oMessage = new P2PMessage();

oMessage.setMessage(sReceivedMessage);

Miner.oIncomingMessageQueue.enqueue(oMessage);

writer.println("Server queued: " + sReceivedMessage);

writer.flush();

}

}

}

catch (IOException ex) {

u.p("[server]: Server exception: " + ex.getMessage());

ex.printStackTrace();

}

}

}

P2PUtil

import java.io.*;

import java.net.InetSocketAddress;

import java.net.Socket;

/**

* This class holds any utility methods needed for P2P networking communication.

*/

public class P2PUtil {

/**

* Allows a one time socket call to a server, gets reply, and then closes connection.

* @param sIP

* @param iPort

* @param sMessage

* @return

*/

public static String connectForOneMessage(String sIP, int iPort, String sMessage

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Advances In Databases 28th British National Conference On Databases Bncod 28 Manchester Uk July 2011 Revised Selected Papers Lncs 7051

Authors: Alvaro A.A. Fernandes ,Alasdair J.G. Gray ,Khalid Belhajjame

2011th Edition

3642245765, 978-3642245763

More Books

Students also viewed these Databases questions

Question

How do books become world of wonder?

Answered: 1 week ago