-
Notifications
You must be signed in to change notification settings - Fork 12
/
Block.java
executable file
·73 lines (60 loc) · 1.93 KB
/
Block.java
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
72
73
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.ArrayList;
public class Block {
public static final double COINBASE = 25;
private byte[] hash;
private byte[] prevBlockHash;
private Transaction coinbase;
private ArrayList<Transaction> txs;
/** {@code address} is the address to which the coinbase transaction would go */
public Block(byte[] prevHash, PublicKey address) {
prevBlockHash = prevHash;
coinbase = new Transaction(COINBASE, address);
txs = new ArrayList<Transaction>();
}
public Transaction getCoinbase() {
return coinbase;
}
public byte[] getHash() {
return hash;
}
public byte[] getPrevBlockHash() {
return prevBlockHash;
}
public ArrayList<Transaction> getTransactions() {
return txs;
}
public Transaction getTransaction(int index) {
return txs.get(index);
}
public void addTransaction(Transaction tx) {
txs.add(tx);
}
public byte[] getRawBlock() {
ArrayList<Byte> rawBlock = new ArrayList<Byte>();
if (prevBlockHash != null)
for (int i = 0; i < prevBlockHash.length; i++)
rawBlock.add(prevBlockHash[i]);
for (int i = 0; i < txs.size(); i++) {
byte[] rawTx = txs.get(i).getRawTx();
for (int j = 0; j < rawTx.length; j++) {
rawBlock.add(rawTx[j]);
}
}
byte[] raw = new byte[rawBlock.size()];
for (int i = 0; i < raw.length; i++)
raw[i] = rawBlock.get(i);
return raw;
}
public void finalize() {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(getRawBlock());
hash = md.digest();
} catch (NoSuchAlgorithmException x) {
x.printStackTrace(System.err);
}
}
}