-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (49 loc) · 1.62 KB
/
index.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
55
56
const {startMining, stopMining} = require('./mine');
const {PORT, PUBLIC_KEY} = require('./config');
const {utxos, blockchain} = require('./db');
const express = require('express');
const app = express();
const cors = require('cors');
const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
app.use(cors());
app.use(express.json());
////////////// SERVER /////////////////
app.post('/', (req, res) => {
const {method, params} = req.body;
/////// Handle Verification //////
if(method === 'verifyAddress') {
const [PUB, MESSAGE, SIG] = params;
const pubKey = ec.keyFromPublic(PUB, 'hex');
const isValid = pubKey.verify(MESSAGE, SIG);
if (PUB === PUBLIC_KEY && isValid === true) {
//set isvalid variable
app.locals.isValid = true;
res.send({isValid: isValid, addressInput: PUB});
}
return;
}
if(method === 'startMining' && app.locals.isValid) {
console.log("Start Mining Authentication:", app.locals.isValid);
startMining();
res.send({ blockNumber: blockchain.blockHeight() });
return;
}
if(method === 'stopMining' && app.locals.isValid) {
console.log("Stop Mining Authentication:", app.locals.isValid);
stopMining();
res.send({ blockNumber: blockchain.blockHeight() });
return;
}
if(method === "getBalance") {
const [address] = params;
const ourUTXOs = utxos.filter(x => {
return x.owner === address && !x.spent;
});
const sum = ourUTXOs.reduce((p,c) => p + c.amount, 0);
res.send({ balance: sum.toString()});
}
});
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}!`);
});