From 8f58f210d47022e66464958b78ae62d45e4f9363 Mon Sep 17 00:00:00 2001 From: devperate Date: Sat, 3 Jun 2023 12:15:28 -0400 Subject: [PATCH 1/2] refactoring the index.js file into components file architecture --- index copy.js | 187 ++++++++++++++++++++++++++++++++++++ index.js | 193 +++----------------------------------- src/helper.js | 40 ++++++++ src/kth.js | 47 ++++++++++ src/router.js | 42 +++++++++ src/routes/block.js | 43 +++++++++ src/routes/header.js | 40 ++++++++ src/routes/transaction.js | 15 +++ 8 files changed, 428 insertions(+), 179 deletions(-) create mode 100644 index copy.js create mode 100644 src/helper.js create mode 100644 src/kth.js create mode 100644 src/router.js create mode 100644 src/routes/block.js create mode 100644 src/routes/header.js create mode 100644 src/routes/transaction.js diff --git a/index copy.js b/index copy.js new file mode 100644 index 0000000..66aa6cf --- /dev/null +++ b/index copy.js @@ -0,0 +1,187 @@ +require('dotenv').config(); +const express = require('express'); +const cache = require('memory-cache'); +const kth = require("@knuth/bch"); + +const app = express(); + +const cacheSeconds = process.env.CACHE_SECONDS; +const port = process.env.PORT; +const nodeStdOut = process.env.NODE_STDOUT === 'true'; + +let running_ = false; + +function getNetworkFromEnv() { + if (process.env.NETWORK === 'chipnet') { + return kth.network.chipnet; + } else if (process.env.NETWORK === 'mainnet') { + return kth.network.mainnet; + } else if (process.env.NETWORK === 'testnet') { + return kth.network.testnet; + } else if (process.env.NETWORK === 'testnet4') { + return kth.network.testnet4; + } else if (process.env.NETWORK === 'scalenet') { + return kth.network.scalenet; + } + return kth.network.mainnet; +} + +function sleep(ms) { + return new Promise((r) => setTimeout(r, ms)); +} + +const config = kth.settings.getDefault(getNetworkFromEnv()); +// console.log(`Config: ${JSON.stringify(config)}`); +const node = new kth.node.Node(config, nodeStdOut); +let chain = undefined; + +const cacheMiddleware = (seconds) => { + return (req, res, next) => { + let key = '__express__' + req.originalUrl || req.url; + let cacheContent = cache.get(key); + if (cacheContent) { + res.send(cacheContent); + return; + } else { + res.sendResponse = res.send; + res.send = (body) => { + cache.put(key, body, seconds * 1000); + res.sendResponse(body); + } + next(); + } + } +} + +//TODO(fernando): add version route (version of this library) +//TODO(fernando): add network route +//TODO(fernando): add health route +//TODO(fernando): add status route +//TODO(fernando): js-api version, js-native version, c-api version, c++ api version +//TODO(fernando): chain state route + +app.get('/lastHeight', cacheMiddleware(cacheSeconds), async (req, res) => { + const [e, h] = await node.chain.getLastHeight(); + + if (e === kth.errors.success) { + res.json({height: h}); + } else { + //TODO(fernando): replace 500 with a more specific error code + //TODO(fernando): get the error message from the error code + res.status(500).json({ error: 'An error occurred', errorCode: e }); + } +}); + +app.get('/header/:id', cacheMiddleware(cacheSeconds), async (req, res) => { + const {id} = req.params; + let result; + if (isNaN(id) && id.length === 64) { + // console.log(`Getting block header by hash: ${id}`) + result = await node.chain.getBlockHeaderByHash(kth.enc.Hash.strToBytes(id)); + } else if (!isNaN(id)) { + result = await node.chain.getBlockHeaderByHeight(parseInt(id)); + } else { + res.status(400).json({ error: 'Invalid ID. It should be a block height (a number) or a block hash (a 64 character string).' }); + return; + } + const [e, headerObj, height] = result; + if (e === kth.errors.success) { + const hash = kth.enc.Hash.bytesToStr(kth.header.hash(headerObj)); + const header = { + version: headerObj.version, + previousBlockHash: kth.enc.Hash.bytesToStr(headerObj.previousBlockHash), + merkle: kth.enc.Hash.bytesToStr(headerObj.merkle), + timestamp: headerObj.timestamp, + bits: headerObj.bits, + nonce: headerObj.nonce, + } + res.json({header, height, hash}); + } else { + res.status(500).json({ error: 'An error occurred', errorCode: e }); + } +}); + +app.get('/block/:id', cacheMiddleware(cacheSeconds), async (req, res) => { + const {id} = req.params; + let result; + if (isNaN(id) && id.length === 64) { + // console.log(`Getting block header by hash: ${id}`) + result = await node.chain.getBlockByHash(kth.enc.Hash.strToBytes(id)); + } else if (!isNaN(id)) { + result = await node.chain.getBlockByHeight(parseInt(id)); + } else { + res.status(400).json({ error: 'Invalid ID. It should be a block height (a number) or a block hash (a 64 character string).' }); + return; + } + const [e, blockObj, height] = result; + if (e === kth.errors.success) { + const hash = kth.enc.Hash.bytesToStr(kth.header.hash(blockObj.header)); + const block = { + header: { + version: blockObj.header.version, + previousBlockHash: kth.enc.Hash.bytesToStr(blockObj.header.previousBlockHash), + merkle: kth.enc.Hash.bytesToStr(blockObj.header.merkle), + timestamp: blockObj.header.timestamp, + bits: blockObj.header.bits, + nonce: blockObj.header.nonce, + }, + transactions: blockObj.transactions, + } + res.json({block, height, hash}); + } else { + res.status(500).json({ error: 'An error occurred', errorCode: e }); + } +}); + +app.get('/transaction/:hash', cacheMiddleware(cacheSeconds), async (req, res) => { + const result = await node.chain.getTransaction(req.params.hash); + res.json(result); +}); + +app.get('/transactionPosition/:hash', cacheMiddleware(cacheSeconds), async (req, res) => { + const result = await node.chain.getTransactionPosition(req.params.hash); + res.json(result); +}); + +//TODO(fernando): organizarBlock (POST) +//TODO(fernando): organizarTransaction (POST) + +const server = app.listen(port, () => console.log(`Server listening on port ${port}!`)); + +async function main() { + process.on('SIGINT', shutdown); + await node.launch(kth.startModules.all); + console.log("Knuth node has been launched."); + running_ = true; + + // const [_, height] = await node.chain.getLastHeight(); + // lastBlockHeight = height; + + while (running_) { + // console.log("sleeping...") + await sleep(1000); + } + + console.log("Shutting down Knuth node..."); + node.close(); + console.log("Shutting down Web server..."); + + server.close(() => { + console.log("Good bye!"); + process.exit(); + }); +} + +function shutdown() { + console.log(''); + console.log('Ctrl+C detected.'); + running_ = false; +} + +(async () => { + try { + await main(); + } catch (e) { + console.log(e); + } +})(); diff --git a/index.js b/index.js index 66aa6cf..f81e971 100644 --- a/index.js +++ b/index.js @@ -1,187 +1,22 @@ -require('dotenv').config(); -const express = require('express'); -const cache = require('memory-cache'); -const kth = require("@knuth/bch"); +require("dotenv").config(); +const express = require("express"); + +const _kth = require("./src/kth"); +const { router } = require("./src/router"); const app = express(); +app.use(router); -const cacheSeconds = process.env.CACHE_SECONDS; const port = process.env.PORT; -const nodeStdOut = process.env.NODE_STDOUT === 'true'; - -let running_ = false; - -function getNetworkFromEnv() { - if (process.env.NETWORK === 'chipnet') { - return kth.network.chipnet; - } else if (process.env.NETWORK === 'mainnet') { - return kth.network.mainnet; - } else if (process.env.NETWORK === 'testnet') { - return kth.network.testnet; - } else if (process.env.NETWORK === 'testnet4') { - return kth.network.testnet4; - } else if (process.env.NETWORK === 'scalenet') { - return kth.network.scalenet; - } - return kth.network.mainnet; -} - -function sleep(ms) { - return new Promise((r) => setTimeout(r, ms)); -} - -const config = kth.settings.getDefault(getNetworkFromEnv()); -// console.log(`Config: ${JSON.stringify(config)}`); -const node = new kth.node.Node(config, nodeStdOut); -let chain = undefined; - -const cacheMiddleware = (seconds) => { - return (req, res, next) => { - let key = '__express__' + req.originalUrl || req.url; - let cacheContent = cache.get(key); - if (cacheContent) { - res.send(cacheContent); - return; - } else { - res.sendResponse = res.send; - res.send = (body) => { - cache.put(key, body, seconds * 1000); - res.sendResponse(body); - } - next(); - } - } -} - -//TODO(fernando): add version route (version of this library) -//TODO(fernando): add network route -//TODO(fernando): add health route -//TODO(fernando): add status route -//TODO(fernando): js-api version, js-native version, c-api version, c++ api version -//TODO(fernando): chain state route - -app.get('/lastHeight', cacheMiddleware(cacheSeconds), async (req, res) => { - const [e, h] = await node.chain.getLastHeight(); - - if (e === kth.errors.success) { - res.json({height: h}); - } else { - //TODO(fernando): replace 500 with a more specific error code - //TODO(fernando): get the error message from the error code - res.status(500).json({ error: 'An error occurred', errorCode: e }); - } -}); - -app.get('/header/:id', cacheMiddleware(cacheSeconds), async (req, res) => { - const {id} = req.params; - let result; - if (isNaN(id) && id.length === 64) { - // console.log(`Getting block header by hash: ${id}`) - result = await node.chain.getBlockHeaderByHash(kth.enc.Hash.strToBytes(id)); - } else if (!isNaN(id)) { - result = await node.chain.getBlockHeaderByHeight(parseInt(id)); - } else { - res.status(400).json({ error: 'Invalid ID. It should be a block height (a number) or a block hash (a 64 character string).' }); - return; - } - const [e, headerObj, height] = result; - if (e === kth.errors.success) { - const hash = kth.enc.Hash.bytesToStr(kth.header.hash(headerObj)); - const header = { - version: headerObj.version, - previousBlockHash: kth.enc.Hash.bytesToStr(headerObj.previousBlockHash), - merkle: kth.enc.Hash.bytesToStr(headerObj.merkle), - timestamp: headerObj.timestamp, - bits: headerObj.bits, - nonce: headerObj.nonce, - } - res.json({header, height, hash}); - } else { - res.status(500).json({ error: 'An error occurred', errorCode: e }); - } -}); - -app.get('/block/:id', cacheMiddleware(cacheSeconds), async (req, res) => { - const {id} = req.params; - let result; - if (isNaN(id) && id.length === 64) { - // console.log(`Getting block header by hash: ${id}`) - result = await node.chain.getBlockByHash(kth.enc.Hash.strToBytes(id)); - } else if (!isNaN(id)) { - result = await node.chain.getBlockByHeight(parseInt(id)); - } else { - res.status(400).json({ error: 'Invalid ID. It should be a block height (a number) or a block hash (a 64 character string).' }); - return; - } - const [e, blockObj, height] = result; - if (e === kth.errors.success) { - const hash = kth.enc.Hash.bytesToStr(kth.header.hash(blockObj.header)); - const block = { - header: { - version: blockObj.header.version, - previousBlockHash: kth.enc.Hash.bytesToStr(blockObj.header.previousBlockHash), - merkle: kth.enc.Hash.bytesToStr(blockObj.header.merkle), - timestamp: blockObj.header.timestamp, - bits: blockObj.header.bits, - nonce: blockObj.header.nonce, - }, - transactions: blockObj.transactions, - } - res.json({block, height, hash}); - } else { - res.status(500).json({ error: 'An error occurred', errorCode: e }); - } -}); - -app.get('/transaction/:hash', cacheMiddleware(cacheSeconds), async (req, res) => { - const result = await node.chain.getTransaction(req.params.hash); - res.json(result); -}); - -app.get('/transactionPosition/:hash', cacheMiddleware(cacheSeconds), async (req, res) => { - const result = await node.chain.getTransactionPosition(req.params.hash); - res.json(result); -}); - -//TODO(fernando): organizarBlock (POST) -//TODO(fernando): organizarTransaction (POST) - -const server = app.listen(port, () => console.log(`Server listening on port ${port}!`)); - -async function main() { - process.on('SIGINT', shutdown); - await node.launch(kth.startModules.all); - console.log("Knuth node has been launched."); - running_ = true; - - // const [_, height] = await node.chain.getLastHeight(); - // lastBlockHeight = height; - - while (running_) { - // console.log("sleeping...") - await sleep(1000); - } - - console.log("Shutting down Knuth node..."); - node.close(); - console.log("Shutting down Web server..."); - - server.close(() => { - console.log("Good bye!"); - process.exit(); - }); -} -function shutdown() { - console.log(''); - console.log('Ctrl+C detected.'); - running_ = false; -} +const server = app.listen(port, () => + console.log(`Server listening on port ${port}!`) +); (async () => { - try { - await main(); - } catch (e) { - console.log(e); - } + try { + await _kth.main(server); + } catch (e) { + console.log(e); + } })(); diff --git a/src/helper.js b/src/helper.js new file mode 100644 index 0000000..1b30e7e --- /dev/null +++ b/src/helper.js @@ -0,0 +1,40 @@ +const cache = require("memory-cache"); +const kth = require("@knuth/bch"); + +const network = process.env.NETWORK; + +function getNetworkFromEnv() { + if (network === "chipnet") { + return kth.network.chipnet; + } else if (network === "mainnet") { + return kth.network.mainnet; + } else if (network === "testnet") { + return kth.network.testnet; + } else if (network === "testnet4") { + return kth.network.testnet4; + } else if (network === "scalenet") { + return kth.network.scalenet; + } + + return kth.network.mainnet; +} + +const cacheMiddleware = (seconds) => { + return (req, res, next) => { + let key = "__express__" + req.originalUrl || req.url; + let cacheContent = cache.get(key); + if (cacheContent) { + res.send(cacheContent); + return; + } else { + res.sendResponse = res.send; + res.send = (body) => { + cache.put(key, body, seconds * 1000); + res.sendResponse(body); + }; + next(); + } + }; +}; + +module.exports = { getNetworkFromEnv, cacheMiddleware }; diff --git a/src/kth.js b/src/kth.js new file mode 100644 index 0000000..59693cd --- /dev/null +++ b/src/kth.js @@ -0,0 +1,47 @@ +const kth = require("@knuth/bch"); +const helperfn = require("./helper"); + +const nodeStdOut = process.env.NODE_STDOUT === "true"; + +let running_ = false; + +const config = kth.settings.getDefault(helperfn.getNetworkFromEnv()); +// console.log(`Config: ${JSON.stringify(config)}`); +const node = new kth.node.Node(config, nodeStdOut); +let chain = undefined; + +async function main(server) { + process.on("SIGINT", shutdown); + await node.launch(kth.startModules.all); + console.log("Knuth node has been launched."); + running_ = true; + + // const [_, height] = await node.chain.getLastHeight(); + // lastBlockHeight = height; + + while (running_) { + // console.log("sleeping...") + await sleep(1000); + } + + console.log("Shutting down Knuth node..."); + node.close(); + console.log("Shutting down Web server..."); + + server.close(() => { + console.log("Good bye!"); + process.exit(); + }); +} + +function sleep(ms) { + return new Promise((r) => setTimeout(r, ms)); +} + +function shutdown() { + console.log(""); + console.log("Ctrl+C detected."); + running_ = false; +} + +module.exports = { node, main }; diff --git a/src/router.js b/src/router.js new file mode 100644 index 0000000..adf9c0d --- /dev/null +++ b/src/router.js @@ -0,0 +1,42 @@ +const express = require("express"); + +const helperfn = require("./helper"); + +const transaction = require("./routes/transaction"); +const block = require("./routes/block"); +const header = require("./routes/header"); + +const cacheSeconds = process.env.CACHE_SECONDS; + +const router = express.Router(); + +//transactions +router.get( + "/transaction/:hash", + helperfn.cacheMiddleware(cacheSeconds), + transaction.getTransaction +); +router.get( + "/transactionPosition/:hash", + helperfn.cacheMiddleware(cacheSeconds), + transaction.getTransactionPosition +); + +//blocks +router.get( + "/block/:id", + helperfn.cacheMiddleware(cacheSeconds), + block.getBlock +); + +//header +router.get( + "/header/:id", + helperfn.cacheMiddleware(cacheSeconds), + header.getHeader +); + +//router.delete("/orders/:id", _deleteOrder); +//router.post("/orders/add", _addOrder); + +module.exports = { router }; diff --git a/src/routes/block.js b/src/routes/block.js new file mode 100644 index 0000000..d8ab1a0 --- /dev/null +++ b/src/routes/block.js @@ -0,0 +1,43 @@ +const kth = require("@knuth/bch"); + +const _kth = require("../kth"); + +async function getBlock(req, res) { + const { id } = req.params; + let result; + if (isNaN(id) && id.length === 64) { + // console.log(`Getting block header by hash: ${id}`) + result = await _kth.node.chain.getBlockByHash( + kth.enc.Hash.strToBytes(id) + ); + } else if (!isNaN(id)) { + result = await _kth.node.chain.getBlockByHeight(parseInt(id)); + } else { + res.status(400).json({ + error: "Invalid ID. It should be a block height (a number) or a block hash (a 64 character string).", + }); + return; + } + const [e, blockObj, height] = result; + if (e === kth.errors.success) { + const hash = kth.enc.Hash.bytesToStr(kth.header.hash(blockObj.header)); + const block = { + header: { + version: blockObj.header.version, + previousBlockHash: kth.enc.Hash.bytesToStr( + blockObj.header.previousBlockHash + ), + merkle: kth.enc.Hash.bytesToStr(blockObj.header.merkle), + timestamp: blockObj.header.timestamp, + bits: blockObj.header.bits, + nonce: blockObj.header.nonce, + }, + transactions: blockObj.transactions, + }; + res.json({ block, height, hash }); + } else { + res.status(500).json({ error: "An error occurred", errorCode: e }); + } +} + +module.exports = { getBlock }; diff --git a/src/routes/header.js b/src/routes/header.js new file mode 100644 index 0000000..2ce90a7 --- /dev/null +++ b/src/routes/header.js @@ -0,0 +1,40 @@ +const kth = require("@knuth/bch"); + +const _kth = require("../kth"); + +async function getHeader(req, res) { + const { id } = req.params; + let result; + if (isNaN(id) && id.length === 64) { + // console.log(`Getting block header by hash: ${id}`) + result = await _kth.node.chain.getBlockHeaderByHash( + kth.enc.Hash.strToBytes(id) + ); + } else if (!isNaN(id)) { + result = await _kth.node.chain.getBlockHeaderByHeight(parseInt(id)); + } else { + res.status(400).json({ + error: "Invalid ID. It should be a block height (a number) or a block hash (a 64 character string).", + }); + return; + } + const [e, headerObj, height] = result; + if (e === kth.errors.success) { + const hash = kth.enc.Hash.bytesToStr(kth.header.hash(headerObj)); + const header = { + version: headerObj.version, + previousBlockHash: kth.enc.Hash.bytesToStr( + headerObj.previousBlockHash + ), + merkle: kth.enc.Hash.bytesToStr(headerObj.merkle), + timestamp: headerObj.timestamp, + bits: headerObj.bits, + nonce: headerObj.nonce, + }; + res.json({ header, height, hash }); + } else { + res.status(500).json({ error: "An error occurred", errorCode: e }); + } +} + +module.exports = { getHeader }; diff --git a/src/routes/transaction.js b/src/routes/transaction.js new file mode 100644 index 0000000..e75acf6 --- /dev/null +++ b/src/routes/transaction.js @@ -0,0 +1,15 @@ +const _kth = require("../kth"); + +async function getTransaction(req, res) { + const result = await _kth.node.chain.getTransaction(req.params.hash); + res.json(result); +} + +async function getTransactionPosition(req, res) { + const result = await _kth.node.chain.getTransactionPosition( + req.params.hash + ); + res.json(result); +} + +module.exports = { getTransaction, getTransactionPosition }; From 191565b4b39151694e7d48f6d476e06125700f6f Mon Sep 17 00:00:00 2001 From: devperate Date: Thu, 29 Jun 2023 01:09:23 -0400 Subject: [PATCH 2/2] refactor 2nd version --- .gitignore | 1 + index.js | 67 +++++++++++++++++++++++++++++------- src/helper.js | 60 ++++++++++++++++---------------- src/kth.js | 47 ------------------------- src/router.js | 36 ++++++++------------ src/routes/block.js | 72 ++++++++++++++++++--------------------- src/routes/header.js | 66 +++++++++++++++++------------------ src/routes/transaction.js | 14 ++++---- 8 files changed, 171 insertions(+), 192 deletions(-) delete mode 100644 src/kth.js diff --git a/.gitignore b/.gitignore index 2df5f1e..5f3e631 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ blockchain/ debug.log error.log hosts.cache +.prettierrc diff --git a/index.js b/index.js index f81e971..005ddd2 100644 --- a/index.js +++ b/index.js @@ -1,22 +1,65 @@ -require("dotenv").config(); -const express = require("express"); +require('dotenv').config(); +const express = require('express'); +const kth = require('@knuth/bch'); -const _kth = require("./src/kth"); -const { router } = require("./src/router"); +const helperfn = require('./helper'); +const {router} = require('./src/router'); const app = express(); app.use(router); const port = process.env.PORT; +const nodeStdOut = process.env.NODE_STDOUT === 'true'; -const server = app.listen(port, () => - console.log(`Server listening on port ${port}!`) -); +const config = kth.settings.getDefault(helperfn.getNetworkFromEnv()); +// console.log(`Config: ${JSON.stringify(config)}`); +const node = new kth.node.Node(config, nodeStdOut); + +let running_ = false; +let chain = undefined; + +const server = app.listen(port, () => console.log(`Server listening on port ${port}!`)); + +async function main() { + process.on('SIGINT', shutdown); + await node.launch(kth.startModules.all); + console.log('Knuth node has been launched.'); + running_ = true; + + // const [_, height] = await node.chain.getLastHeight(); + // lastBlockHeight = height; + + while (running_) { + // console.log("sleeping...") + await sleep(1000); + } + + console.log('Shutting down Knuth node...'); + node.close(); + console.log('Shutting down Web server...'); + + server.close(() => { + console.log('Good bye!'); + process.exit(); + }); +} + +function sleep(ms) { + return new Promise((r) => setTimeout(r, ms)); +} + +function shutdown() { + console.log(''); + console.log('Ctrl+C detected.'); + running_ = false; +} (async () => { - try { - await _kth.main(server); - } catch (e) { - console.log(e); - } + try { + await main(); + } catch (e) { + console.log(e); + } })(); + +module.exports = {node}; diff --git a/src/helper.js b/src/helper.js index 1b30e7e..6d94a35 100644 --- a/src/helper.js +++ b/src/helper.js @@ -1,40 +1,40 @@ -const cache = require("memory-cache"); -const kth = require("@knuth/bch"); +const cache = require('memory-cache'); +const kth = require('@knuth/bch'); const network = process.env.NETWORK; function getNetworkFromEnv() { - if (network === "chipnet") { - return kth.network.chipnet; - } else if (network === "mainnet") { - return kth.network.mainnet; - } else if (network === "testnet") { - return kth.network.testnet; - } else if (network === "testnet4") { - return kth.network.testnet4; - } else if (network === "scalenet") { - return kth.network.scalenet; - } + if (network === 'chipnet') { + return kth.network.chipnet; + } else if (network === 'mainnet') { + return kth.network.mainnet; + } else if (network === 'testnet') { + return kth.network.testnet; + } else if (network === 'testnet4') { + return kth.network.testnet4; + } else if (network === 'scalenet') { + return kth.network.scalenet; + } - return kth.network.mainnet; + return kth.network.mainnet; } const cacheMiddleware = (seconds) => { - return (req, res, next) => { - let key = "__express__" + req.originalUrl || req.url; - let cacheContent = cache.get(key); - if (cacheContent) { - res.send(cacheContent); - return; - } else { - res.sendResponse = res.send; - res.send = (body) => { - cache.put(key, body, seconds * 1000); - res.sendResponse(body); - }; - next(); - } - }; + return (req, res, next) => { + let key = '__express__' + req.originalUrl || req.url; + let cacheContent = cache.get(key); + if (cacheContent) { + res.send(cacheContent); + return; + } else { + res.sendResponse = res.send; + res.send = (body) => { + cache.put(key, body, seconds * 1000); + res.sendResponse(body); + }; + next(); + } + }; }; -module.exports = { getNetworkFromEnv, cacheMiddleware }; +module.exports = {getNetworkFromEnv, cacheMiddleware}; diff --git a/src/kth.js b/src/kth.js deleted file mode 100644 index 59693cd..0000000 --- a/src/kth.js +++ /dev/null @@ -1,47 +0,0 @@ -const kth = require("@knuth/bch"); -const helperfn = require("./helper"); - -const nodeStdOut = process.env.NODE_STDOUT === "true"; - -let running_ = false; - -const config = kth.settings.getDefault(helperfn.getNetworkFromEnv()); -// console.log(`Config: ${JSON.stringify(config)}`); -const node = new kth.node.Node(config, nodeStdOut); -let chain = undefined; - -async function main(server) { - process.on("SIGINT", shutdown); - await node.launch(kth.startModules.all); - console.log("Knuth node has been launched."); - running_ = true; - - // const [_, height] = await node.chain.getLastHeight(); - // lastBlockHeight = height; - - while (running_) { - // console.log("sleeping...") - await sleep(1000); - } - - console.log("Shutting down Knuth node..."); - node.close(); - console.log("Shutting down Web server..."); - - server.close(() => { - console.log("Good bye!"); - process.exit(); - }); -} - -function sleep(ms) { - return new Promise((r) => setTimeout(r, ms)); -} - -function shutdown() { - console.log(""); - console.log("Ctrl+C detected."); - running_ = false; -} - -module.exports = { node, main }; diff --git a/src/router.js b/src/router.js index adf9c0d..8370999 100644 --- a/src/router.js +++ b/src/router.js @@ -1,10 +1,10 @@ -const express = require("express"); +const express = require('express'); -const helperfn = require("./helper"); +const helperfn = require('./helper'); -const transaction = require("./routes/transaction"); -const block = require("./routes/block"); -const header = require("./routes/header"); +const transaction = require('./routes/transaction'); +const block = require('./routes/block'); +const header = require('./routes/header'); const cacheSeconds = process.env.CACHE_SECONDS; @@ -12,31 +12,23 @@ const router = express.Router(); //transactions router.get( - "/transaction/:hash", - helperfn.cacheMiddleware(cacheSeconds), - transaction.getTransaction + '/transaction/:hash', + helperfn.cacheMiddleware(cacheSeconds), + transaction.getTransaction ); router.get( - "/transactionPosition/:hash", - helperfn.cacheMiddleware(cacheSeconds), - transaction.getTransactionPosition + '/transactionPosition/:hash', + helperfn.cacheMiddleware(cacheSeconds), + transaction.getTransactionPosition ); //blocks -router.get( - "/block/:id", - helperfn.cacheMiddleware(cacheSeconds), - block.getBlock -); +router.get('/block/:id', helperfn.cacheMiddleware(cacheSeconds), block.getBlock); //header -router.get( - "/header/:id", - helperfn.cacheMiddleware(cacheSeconds), - header.getHeader -); +router.get('/header/:id', helperfn.cacheMiddleware(cacheSeconds), header.getHeader); //router.delete("/orders/:id", _deleteOrder); //router.post("/orders/add", _addOrder); -module.exports = { router }; +module.exports = {router}; diff --git a/src/routes/block.js b/src/routes/block.js index d8ab1a0..6654608 100644 --- a/src/routes/block.js +++ b/src/routes/block.js @@ -1,43 +1,39 @@ -const kth = require("@knuth/bch"); +const kth = require('@knuth/bch'); -const _kth = require("../kth"); +const {node} = require('../../index'); async function getBlock(req, res) { - const { id } = req.params; - let result; - if (isNaN(id) && id.length === 64) { - // console.log(`Getting block header by hash: ${id}`) - result = await _kth.node.chain.getBlockByHash( - kth.enc.Hash.strToBytes(id) - ); - } else if (!isNaN(id)) { - result = await _kth.node.chain.getBlockByHeight(parseInt(id)); - } else { - res.status(400).json({ - error: "Invalid ID. It should be a block height (a number) or a block hash (a 64 character string).", - }); - return; - } - const [e, blockObj, height] = result; - if (e === kth.errors.success) { - const hash = kth.enc.Hash.bytesToStr(kth.header.hash(blockObj.header)); - const block = { - header: { - version: blockObj.header.version, - previousBlockHash: kth.enc.Hash.bytesToStr( - blockObj.header.previousBlockHash - ), - merkle: kth.enc.Hash.bytesToStr(blockObj.header.merkle), - timestamp: blockObj.header.timestamp, - bits: blockObj.header.bits, - nonce: blockObj.header.nonce, - }, - transactions: blockObj.transactions, - }; - res.json({ block, height, hash }); - } else { - res.status(500).json({ error: "An error occurred", errorCode: e }); - } + const {id} = req.params; + let result; + if (isNaN(id) && id.length === 64) { + // console.log(`Getting block header by hash: ${id}`) + result = await node.chain.getBlockByHash(kth.enc.Hash.strToBytes(id)); + } else if (!isNaN(id)) { + result = await node.chain.getBlockByHeight(parseInt(id)); + } else { + res.status(400).json({ + error: 'Invalid ID. It should be a block height (a number) or a block hash (a 64 character string).' + }); + return; + } + const [e, blockObj, height] = result; + if (e === kth.errors.success) { + const hash = kth.enc.Hash.bytesToStr(kth.header.hash(blockObj.header)); + const block = { + header: { + version: blockObj.header.version, + previousBlockHash: kth.enc.Hash.bytesToStr(blockObj.header.previousBlockHash), + merkle: kth.enc.Hash.bytesToStr(blockObj.header.merkle), + timestamp: blockObj.header.timestamp, + bits: blockObj.header.bits, + nonce: blockObj.header.nonce + }, + transactions: blockObj.transactions + }; + res.json({block, height, hash}); + } else { + res.status(500).json({error: 'An error occurred', errorCode: e}); + } } -module.exports = { getBlock }; +module.exports = {getBlock}; diff --git a/src/routes/header.js b/src/routes/header.js index 2ce90a7..f6f206a 100644 --- a/src/routes/header.js +++ b/src/routes/header.js @@ -1,40 +1,36 @@ -const kth = require("@knuth/bch"); +const kth = require('@knuth/bch'); -const _kth = require("../kth"); +const {node} = require('../../index'); async function getHeader(req, res) { - const { id } = req.params; - let result; - if (isNaN(id) && id.length === 64) { - // console.log(`Getting block header by hash: ${id}`) - result = await _kth.node.chain.getBlockHeaderByHash( - kth.enc.Hash.strToBytes(id) - ); - } else if (!isNaN(id)) { - result = await _kth.node.chain.getBlockHeaderByHeight(parseInt(id)); - } else { - res.status(400).json({ - error: "Invalid ID. It should be a block height (a number) or a block hash (a 64 character string).", - }); - return; - } - const [e, headerObj, height] = result; - if (e === kth.errors.success) { - const hash = kth.enc.Hash.bytesToStr(kth.header.hash(headerObj)); - const header = { - version: headerObj.version, - previousBlockHash: kth.enc.Hash.bytesToStr( - headerObj.previousBlockHash - ), - merkle: kth.enc.Hash.bytesToStr(headerObj.merkle), - timestamp: headerObj.timestamp, - bits: headerObj.bits, - nonce: headerObj.nonce, - }; - res.json({ header, height, hash }); - } else { - res.status(500).json({ error: "An error occurred", errorCode: e }); - } + const {id} = req.params; + let result; + if (isNaN(id) && id.length === 64) { + // console.log(`Getting block header by hash: ${id}`) + result = await node.chain.getBlockHeaderByHash(kth.enc.Hash.strToBytes(id)); + } else if (!isNaN(id)) { + result = await node.chain.getBlockHeaderByHeight(parseInt(id)); + } else { + res.status(400).json({ + error: 'Invalid ID. It should be a block height (a number) or a block hash (a 64 character string).' + }); + return; + } + const [e, headerObj, height] = result; + if (e === kth.errors.success) { + const hash = kth.enc.Hash.bytesToStr(kth.header.hash(headerObj)); + const header = { + version: headerObj.version, + previousBlockHash: kth.enc.Hash.bytesToStr(headerObj.previousBlockHash), + merkle: kth.enc.Hash.bytesToStr(headerObj.merkle), + timestamp: headerObj.timestamp, + bits: headerObj.bits, + nonce: headerObj.nonce + }; + res.json({header, height, hash}); + } else { + res.status(500).json({error: 'An error occurred', errorCode: e}); + } } -module.exports = { getHeader }; +module.exports = {getHeader}; diff --git a/src/routes/transaction.js b/src/routes/transaction.js index e75acf6..9810451 100644 --- a/src/routes/transaction.js +++ b/src/routes/transaction.js @@ -1,15 +1,13 @@ -const _kth = require("../kth"); +const {node} = require('../../index'); async function getTransaction(req, res) { - const result = await _kth.node.chain.getTransaction(req.params.hash); - res.json(result); + const result = await node.chain.getTransaction(req.params.hash); + res.json(result); } async function getTransactionPosition(req, res) { - const result = await _kth.node.chain.getTransactionPosition( - req.params.hash - ); - res.json(result); + const result = await node.chain.getTransactionPosition(req.params.hash); + res.json(result); } -module.exports = { getTransaction, getTransactionPosition }; +module.exports = {getTransaction, getTransactionPosition};