-
Notifications
You must be signed in to change notification settings - Fork 0
/
Transaction.js
36 lines (33 loc) · 938 Bytes
/
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
35
36
const { Wallet } = require("./Wallet");
const Transaction = (exports.Transaction = class Transaction {
constructor(opts = {}) {
Object.assign(
this,
{
from: null,
to: null,
value: 0,
nonce: 0,
signature: null,
},
opts
);
}
hash() {
const head = JSON.stringify(this, ["from", "to", "value", "nonce"]);
return createHash("SHA256").update(head).digest("hex");
}
sign(privateKey) {
const cert = Wallet.getNodePrivateKey(this.from, privateKey);
const signature = createSign("SHA256")
.update(this.hash())
.sign(cert, "hex");
return new Transaction({ ...this, signature });
}
test() {
const cert = Wallet.getNodePublicKey(this.from);
const signature = createVerify("SHA256").update(this.hash());
if (!this.from || !this.signature) return false;
return signature.verify(cert, this.signature, "hex");
}
});