Removed dist folder

This commit is contained in:
Chris Troutner
2019-05-27 19:45:54 -07:00
parent d89e7cb2d3
commit b6c2debd0e
15 changed files with 0 additions and 34659 deletions
Vendored
-234
View File
@@ -1,234 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var express = require("express");
// Middleware
var route_ratelimit_1 = require("./middleware/route-ratelimit");
var path = require("path");
var logger = require("morgan");
var wlogger = require("./util/winston-logging");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var basicAuth = require("express-basic-auth");
var helmet = require("helmet");
var debug = require("debug")("rest-cloud:server");
var http = require("http");
var cors = require("cors");
var AuthMW = require("./middleware/auth");
var BitcoinCashZMQDecoder = require("bitcoincash-zmq-decoder");
var zmq = require("zeromq");
var sock = zmq.socket("sub");
var swStats = require("swagger-stats");
var apiSpec;
if (process.env.NETWORK === "mainnet") {
apiSpec = require("./public/bitcoin-com-mainnet-rest-v2.json");
}
else {
apiSpec = require("./public/bitcoin-com-testnet-rest-v2.json");
}
// v1
var indexV1 = require("./routes/v1/index");
var healthCheckV1 = require("./routes/v1/health-check");
var addressV1 = require("./routes/v1/address");
var blockV1 = require("./routes/v1/block");
var blockchainV1 = require("./routes/v1/blockchain");
var controlV1 = require("./routes/v1/control");
var generatingV1 = require("./routes/v1/generating");
var miningV1 = require("./routes/v1/mining");
var networkV1 = require("./routes/v1/network");
var rawtransactionsV1 = require("./routes/v1/rawtransactions");
var transactionV1 = require("./routes/v1/transaction");
var utilV1 = require("./routes/v1/util");
var dataRetrievalV1 = require("./routes/v1/dataRetrieval");
var payloadCreationV1 = require("./routes/v1/payloadCreation");
var slpV1 = require("./routes/v1/slp");
// v2
var indexV2 = require("./routes/v2/index");
var healthCheckV2 = require("./routes/v2/health-check");
var addressV2 = require("./routes/v2/address");
var blockV2 = require("./routes/v2/block");
var blockchainV2 = require("./routes/v2/blockchain");
var controlV2 = require("./routes/v2/control");
var generatingV2 = require("./routes/v2/generating");
var miningV2 = require("./routes/v2/mining");
var networkV2 = require("./routes/v2/network");
var rawtransactionsV2 = require("./routes/v2/rawtransactions");
var transactionV2 = require("./routes/v2/transaction");
var utilV2 = require("./routes/v2/util");
var slpV2 = require("./routes/v2/slp");
require("dotenv").config();
var app = express();
app.locals.env = process.env;
app.use(swStats.getMiddleware({ swaggerSpec: apiSpec }));
app.use(helmet());
app.use(cors());
app.enable("trust proxy");
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use("/public", express.static(__dirname + "/public"));
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
// Make io accessible to our router
app.use(function (req, res, next) {
req.io = io;
next();
});
var v1prefix = "v1";
var v2prefix = "v2";
app.use("/", indexV1);
app.use("/" + v1prefix + "/" + "health-check", healthCheckV1);
app.use("/" + v1prefix + "/" + "address", addressV1);
app.use("/" + v1prefix + "/" + "blockchain", blockchainV1);
app.use("/" + v1prefix + "/" + "block", blockV1);
app.use("/" + v1prefix + "/" + "control", controlV1);
app.use("/" + v1prefix + "/" + "generating", generatingV1);
app.use("/" + v1prefix + "/" + "mining", miningV1);
app.use("/" + v1prefix + "/" + "network", networkV1);
app.use("/" + v1prefix + "/" + "rawtransactions", rawtransactionsV1);
app.use("/" + v1prefix + "/" + "transaction", transactionV1);
app.use("/" + v1prefix + "/" + "util", utilV1);
app.use("/" + v1prefix + "/" + "dataRetrieval", dataRetrievalV1);
app.use("/" + v1prefix + "/" + "payloadCreation", payloadCreationV1);
app.use("/" + v1prefix + "/" + "slp", slpV1);
// Instantiate the authorization middleware, used to implement pro-tier rate limiting.
var auth = new AuthMW();
app.use("/" + v2prefix + "/", auth.mw());
// Rate limit on all v2 routes
app.use("/" + v2prefix + "/", route_ratelimit_1.routeRateLimit);
app.use("/", indexV2);
app.use("/" + v2prefix + "/" + "health-check", healthCheckV2);
app.use("/" + v2prefix + "/" + "address", addressV2.router);
app.use("/" + v2prefix + "/" + "blockchain", blockchainV2.router);
app.use("/" + v2prefix + "/" + "block", blockV2.router);
app.use("/" + v2prefix + "/" + "control", controlV2.router);
app.use("/" + v2prefix + "/" + "generating", generatingV2);
app.use("/" + v2prefix + "/" + "mining", miningV2.router);
app.use("/" + v2prefix + "/" + "network", networkV2);
app.use("/" + v2prefix + "/" + "rawtransactions", rawtransactionsV2.router);
app.use("/" + v2prefix + "/" + "transaction", transactionV2.router);
app.use("/" + v2prefix + "/" + "util", utilV2.router);
app.use("/" + v2prefix + "/" + "slp", slpV2.router);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = {
message: "Not Found",
status: 404
};
next(err);
});
// error handler
app.use(function (err, req, res, next) {
var status = err.status || 500;
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(status);
res.json({
status: status,
message: err.message
});
});
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || "3000");
app.set("port", port);
console.log("rest.bitcoin.com started on port " + port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
var io = require("socket.io").listen(server);
io.on("connection", function (socket) {
console.log("Socket Connected");
socket.on("disconnect", function () {
console.log("Socket Disconnected");
});
});
/**
* Setup ZMQ connections if ZMQ URL and port provided
*/
if (process.env.ZEROMQ_URL && process.env.ZEROMQ_PORT) {
console.log("Connecting to BCH ZMQ at " + process.env.ZEROMQ_URL + ":" + process.env.ZEROMQ_PORT);
var bitcoincashZmqDecoder_1 = new BitcoinCashZMQDecoder(process.env.NETWORK);
sock.connect("tcp://" + process.env.ZEROMQ_URL + ":" + process.env.ZEROMQ_PORT);
sock.subscribe("raw");
sock.on("message", function (topic, message) {
try {
var decoded = topic.toString("ascii");
if (decoded === "rawtx") {
var txd = bitcoincashZmqDecoder_1.decodeTransaction(message);
io.emit("transactions", JSON.stringify(txd, null, 2));
}
else if (decoded === "rawblock") {
var blck = bitcoincashZmqDecoder_1.decodeBlock(message);
io.emit("blocks", JSON.stringify(blck, null, 2));
}
}
catch (error) {
var errorMessage = 'Error processing ZMQ message';
console.log(errorMessage, error);
wlogger.error(errorMessage, error);
}
});
}
else {
console.log("ZEROMQ_URL and ZEROMQ_PORT env vars missing. Skipping ZMQ connection.");
}
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on("error", onError);
server.on("listening", onListening);
// Set the time before a timeout error is generated. This impacts testing and
// the handling of timeout errors. Is 10 seconds too agressive?
server.setTimeout(30 * 1000);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== "listen")
throw error;
var bind = typeof port === "string" ? "Pipe " + port : "Port " + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
debug("Listening on " + bind);
}
-78
View File
@@ -1,78 +0,0 @@
/*
Handle authorization for bypassing rate limits.
This file uses the passport npm library to check the header of each REST API
call for the prescence of a Basic authorization header:
https://en.wikipedia.org/wiki/Basic_access_authentication
If the header is found and validated, the req.locals.proLimit Boolean value
is set and passed to the route-ratelimits.ts middleware.
*/
"use strict";
var passport = require("passport");
var BasicStrategy = require("passport-http").BasicStrategy;
var AnonymousStrategy = require("passport-anonymous");
var wlogger = require("../util/winston-logging");
// Used for debugging and iterrogating JS objects.
var util = require("util");
util.inspect.defaultOptions = { depth: 1 };
var _this;
// Set default rate limit value for testing
var PRO_PASSes = process.env.PRO_PASS ? process.env.PRO_PASS : "BITBOX";
// Convert the pro-tier password string into an array split by ':'.
var PRO_PASS = PRO_PASSes.split(":");
//wlogger.verbose(`PRO_PASS set to: ${PRO_PASS}`)
// Auth Middleware
var AuthMW = /** @class */ (function () {
function AuthMW() {
_this = this;
// Initialize passport for 'anonymous' authentication.
/*
passport.use(
new AnonymousStrategy({ passReqToCallback: true }, function(
req,
username,
password,
done
) {
console.log(`anonymous auth handler triggered.`)
})
)
*/
passport.use(new AnonymousStrategy());
// Initialize passport for 'basic' authentication.
passport.use(new BasicStrategy({ passReqToCallback: true }, function (req, username, password, done) {
//console.log(`req: ${util.inspect(req)}`)
//console.log(`username: ${username}`)
//console.log(`password: ${password}`)
// Create the req.locals property if it does not yet exist.
if (!req.locals)
req.locals = {};
// Set pro-tier rate limit to flag to false by default.
req.locals.proLimit = false;
// Evaluate the username and password and set the rate limit accordingly.
//if (username === "BITBOX" && password === PRO_PASS) {
if (username === "BITBOX") {
for (var i = 0; i < PRO_PASS.length; i++) {
var thisPass = PRO_PASS[i];
if (password === thisPass) {
wlogger.verbose(req.url + " called by " + password.slice(0, 6));
// Success
req.locals.proLimit = true;
break;
}
}
}
//console.log(`req.locals: ${util.inspect(req.locals)}`)
return done(null, true);
}));
}
// Middleware called by the route.
AuthMW.prototype.mw = function () {
return passport.authenticate(["basic", "anonymous"], {
session: false
});
};
return AuthMW;
}());
module.exports = AuthMW;
-81
View File
@@ -1,81 +0,0 @@
"use strict";
/*
This file controls the request-per-minute (RPM) rate limits.
It is assumed that this middleware is run AFTER the auth.js middleware which
checks for Basic auth. If the user adds the correct Basic auth to the header
of their API request, they will get pro-tier rate limits. By default, the
freemium rate limits apply.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var RateLimit = require("express-rate-limit");
// Set max requests per minute
var maxRequests = process.env.RATE_LIMIT_MAX_REQUESTS
? parseInt(process.env.RATE_LIMIT_MAX_REQUESTS)
: 60;
// Pro-tier rate limits are 10x the freemium limits.
var PRO_RPM = 10 * maxRequests;
// Unique route mapped to its rate limit
var uniqueRateLimits = {};
var routeRateLimit = function (req, res, next) {
// Create a res.locals object if not passed in.
if (!req.locals)
req.locals = {};
// Disable rate limiting if 0 passed from RATE_LIMIT_MAX_REQUESTS
if (maxRequests === 0)
return next();
// Current route
var rateLimitTier = req.locals.proLimit ? "PRO" : "BASIC";
var path = req.baseUrl + req.path;
var route = rateLimitTier +
req.method +
path
.split("/")
.slice(0, 4)
.join("/");
// This boolean value is passed from the auth.js middleware.
var proRateLimits = req.locals.proLimit;
// Pro level rate limits
if (proRateLimits) {
// TODO: replace the console.logs with calls to our logging system.
//console.log(`applying pro-rate limits`)
// Create new RateLimit if none exists for this route
if (!uniqueRateLimits[route]) {
uniqueRateLimits[route] = new RateLimit({
windowMs: 60 * 1000,
delayMs: 0,
max: PRO_RPM,
handler: function (req, res /*next*/) {
//console.log(`pro-tier rate-handler triggered.`)
res.status(429); // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
return res.json({
error: "Too many requests. Limits are " + PRO_RPM + " requests per minute."
});
}
});
}
// Freemium level rate limits
}
else {
// TODO: replace the console.logs with calls to our logging system.
//console.log(`applying freemium limits`)
// Create new RateLimit if none exists for this route
if (!uniqueRateLimits[route]) {
uniqueRateLimits[route] = new RateLimit({
windowMs: 60 * 1000,
delayMs: 0,
max: maxRequests,
handler: function (req, res /*next*/) {
//console.log(`freemium rate-handler triggered.`)
res.status(429); // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
return res.json({
error: "Too many requests. Limits are " + maxRequests + " requests per minute."
});
}
});
}
}
// Call rate limit for this route
uniqueRateLimits[route](req, res, next);
};
exports.routeRateLimit = routeRateLimit;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

-16468
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-1726
View File
File diff suppressed because it is too large Load Diff
-3
View File
File diff suppressed because one or more lines are too long
-45
View File
@@ -1,45 +0,0 @@
/*
Instantiates and configures the Winston logging library. This utitlity library
can be called by other parts of the application to conveniently tap into the
logging library.
*/
"use strict";
var winston = require("winston");
require("winston-daily-rotate-file");
var NETWORK = process.env.NETWORK;
// Configure daily-rotation transport.
var transport = new winston.transports.DailyRotateFile({
filename: __dirname + "/../../logs/rest-" + NETWORK + "-%DATE%.log",
datePattern: "YYYY-MM-DD",
zippedArchive: false,
maxSize: "1m",
maxFiles: "5d",
format: winston.format.combine(winston.format.timestamp(), winston.format.json())
});
transport.on("rotate", function (oldFilename, newFilename) {
wlogger.info("Rotating log files");
});
// This controls what goes into the log FILES
var wlogger = winston.createLogger({
level: "verbose",
format: winston.format.json(),
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
// new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
// new winston.transports.File({ filename: 'logs/combined.log' })
transport
]
});
// This controls the logs to CONSOLE
/*
wlogger.add(
new winston.transports.Console({
format: winston.format.simple(),
level: "info"
})
)
*/
module.exports = wlogger;
-64
View File
@@ -1,64 +0,0 @@
doctype html
// HTML for static distribution bundle build
html(lang='en')
head
// Global site tag (gtag.js) - Google Analytics
script(async='', src='https://www.googletagmanager.com/gtag/js?id=UA-115463658-5')
script.
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-115463658-5');
meta(charset='UTF-8')
title REST V2 by Bitcoin.com - BCH RPC over HTTP
link(href='https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700', rel='stylesheet')
link(rel='stylesheet', type='text/css', href='../../public/swagger-ui-v2.css')
link(rel='icon', type='image/png', href='../public/favicon.png', sizes='32x32')
style.
html
{
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after
{
box-sizing: inherit;
}
body
{
margin:0;
background: #fafafa;
}
body
#swagger-ui
script(src='../public/swagger-ui-bundle.js')
script(src='../public/swagger-ui-standalone-preset.js')
script.
window.onload = function() {
let network = "#{env.NETWORK}"
let path;
if(network === 'mainnet') {
path = "../public/bitcoin-com-mainnet-rest-v2.json"
} else {
path = "../public/bitcoin-com-testnet-rest-v2.json"
}
const ui = SwaggerUIBundle({
url: path,
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}
-57
View File
@@ -1,57 +0,0 @@
doctype html
// HTML for static distribution bundle build
html(lang='en')
head
// Global site tag (gtag.js) - Google Analytics
script(async='', src='https://www.googletagmanager.com/gtag/js?id=UA-115463658-5')
script.
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-115463658-5');
meta(charset='UTF-8')
title REST by Bitcoin.com - BCH RPC over HTTP
link(href='https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700', rel='stylesheet')
link(rel='stylesheet', type='text/css', href='../public/swagger-ui.css')
link(rel='icon', type='image/png', href='../public/favicon.png', sizes='32x32')
style.
html
{
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after
{
box-sizing: inherit;
}
body
{
margin:0;
background: #fafafa;
}
body
#swagger-ui
script(src='../public/swagger-ui-bundle.js')
script(src='../public/swagger-ui-standalone-preset.js')
script.
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: "../public/bitcoin-com-rest-v1.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}