diff --git a/server/api.js b/server/api.js index 6f90ff8..4e1af42 100644 --- a/server/api.js +++ b/server/api.js @@ -1,6 +1,9 @@ const express = require("express"); const bodyParser = require("body-parser"); const Wallet = require("./wallet"); +const Transaction = require("./transaction") +const Blockchain = require("./blockchain"); +const Block = require("./block"); //get the port from the user or set the default port const HTTP_PORT = process.env.HTTP_PORT || 3001; @@ -29,3 +32,23 @@ app.post("/mine", (req, res) => { app.listen(HTTP_PORT, () => { console.log(`listening on port ${HTTP_PORT}`); }); + +app.post("/transact", (req, res) =>{ + try{ + const wallet=new Wallet(req.body.senderPrivateKey); + const trans=new Transaction(); + trans.newTransaction(wallet, req.body.recipientPublicKey, req.body.amount); + const bc=Blockchain(Block.genesis()); + bc.addBlock(trans); + + res.json({ + "status": 200, + }); + } + catch(err) { + res.json({ + "status": 400, + "error": err.message, + }); + } +}); diff --git a/server/blockchain.js b/server/blockchain.js index 3d4c7bb..f724982 100644 --- a/server/blockchain.js +++ b/server/blockchain.js @@ -1,8 +1,9 @@ const Block = require("./block.js"); +const mysql = require('mysql'); class Blockchain { - constructor() { - this.chain = [Block.genesis()]; + constructor(chain) { + this.chain = chain; } addBlock(data) { @@ -12,6 +13,11 @@ class Blockchain { return block; } + /** + * Given a chain, return true if it is valid + * @param {array} chain + * @returns {boolean} + */ isValidChain(chain) { if (JSON.stringify(chain[0]) !== JSON.stringify(Block.genesis())) return false; @@ -22,7 +28,7 @@ class Blockchain { if ( block.lastHash !== lastBlock.hash || block.hash !== Block.blockHash(block) - ) + ) return false; }