-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathexplorer.js
More file actions
246 lines (200 loc) · 6.75 KB
/
Copy pathexplorer.js
File metadata and controls
246 lines (200 loc) · 6.75 KB
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/*jslint node: true */
"use strict";
const { existsSync, renameSync } = require('fs');
var desktopApp = require('ocore/desktop_app.js');
var appDataDir = desktopApp.getAppDataDir();
var path = require('path');
if (require.main === module && !existsSync(appDataDir) && existsSync(path.dirname(appDataDir)+'/byteball-explorer')){
console.log('=== will rename old explorer data dir');
renameSync(path.dirname(appDataDir)+'/byteball-explorer', appDataDir);
}
require('./relay');
var conf = require('ocore/conf.js');
var eventBus = require('ocore/event_bus.js');
var network = require('ocore/network.js');
const device = require('ocore/device');
const express = require("express");
const cors = require('cors')
const { createServer } = require("http");
const { Server } = require("socket.io");
const randomString = require('./utils/randomString');
const app = express();
const httpServer = createServer(app);
const api = require('./gateways/api');
const BalanceDumpService = require('./services/BalanceDumpService');
const io = new Server(httpServer, {
cors: {
origin: "*"
}
});
let exchange_rates = {};
if (conf.initial_peers) {
const firstPeer = conf.initial_peers[0];
const hubAddress = firstPeer.startsWith('wss://') ? firstPeer.substring(6) : firstPeer.substring(5);
device.setDeviceHub(hubAddress);
network.findOutboundPeerOrConnect(firstPeer, (err, ws) => {
if (err)
return console.log('failed to connect to initial peer ' + firstPeer + ': ' + err);
ws.bLoggedIn = true;
network.sendRequest(ws, 'hub/get_exchange_rates', null, null, (ws, err, result) => {
exchange_rates = result;
})
});
}
eventBus.on('new_joint', function() {
io.sockets.emit('update');
});
eventBus.on('rates_updated', function() {
exchange_rates = { ...exchange_rates, ...network.exchangeRates };
console.log('rates_updated: ', exchange_rates);
io.sockets.emit('rates_updated', exchange_rates);
});
const activeRequests = new Map();
app.use((req, res, next) => {
const id = randomString();
const start = Date.now();
activeRequests.set(id, { start, url: req.url, method: req.method, params: req.query });
console.log(`[start:${id}] ${req.url}`);
let cleaned = false;
function cleanup() {
if (cleaned) return;
cleaned = true;
const end = Date.now() - start;
const isLong = end > 1000;
console.log(`[end:${id}] ${req.url} ${res.statusCode} ${end}ms${isLong ? ' (long)' : ''}`);
activeRequests.delete(id);
}
res.once('finish', cleanup);
res.once('close', cleanup);
next();
});
app.use(cors());
function sendJsonResult(res, result) {
if (result && result.statusCode) {
res.status(result.statusCode);
}
res.json(result);
}
function sendRouteError(res, err) {
console.error('route error', err);
if (res.headersSent || res.writableEnded) {
return;
}
res.status(500).json({ error: 'internal_error', message: 'Internal error' });
}
function asyncRoute(handler) {
return (req, res) => {
Promise.resolve(handler(req, res)).catch(err => sendRouteError(res, err));
};
}
function registerSocketHandler(socket, eventName, handler) {
socket.on(eventName, async (...args) => {
const cb = args[args.length - 1];
if (typeof cb !== 'function') {
return;
}
try {
await handler(...args);
} catch (err) {
console.error('socket handler error', eventName, err);
cb({ error: 'internal_error', message: 'Internal error' });
}
});
}
app.get('/api/unit/:unit', asyncRoute(async(req, res) => {
if (req.params.unit.length !== 44) {
return res.json({ notFound: true });
}
await api.dagGateway.info(req.params.unit, result => {
sendJsonResult(res, result);
});
}));
app.get('/api/address/:address/info', asyncRoute(async (req, res) => {
if (req.params.address.length !== 32) {
return res.json({ notFound: true });
}
const params = {
address: req.params.address,
...req.query,
}
await api.addressGateway.getAddressData(params, result => {
sendJsonResult(res, result);
});
}));
app.get('/api/address/:address/next_page', asyncRoute(async (req, res) => {
if (req.params.address.length !== 32) {
return res.json({ notFound: true });
}
const params = {
address: req.params.address,
...req.query
}
await api.addressGateway.loadNextPageAddressTransactions(params, result => {
sendJsonResult(res, result);
});
}));
app.get('/api/asset/:asset/info', asyncRoute(async (req, res) => {
const params = {
asset: req.params.asset,
}
await api.assetGateway.getAssetData(params, result => {
sendJsonResult(res, result);
});
}));
app.get('/api/asset/:asset/next_page_transactions', asyncRoute(async (req, res) => {
const params = {
asset: req.params.asset,
...req.query,
}
await api.assetGateway.loadNextPageAssetTransactions(params, result => {
sendJsonResult(res, result);
});
}));
app.get('/api/asset/:asset/next_page_holders', asyncRoute(async (req, res) => {
const params = {
asset: req.params.asset,
...req.query,
}
await api.assetGateway.loadNextPageAssetHolders(params, result => {
sendJsonResult(res, result);
});
}));
io.on('connection', async (socket) => {
socket.emit('rates_updated', exchange_rates);
registerSocketHandler(socket, 'info', api.dagGateway.info);
registerSocketHandler(socket, 'newUnits', api.dagGateway.newUnits);
registerSocketHandler(socket, 'nextUnits', api.dagGateway.nextUnits);
registerSocketHandler(socket, 'prevUnits', api.dagGateway.prevUnits);
registerSocketHandler(socket, 'getUnit', api.dagGateway.getUnit);
registerSocketHandler(socket, 'getLastUnits', api.dagGateway.getLastUnits);
registerSocketHandler(socket, 'highlightNode', api.dagGateway.highlightNode);
registerSocketHandler(socket, 'getAddressData', api.addressGateway.getAddressData);
registerSocketHandler(socket, 'loadNextPageAddressTransactions', api.addressGateway.loadNextPageAddressTransactions);
registerSocketHandler(socket, 'getAssetData', api.assetGateway.getAssetData);
registerSocketHandler(socket, 'loadNextPageAssetTransactions', api.assetGateway.loadNextPageAssetTransactions);
registerSocketHandler(socket, 'loadNextPageAssetHolders', api.assetGateway.loadNextPageAssetHolders);
registerSocketHandler(socket, 'fetchAssetNamesList', api.assetGateway.fetchAssetNamesList);
try {
await api.assetGateway.fetchAssetNamesList(({ assetNames }) => {
socket.emit('updateAssetsList', assetNames);
})
} catch (err) {
console.error('failed to fetch asset names list', err);
}
});
httpServer.listen(conf.webPort);
async function start() {
const balanceDumpService = new BalanceDumpService();
await balanceDumpService.start();
}
start();
process.on('uncaughtException', (err) => {
console.error('uncaughtException', err);
console.error('activeRequests', activeRequests);
process.exit(1);
});
process.on('unhandledRejection', (reason) => {
console.error('unhandledRejection', reason);
console.error('activeRequests', activeRequests);
process.exit(1);
});