-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
89 lines (76 loc) · 2.75 KB
/
index.js
File metadata and controls
89 lines (76 loc) · 2.75 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var BlockChain = new (require(`./BlockChain`))();
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const uuid = require('uuid/v4');
const node_address = uuid().replace(/[\-]/g,'');
var MINE_REWARD = 10;
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('/',(req,res)=>{
res.send({ address: node_address, nodes: BlockChain.nodes});
});
app.get('/blockchain',(req,res)=>{
res.send({
length: BlockChain.chain.length,
chain: BlockChain.chain
});
});
app.get('/status',(req,res)=>{
res.send("The system is under development.");
});
app.get('/mine',(req,res)=>{
var prev_block = BlockChain.get_previous_block();
var prev_proof = prev_block.proof;
var proof = BlockChain.proof_of_work(prev_proof);
var prev_hash = BlockChain.hash(prev_block);
BlockChain.addTransaction(node_address,node_address,MINE_REWARD);
var block = BlockChain.create_block(proof,prev_hash);
res.send({
message: `Congrats, Block ${block.index} is successfully mined !`,
block : block
});
});
app.get('/isValid',(req,res)=>{
res.send(BlockChain.isChainValid()?"Yes, blockchain is in valid state":"No, blockchain is not in valid state.")
});
app.post('/addTransaction',(req,res)=>{
var postData = req.body;
var block_index = -1;
if(postData.sender&&postData.receiver&&postData.amount){
block_index = BlockChain.addTransaction(postData.sender,postData.receiver,postData.amount);
res.send({status: `Transaction will be added to block ${block_index}`});
}
else res.send({status: "Corrupted Transaction Submitted. Error" },201);
});
// Create New Nodes For Decentralized Blockchain
app.post('/connectNode',(req,res)=>{
var postData = req.body;
var nodes = postData.nodes;
if(nodes){
nodes.forEach(node => {
BlockChain.add_node(node);
});
res.send({status: `Nodes Added Successfully`});
}else res.send({status: "Connection Aborted. Error" },201);
});
app.get('/replaceChain',(req,res)=>{
BlockChain.replace_chain().then((isChainReplaced)=>{
if(isChainReplaced){
res.send({
status: `The blockchain is replaced by the longest chain.`,
chain: BlockChain.chain
});
}else{
res.send({
status : `Block chain is not required to be replaced.`,
chain: BlockChain.chain
});
}
});
});
console.log(`My address is ${node_address}`);
PORT = 3000;
app.listen(process.env.PORT || PORT, () => console.log(`Blockchain app listening on port ${PORT}!`));