-
Notifications
You must be signed in to change notification settings - Fork 49
/
Xud.ts
331 lines (291 loc) · 10.4 KB
/
Xud.ts
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import { AssertionError } from 'assert';
import { EventEmitter } from 'events';
import { promises as fs } from 'fs';
import path from 'path';
import { Subscription } from 'rxjs';
import bootstrap from './bootstrap';
import Config from './Config';
import { SwapClientType, XuNetwork } from './constants/enums';
import DB from './db/DB';
import GrpcServer from './grpc/GrpcServer';
import GrpcWebProxyServer from './grpc/webproxy/GrpcWebProxyServer';
import HttpServer from './http/HttpServer';
import Logger from './Logger';
import NodeKey from './nodekey/NodeKey';
import OrderBook from './orderbook/OrderBook';
import Pool from './p2p/Pool';
import InitService from './service/InitService';
import Service from './service/Service';
import SwapClientManager from './swaps/SwapClientManager';
import Swaps from './swaps/Swaps';
import { createSimnetChannels } from './utils/simnet-connext-channels';
import { UnitConverter } from './utils/UnitConverter';
const version: string = require('../package.json').version;
interface Xud {
on(event: 'shutdown', listener: () => void): this;
emit(event: 'shutdown'): boolean;
}
bootstrap();
/** Class representing a complete Exchange Union daemon. */
class Xud extends EventEmitter {
public service!: Service;
private logger!: Logger;
private config: Config;
private db!: DB;
private pool!: Pool;
private orderBook!: OrderBook;
private rpcServer?: GrpcServer;
private httpServer?: HttpServer;
private grpcAPIProxy?: GrpcWebProxyServer;
private swaps!: Swaps;
private shuttingDown = false;
private swapClientManager?: SwapClientManager;
private unitConverter?: UnitConverter;
private simnetChannels$?: Subscription;
/**
* Create an Exchange Union daemon.
*/
constructor() {
super();
this.config = new Config();
process.on('SIGINT', () => {
this.beginShutdown();
});
process.on('SIGTERM', () => {
this.beginShutdown();
});
}
/**
* Start all processes necessary for the operation of an Exchange Union node.
* @param args optional arguments to override configuration parameters.
*/
public start = async (args?: { [argName: string]: any }) => {
let configFileLoaded: boolean;
try {
configFileLoaded = await this.config.load(args);
} catch (err) {
if (err instanceof AssertionError) {
console.error(err.message);
process.exit(1);
} else {
throw err;
}
}
const loggers = Logger.createLoggers(this.config.loglevel, this.config.logpath, this.config.instanceid, this.config.logdateformat);
this.logger = loggers.global;
if (configFileLoaded) {
this.logger.info('config file loaded');
}
try {
if (!this.config.rpc.disable) {
// start rpc server first, it will respond with UNAVAILABLE error
// indicating xud is starting until xud finishes initializing
this.rpcServer = new GrpcServer(loggers.rpc);
await this.rpcServer.listen(
this.config.rpc.port,
this.config.rpc.host,
path.join(this.config.xudir, 'tls.cert'),
path.join(this.config.xudir, 'tls.key'),
);
if (!this.config.webproxy.disable) {
this.grpcAPIProxy = new GrpcWebProxyServer(loggers.rpc);
await this.grpcAPIProxy.listen(
this.config.webproxy.port,
this.config.rpc.port,
this.config.rpc.host,
path.join(this.config.xudir, 'tls.cert'),
);
}
}
this.db = new DB(loggers.db, this.config.dbpath);
await this.db.init(this.config.network, this.config.initdb);
this.unitConverter = new UnitConverter();
this.unitConverter.init();
const nodeKeyPath = NodeKey.getPath(this.config.xudir, this.config.instanceid);
const nodeKeyExists = await fs.access(nodeKeyPath).then(() => true).catch(() => false);
this.swapClientManager = new SwapClientManager(this.config, loggers, this.unitConverter);
await this.swapClientManager.init(this.db.models);
let nodeKey: NodeKey | undefined;
if (this.config.noencrypt) {
if (nodeKeyExists) {
nodeKey = await NodeKey.fromFile(nodeKeyPath);
} else {
nodeKey = await NodeKey.generate();
await nodeKey.toFile(nodeKeyPath);
}
} else if (this.rpcServer) {
this.rpcServer.grpcService.locked = true;
const initService = new InitService(this.swapClientManager, nodeKeyPath, nodeKeyExists, this.config.dbpath);
this.rpcServer.grpcInitService.setInitService(initService);
this.logger.info("Node key is encrypted, unlock with 'xucli unlock', 'xucli create', or 'xucli restore'");
nodeKey = await new Promise<NodeKey | undefined>((resolve) => {
initService.once('nodekey', resolve);
this.on('shutdown', () => {
// in case we shutdown before unlocking xud
resolve();
initService.removeListener('nodekey', resolve);
});
});
if (!nodeKey) {
return; // we interrupted before unlocking xud
}
this.rpcServer.grpcService.locked = false;
} else {
throw new Error('rpc server cannot be disabled when xud is locked');
}
if (this.rpcServer) {
this.rpcServer.grpcInitService.disable();
}
this.logger.info(`Local nodePubKey is ${nodeKey.pubKey}`);
this.pool = new Pool({
nodeKey,
version,
config: this.config.p2p,
xuNetwork: this.config.network,
logger: loggers.p2p,
models: this.db.models,
strict: this.config.strict,
});
const initPromises: Promise<any>[] = [];
this.swaps = new Swaps({
logger: loggers.swaps,
models: this.db.models,
pool: this.pool,
swapClientManager: this.swapClientManager,
strict: this.config.strict,
});
initPromises.push(this.swaps.init());
this.orderBook = new OrderBook({
logger: loggers.orderbook,
models: this.db.models,
thresholds: this.config.orderthresholds,
nomatching: this.config.nomatching,
pool: this.pool,
swaps: this.swaps,
nosanityswaps: this.config.nosanityswaps,
nobalancechecks: this.config.nobalancechecks,
strict: this.config.strict,
});
initPromises.push(this.orderBook.init());
// wait for components to initialize in parallel
await Promise.all(initPromises);
// We initialize Connext separately because it
// requires a NodeKey.
await this.swapClientManager.initConnext(
nodeKey.childSeed(SwapClientType.Connext),
);
// initialize pool and start listening/connecting only once other components are initialized
await this.pool.init();
this.service = new Service({
version,
orderBook: this.orderBook,
swapClientManager: this.swapClientManager,
pool: this.pool,
swaps: this.swaps,
logger: loggers.service,
shutdown: this.beginShutdown,
});
if (
this.swapClientManager.raidenClient?.isOperational() ||
this.swapClientManager.connextClient?.isOperational()
) {
this.httpServer = new HttpServer(loggers.http, this.service);
await this.httpServer.listen(
this.config.http.port,
this.config.http.host,
);
}
// if we're running in simnet mode and Connext is enabled we'll
// attempt to request funds from the faucet and open a channel
// to the node once we have received the on-chain funds
if (
this.config.network === XuNetwork.SimNet &&
this.swapClientManager.connextClient?.isOperational()
) {
this.simnetChannels$ = createSimnetChannels({
channels: [
{
currency: 'ETH',
// amount of currency to put in the channel
channelAmount: 1000000000,
// minimum channelBalance threshold
minChannelAmount: 100000000,
},
{
currency: 'USDT',
channelAmount: 100000000000,
minChannelAmount: 100000000,
},
],
// we check the channel and on-chain balance every 10 seconds
// and refund from faucet if below the walletAmount
retryInterval: 10000,
}).subscribe({
next: (currency) => {
this.logger.info(`Connext wallet funded and channel opened for ${currency}`);
},
error: (e) => {
this.logger.error(`Failed to fund Connext wallet and open a channel: ${e}`);
},
complete: () => {
this.logger.info('Stopped monitoring Connext balances for automatic funding and channel creation');
},
});
}
// initialize rpc server last
if (this.rpcServer) {
this.rpcServer.grpcService.setService(this.service);
} else {
this.logger.info('RPC server is disabled.');
}
} catch (err) {
this.logger.error('Unexpected error during initialization, shutting down...', err);
await this.shutdown();
}
}
private shutdown = async () => {
if (this.shuttingDown) {
this.logger.info('XUD is already shutting down');
return;
}
this.shuttingDown = true;
this.logger.info('XUD is shutting down');
// TODO: ensure we are not in the middle of executing any trades
const closePromises: Promise<void>[] = [];
this.simnetChannels$?.unsubscribe();
if (this.swapClientManager) {
this.swapClientManager.close();
}
if (this.httpServer) {
closePromises.push(this.httpServer.close());
}
if (this.pool) {
closePromises.push(this.pool.disconnect());
}
if (this.rpcServer) {
closePromises.push(this.rpcServer.close());
}
if (this.grpcAPIProxy) {
closePromises.push(this.grpcAPIProxy.close());
}
if (this.swaps) {
this.swaps.close();
}
await Promise.all(closePromises);
await this.db.close();
this.logger.info('XUD shutdown gracefully');
this.emit('shutdown');
}
/**
* Initiate graceful shutdown of xud. Emits the `shutdown` event when shutdown is complete.
*/
public beginShutdown = () => {
// we begin the shutdown process but return a response before it completes.
void (this.shutdown());
}
}
if (!module.parent) {
const xud = new Xud();
void xud.start();
}
export default Xud;