forked from cenetex/tinychain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
64 lines (56 loc) · 1.97 KB
/
server.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
57
58
59
60
61
62
63
64
const express = require('express');
const bodyParser = require('body-parser');
const blockchain = require('.');
const app = express(),
PORT = 3030;
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', express.static('static'));
blockchain.create(chain => {
app.get('/chains/test', (request, response) => {
response.send(JSON.stringify(chain, null, 4));
});
app.put("/chain/mine", (request, response) => {
let data = request.body;
let counter = 0;
let blocks = chain.mine(data.address);
while (counter < 10000 && blocks === null) {
blocks = chain.mine(data.address);
counter++;
}
if (blocks !== null) {
chain.blocks = blocks;
chain.save();
response.send("Successfully mined a block and saved the chainfile!");
return;
}
throw new Error("Failed to mine a block after 1000 attempts!");
});
app.get("/chain/download", (request, response) => {
response.send(chain);
});
app.get("/chain.json", (request, response) => {
response.send(chain);
});
app.get('/wallet/new', (request, response) => {
response.send(blockchain.wallet.create());
});
app.post('/wallet/sign', (request, response) => {
let data = request.body;
let wallet = blockchain.wallet.load(data.source, data.key);
response.send(JSON.stringify(wallet.transaction(data.destination, data.amount)));
});
app.post('/transaction', (request, response) => {
let data = request.body;
chain.addTransaction(forge.util.encode64(JSON.stringify({
source: data.source,
destination: data.destination,
signature: data.signature
})));
response.send(chain);
});
app.listen(PORT, () => {
console.log(`listening on port ${PORT}`);
});
});