-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWallet.java
More file actions
68 lines (61 loc) · 2.35 KB
/
Wallet.java
File metadata and controls
68 lines (61 loc) · 2.35 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
// The following code is from
// https://gist.github.com/CryptoKass/6f540a2cd67ebad81a057ea3a50e7f09#file-wallet-java
// This class stores the public and private key pair that will be used for transactions
import java.security.*;
import java.security.spec.*;
import java.util.*;
public class Wallet {
public PrivateKey privateKey;
public PublicKey publicKey;
public Map<String, TransactionOutput> UTXOs;
public Wallet()
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException {
generateKeyPair();
UTXOs = new HashMap<String, TransactionOutput>();
}
// Generating the keypairs using Elliptical curve Cryptography
public void generateKeyPair()
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", "BC");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
ECGenParameterSpec ecsp = new ECGenParameterSpec("prime192v1");
keyGen.initialize(ecsp, random);
KeyPair keyPair = keyGen.generateKeyPair();
privateKey = keyPair.getPrivate();
publicKey = keyPair.getPublic();
}
// Returns balance of the wallet by adding up all unspent transactions
public float getBalance() {
float total = 0;
for (String item : BlockChain.UTXOs.keySet()) {
TransactionOutput UTXO = BlockChain.UTXOs.get(item);
if (UTXO.isMine(publicKey)) {
UTXOs.put(UTXO.id, UTXO);
total += UTXO.value;
}
}
return total;
}
public Transaction sendFunds(PublicKey recieverKey, float value) {
if (getBalance() < value) {
System.out.println("Not enough funds. You have :" + getBalance());
return null;
}
ArrayList<TransactionInput> inputs = new ArrayList<TransactionInput>();
float total = 0;
for (String item : UTXOs.keySet()) {
TransactionOutput UTXO = UTXOs.get(item);
total += UTXO.value;
inputs.add(new TransactionInput(UTXO.id));
if (total > value) {
break;
}
}
Transaction newTransaction = new Transaction(publicKey, recieverKey, value, inputs);
newTransaction.generateSignature(privateKey);
for (TransactionInput input : inputs) {
UTXOs.remove(input.transactionOutputId);
}
return newTransaction;
}
}