-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlock.java
More file actions
71 lines (64 loc) · 1.81 KB
/
Block.java
File metadata and controls
71 lines (64 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
//a block stores its own hash, previous nodes hash,
//timestamp of creation, data, and a arbitary number used for cryptoraphy
public class Block
{
private static Logger logger = Logger.getLogger(Block.class.getName());
private String hash;
private String previoushash;
private String data;
private long timestamp;
private int nonce;
public Block(String data, String previoushash, long timestamp)
{
this.data = data;
this.previoushash = previoushash;
this.timestamp = timestamp;
this.hash = calculateBlockHash();
}
public String mineBlock(int prefix)
{
String prefixString = new String(new char[prefix]).replace('\0', '0');
while (!hash.substring(0, prefix)
.equals(prefixString)) {
nonce++;
hash = calculateBlockHash();
}
return hash;
}
public String calculateBlockHash()
{
String dataToHash = previoushash
+ Long.toString(timestamp)
+ Integer.toString(nonce)
+ data;
MessageDigest digest = null;
byte[] bytes = null;
try{
digest = MessageDigest.getInstance("SHA-256");
bytes = digest.digest(dataToHash.getBytes("UTF_8"));
}
catch(NoSuchAlgorithmException | UnsupportedEncodingException ex)
{
logger.log(Level.SEVERE, ex.getMessage());
}
StringBuffer buffer = new StringBuffer();
for (byte b : bytes)
{
buffer.append(String.format("%02x",b));
}
return buffer.toString();
}
}
/*
public class Main
{
public static void main(String[] args) {
System.out.println("hello world");
}
}
*/