-
Notifications
You must be signed in to change notification settings - Fork 0
/
TransactionOutput.java
51 lines (40 loc) · 1.39 KB
/
TransactionOutput.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
import java.security.*;
import java.util.*;
import java.nio.*;
import java.nio.charset.StandardCharsets;
public class TransactionOutput {
public String id;
public PublicKey reciepient; //also known as the new owner of these coins.
public float value; //the amount of coins they own
public String parentTransactionId; //the id of the transaction this output was created in
//Constructor
public TransactionOutput(PublicKey reciepient, float value, String parentTransactionId) {
this.reciepient = reciepient;
this.value = value;
this.parentTransactionId = parentTransactionId;
this.id = calculateHash();
}
private String calculateHash() {
String dataToHash = getStringFromKey(reciepient) + Float.toString(value) + parentTransactionId;
MessageDigest digest = null;
byte[] bytes = null;
try{
digest = MessageDigest.getInstance("SHA-256");
bytes = digest.digest(dataToHash.getBytes(StandardCharsets.UTF_8));
} catch(NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
StringBuffer buffer = new StringBuffer();
for (byte b : bytes) {
buffer.append(String.format("%02x", b));
}
return buffer.toString();
}
//Check if coin belongs to you
public boolean isMine(PublicKey publicKey) {
return (publicKey == reciepient);
}
public static String getStringFromKey(Key key) {
return Base64.getEncoder().encodeToString(key.getEncoded());
}
}