-
Notifications
You must be signed in to change notification settings - Fork 37
/
app.js
231 lines (194 loc) · 5.82 KB
/
app.js
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let basicAuth = require('express-basic-auth');
let helmet = require('helmet');
let RateLimit = require('express-rate-limit');
let axios = require('axios');
let debug = require('debug')('rest-cloud:server');
let http = require('http');
let TxDecoder = require('bitcoin-txdecoder');
let zmq = require('zeromq')
, sock = zmq.socket('sub');
let swStats = require('swagger-stats');
let apiSpec = require('./public/bitbox-rest-v1.json');
require('dotenv').config()
let app = express();
let index = require('./routes/index');
let healthCheck = require('./routes/health-check');
let address = require('./routes/address');
let block = require('./routes/block');
let blockchain = require('./routes/blockchain');
let control = require('./routes/control');
let generating = require('./routes/generating');
let mining = require('./routes/mining');
let network = require('./routes/network');
let rawtransactions = require('./routes/rawtransactions');
let transaction = require('./routes/transaction');
let util = require('./routes/util');
app.use(swStats.getMiddleware({ swaggerSpec: apiSpec }));
app.use(helmet());
let cors = require('cors')
app.use(cors())
app.enable('trust proxy');
let limiter = new RateLimit({
windowMs: 60000, // 1 minute
max: 60, // limit each IP to 20 requests per windowMs
delayMs: 0, // disable delaying - full speed until the max limit is reached
handler: function (req, res, /*next*/) {
res.format({
json: function () {
res.status(500).json({ error: 'Too many requests. Limits are 60 requests per minute.' });
}
});
}
});
app.use('/v1/', limiter);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use("/public", express.static(__dirname + "/public"));
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
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')));
//
// let username = process.env.USERNAME;
// let password = process.env.PASSWORD;
//
// app.use(basicAuth(
// {
// users: { username: password }
// }
// ));
// Make io accessible to our router
app.use(function (req, res, next) {
req.io = io;
next();
});
let prefix = 'v1';
app.use('/', index);
app.use('/' + prefix + '/' + 'health-check', healthCheck);
app.use('/' + prefix + '/' + 'address', address);
app.use('/' + prefix + '/' + 'blockchain', blockchain);
app.use('/' + prefix + '/' + 'block', block);
app.use('/' + prefix + '/' + 'control', control);
app.use('/' + prefix + '/' + 'generating', generating);
app.use('/' + prefix + '/' + 'mining', mining);
app.use('/' + prefix + '/' + 'network', network);
app.use('/' + prefix + '/' + 'rawtransactions', rawtransactions);
app.use('/' + prefix + '/' + 'transaction', transaction);
app.use('/' + prefix + '/' + 'util', util);
// catch 404 and forward to error handler
app.use((req, res, next) => {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function (err, req, res, next) {
// 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(err.status || 500);
res.json({
status: 500,
message: err.message
});
});
/**
* Get port from environment and store in Express.
*/
let port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
let server = http.createServer(app);
let io = require('socket.io').listen(server);
io.on('connection', (socket) => {
console.log("Socket Connected")
socket.on('disconnect', () => {
console.log("Socket Disconnected")
})
});
sock.connect(`tcp://${process.env.ZEROMQ_URL}:${process.env.ZEROMQ_PORT}`);
sock.subscribe('raw');
sock.on('message', (topic, message) => {
let decoded = topic.toString('ascii');
if (decoded === 'rawtx') {
let network;
if (process.env.NETWORK === 'mainnet') {
network = { 'pubKeyHash': 0x00, 'scriptHash': 0x05 };
} else if (process.env.NETWORK === 'testnet') {
network = { 'pubKeyHash': 0x6F, 'scriptHash': 0xC4 };
}
let txd = new TxDecoder(message, network);
io.emit('transactions', JSON.stringify(txd.toObject(), null, 2));
} else if (decoded === 'rawblock') {
}
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
let 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;
}
let 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() {
let addr = server.address();
let bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
//
// module.exports = app;