-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWallet.java
85 lines (71 loc) · 2.85 KB
/
Wallet.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
74
75
76
77
78
79
80
81
82
83
84
85
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Wallet
{
public PrivateKey privateKey;//Private key is used to sign the transactions.Users will have to keep their private key secret.
public PublicKey publicKey;//The public key will act as a address.We can share public key with others to receive payment.
public HashMap<String,TransactionOutput> UTXOs = new HashMap<String,TransactionOutput>();
public Wallet()
{
generateKeyPair();
}
public void generateKeyPair()
{
//We will generate our private and public keys in a KeyPair.We will use Elliptic curve Cryptography to generate our key pairs using Java.security.KeyPairGenerator.
try
{
KeyPairGenerator keygen = KeyPairGenerator.getInstance("ECDSA","BC");// Elliptic Curve Digital Signature Algorithm
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
ECGenParameterSpec ecSpec = new ECGenParameterSpec("prime192v1");
keygen.initialize(ecSpec,random);
KeyPair keyPair = keygen.generateKeyPair();
privateKey = keyPair.getPrivate();
publicKey = keyPair.getPublic();
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
public float getBalance()
{
//Wallet balance is the sum of all the unspent transaction outputs addressed to you.
float total = 0;
for (Map.Entry<String, TransactionOutput> item: noobchain.UTXOs.entrySet())
{
TransactionOutput UTXO = item.getValue();
if(UTXO.isMine(publicKey))//if output belongs to me then those coins belongs to me
{
UTXOs.put(UTXO.id,UTXO);//add it to the list of unspent transactions
total += UTXO.value ;
}
}
return total;
}
public Transaction sendFunds(PublicKey _recipient,float value )
{
if(getBalance() < value)
{
System.out.println("#Not Enough funds to send transaction. Transaction Discarded.");
return null;
}
ArrayList<TransactionInput> inputs = new ArrayList<TransactionInput>();
float total = 0;
for (Map.Entry<String, TransactionOutput> item: UTXOs.entrySet())
{
TransactionOutput UTXO = item.getValue();
total += UTXO.value;
inputs.add(new TransactionInput(UTXO.id));
if(total > value) break;
}
Transaction newTransaction = new Transaction(publicKey, _recipient , value, inputs);
newTransaction.generateSignature(privateKey);
for(TransactionInput input: inputs){
UTXOs.remove(input.transactionOutputId);
}
return newTransaction;
}
}