const express = require('express')
const app = express()
const bodyParser = require('body-parser');
const Blockchain = require("./Blockchain");
const {v4: uuidv4} = require('uuid');
const bitcoin = new Blockchain();
const port = process.argv[2];
const nodeAddress = uuidv4().split("-").join('');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
// respond with "hello world" when a GET request is made to the homepage
app.get('/blockchain', (req, res) => {
res.send(bitcoin)
})
// app.post('/transaction', (req, res) => {
// const blockIndex = bitcoin.createNewTransaction(req.body.amount, req.body.sender, req.body.recipient);
// res.json({note: `this transaction will be added in block ${blockIndex}`})
// })
app.get('/mine', (req, res) => {
const lastBlock = bitcoin.getLastBlock();
const prevBlockHash = lastBlock['hash'];
const currentBlockData = {
transaction : bitcoin.pendingTransactions,
index : lastBlock['index'] + 1
}
const nonce = bitcoin.proofOfWork(prevBlockHash, currentBlockData);
const blockHash = bitcoin.hashBlock(prevBlockHash, currentBlockData, nonce);
const newBlock = bitcoin.createNewBlock(nonce, prevBlockHash, blockHash);
bitcoin.createNewTransaction(100, '0', nodeAddress);
res.json({
note : "New block mined Successfully",
block : newBlock
})
})
app.get('/wallet', (req, res) => {
res.sendFile(__dirname + "/index.html");
})
app.post('/wallet', (req, res) => {
const blockIndex = bitcoin.createNewTransaction(req.body.amount, req.body.senderAddress, req.body.recipientAddress);
res.json({note: `this transaction will be added in block ${blockIndex}`})
})
app.listen(port, function(){
console.log(`Server is Running on ${port}`);
});