Last active
March 27, 2019 19:23
-
-
Save lobster1234/b8619152a8bc29bede97ccde501d5a59 to your computer and use it in GitHub Desktop.
A miner for demo during talks/presentations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.lobster1234; | |
import org.apache.commons.codec.digest.DigestUtils; | |
public class Miner { | |
public static void main(String[] args){ | |
Block block = new Block("185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969" | |
,"be98c2510e417405647facb89399582fc499c3de4452b3014857f92e6baad9a9" | |
,1.45f, | |
System.currentTimeMillis()); | |
Miner miner = new Miner(); | |
long nonce = miner.getNonce(block,6); | |
System.out.println("Nonce is " + nonce); | |
} | |
private long getNonce(Block block, int difficulty){ | |
String data = block.getTo() + block.getFrom() + block.getAmount() + block.getTimestamp(); | |
StringBuilder target = new StringBuilder(); | |
for(int i=0;i<difficulty;i++){ | |
target.append("0"); | |
} | |
System.out.println("Target is " + target + " and initial data is " + data); | |
long nonce = 0; | |
long start = System.currentTimeMillis(); | |
while(true){ | |
String newHashHex = DigestUtils.sha256Hex(data+nonce); | |
if(newHashHex.startsWith(target.toString())) | |
break; | |
else ++nonce; | |
} | |
System.out.println("For difficultly level " + difficulty + ", it took " + (System.currentTimeMillis()-start) + " milliseconds."); | |
return nonce; | |
} | |
} | |
/** | |
For now lets just assume 1 block = 1 transaction. In the real world a block = bunch of transactions | |
*/ | |
class Block{ | |
private String to; | |
private String from; | |
private float amount; | |
private long timestamp; | |
public Block(String to, String from, float amount, long timestamp) { | |
this.to = to; | |
this.from = from; | |
this.amount = amount; | |
this.timestamp = timestamp; | |
} | |
public String getTo() { | |
return to; | |
} | |
public String getFrom() { | |
return from; | |
} | |
public float getAmount() { | |
return amount; | |
} | |
public long getTimestamp() { | |
return timestamp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment