-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWallet.js
54 lines (43 loc) · 1.33 KB
/
Wallet.js
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
const { generatePair } = require('./crypto');
const { Transaction } = require('./Transaction');
class Wallet {
constructor(blockchain, name) {
const { publicKey, privateKey } = generatePair();
this.publicKey = publicKey;
this.privateKey = privateKey;
this.blockchain = blockchain;
this.name = name;
}
getUTXOPool() {
return this.blockchain.getUnspentTransactionOutputsFromAddress(this.publicKey);
}
hasSufficientBalance(amountToPay) {
return (this.getUTXOPool().amount >= amountToPay);
}
getBalance() {
return this.blockchain.getBalanceOfAddress(this.publicKey);
}
_addFunds(amount) {
console.log(`Adding money to ${this.name} for testing purposes (THIS DOESN'T HAPPEN IN REAL LIFE)`);
let latestBlock = this.blockchain.getMaximumHeightBlock();
latestBlock.utxoPool.addUTXO(this.publicKey, amount);
}
getAddress() {
return this.publicKey;
}
getPrivateKey() {
return this.privateKey;
}
transferTo(recipientAddress, amount) {
if (!this.hasSufficientBalance(amount)) {
console.log(`[Wallet ${this.name}: insufficient funds`);
return;
}
const transaction = new Transaction(this.publicKey, recipientAddress, amount);
transaction.sign(this.privateKey);
this.blockchain.addTransactionToThePool(transaction);
}
}
module.exports = {
Wallet
};