Skip to content

Commit 7326135

Browse files
Add files via upload
1 parent 41d16d6 commit 7326135

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

Block chain using Java/Block.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import java.util.Date;
2+
3+
public class Block {
4+
5+
public String hash;
6+
public String previousHash;
7+
private String data; //our data will be a simple message.
8+
private long timeStamp; //as number of milliseconds since 1/1/1970.
9+
private int nonce;
10+
11+
//Block Constructor.
12+
public Block(String data,String previousHash ) {
13+
this.data = data;
14+
this.previousHash = previousHash;
15+
this.timeStamp = new Date().getTime();
16+
17+
this.hash = calculateHash(); //Making sure we do this after we set the other values.
18+
}
19+
20+
//Calculate new hash based on blocks contents
21+
public String calculateHash() {
22+
String calculatedhash = StringUtil.applySha256(
23+
previousHash +
24+
Long.toString(timeStamp) +
25+
Integer.toString(nonce) +
26+
data
27+
);
28+
return calculatedhash;
29+
}
30+
31+
public void mineBlock(int difficulty) {
32+
String target = new String(new char[difficulty]).replace('\0', '0'); //Create a string with difficulty * "0"
33+
while(!hash.substring( 0, difficulty).equals(target)) {
34+
nonce ++;
35+
hash = calculateHash();
36+
}
37+
System.out.println("Block Mined!!! : " + hash);
38+
}
39+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import java.security.MessageDigest;
2+
3+
public class StringUtil {
4+
//Applies Sha256 to a string and returns the result.
5+
public static String applySha256(String input){
6+
try {
7+
MessageDigest digest = MessageDigest.getInstance("SHA-256");
8+
//Applies sha256 to our input,
9+
byte[] hash = digest.digest(input.getBytes("UTF-8"));
10+
StringBuffer hexString = new StringBuffer(); // This will contain hash as hexidecimal
11+
for (int i = 0; i < hash.length; i++) {
12+
String hex = Integer.toHexString(0xff & hash[i]);
13+
if(hex.length() == 1) hexString.append('0');
14+
hexString.append(hex);
15+
}
16+
return hexString.toString();
17+
}
18+
catch(Exception e) {
19+
throw new RuntimeException(e);
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)