-
Notifications
You must be signed in to change notification settings - Fork 0
/
Transaction.js
34 lines (29 loc) · 1.07 KB
/
Transaction.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
const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
const {
MINT_PUBLIC_ADDRESS,
createSHA256Hash
} = require('./helpers');
class Transaction {
constructor(from, to, amount, gas = 0) {
this.from = from;
this.to = to;
this.amount = amount;
this.gas = gas;
}
sign(keyPair) {
if (keyPair.getPublic('hex') === this.from) {
this.signature = keyPair.sign(createSHA256Hash(this.from + this.to + this.amount + this.gas), 'base64').toDER('hex');
}
}
isValid(transaction, chain) {
return (
transaction.from &&
transaction.to &&
transaction.amount &&
(chain.getBalance(transaction.from) >= transaction.amount + transaction.gas || transaction.from === MINT_PUBLIC_ADDRESS && transaction.amount === chain.reward) &&
ec.keyFromPublic(transaction.from, 'hex').verify(createSHA256Hash(transaction.from + transaction.to + transaction.amount + transaction.gas), transaction.signature)
);
}
}
module.exports = Transaction;