All files server.js

12.21% Statements 70/573
100% Branches 1/1
3.12% Functions 1/32
12.21% Lines 70/573

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 5741x 1x                 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x                                                         1x           1x                                     1x     1x                                     1x     1x       1x     1x     1x         1x                   1x     1x         1x         1x     1x     1x           1x                                                                                               1x             1x                               1x                             1x               1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         1x                 1x         1x                 1x                     1x         1x         1x         1x 1x  
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Server = void 0;
const tls_1 = require("tls");
const crypto_1 = require("crypto");
const fs_1 = require("fs");
const path_1 = require("path");
const logger_1 = require("./logger");
const util_1 = require("util");
const helpers_1 = require("./helpers");
const network_1 = require("./network");
const address_book_1 = require("./address_book");
const client_1 = require("./client");
const cash_1 = require("./cash");
const contact_1 = require("./contact");
const overlay_1 = require("./overlay");
const VERSION = 1;
class Server extends network_1.Network {
    constructor(_config) {
        super();
        this._config = _config;
        this._shutdown = false;
        this._privateKeyDerivation = null;
        this._server = null;
        this._clients = new Map();
        this._tasks = new Map();
        this._logger = logger_1.LoggerFactory.getInstance().createLogger('server');
        this._privateKeyFilePath = (0, path_1.join)(this._config.data_dir, 'private_key.pem');
        this._publicKeyFilePath = (0, path_1.join)(this._config.data_dir, 'public_key.pem');
        this._certificateFilePath = (0, path_1.join)(this._config.data_dir, 'certificate.pem');
        this._logger.debug('certificate file path', this._certificateFilePath);
        this._addressbookFilePath = (0, path_1.join)(this._config.data_dir, 'address_book.json');
        this._logger.debug('address book file path', this._addressbookFilePath);
        this._addressbookBootstrapFilePath = (0, path_1.join)(this._config.data_dir, 'bootstrap.json');
        this._addressbook = new address_book_1.AddressBook(this._addressbookFilePath);
        this._localNode = overlay_1.Node.parse(this._config.id);
    }
    start() {
        this._logger.info('start()');
        this._logger.debug('password key derivation start');
        this._privateKeyDerivation = (0, helpers_1.passwordKeyDerivation)(process.env.FLUXCHAT_KEY_PASSWORD || 'password');
        this._logger.debug('password key derivation done');
        // Tasks
        this._tasks.set('debug_clients', setInterval(this._debugClients.bind(this), 10000));
        this._tasks.set('handle_clients', setInterval(this._handleClients.bind(this), 300));
        this._tasks.set('ping_clients', setInterval(this._pingClients.bind(this), 60000));
        this._tasks.set('save', setInterval(this.save.bind(this), 60000));
        this._tasks.set('contact_address_book', setTimeout(this._contactAddressBook.bind(this), 10000));
        // Address Book
        this._addressbook.load();
        this._addressbook.loadBootstrap(this._addressbookBootstrapFilePath);
        // TLS Server
        this._logger.info('start TLS server');
        const options = {
            key: [{
                    pem: (0, fs_1.readFileSync)(this._privateKeyFilePath),
                    passphrase: this._privateKeyDerivation,
                }],
            cert: (0, fs_1.readFileSync)(this._certificateFilePath),
        };
        this._server = (0, tls_1.createServer)(options, this._onServerConnection.bind(this));
        this._server.listen(this._config.port, this._config.address, this._onServerListen.bind(this));
        this._server.on('close', this._onServerClose.bind(this));
        this._server.on('error', this._onServerError.bind(this));
        this._server.on('drop', this._onServerDrop.bind(this));
    }
    save() {
        this._logger.info('save()');
        if (this._addressbook) {
            this._addressbook.save();
        }
    }
    shutdown(reason) {
        this._logger.info('shutdown()', reason);
        this._shutdown = true;
        this._logger.info('shutdown tasks');
        for (const [name, task] of this._tasks) {
            this._logger.debug((0, util_1.format)('task %s', name));
            clearInterval(task);
        }
        this._logger.info('shutdown clients');
        for (const [, client] of this._clients) {
            this._logger.debug((0, util_1.format)('client %s', client.uuid));
            client.socket.destroy();
        }
        if (this._server) {
            this._logger.info('shutdown TLS server');
            this._server.close();
            this._server = null;
        }
    }
    _onServerListen() {
        this._logger.debug('_onListen()');
    }
    _onServerConnection(socket) {
        this._logger.info('_onConnection()');
        this._logger.debug((0, util_1.format)('address: %s', socket.address()));
        this._logger.debug((0, util_1.format)('authorized: %s', socket.authorized));
        this._logger.debug((0, util_1.format)('authorizationError: %s', socket.authorizationError));
        this._logger.debug((0, util_1.format)('encrypted: %s', socket.encrypted));
        // this._logger.debug(f('getCipher() %s', socket.getCipher()));
        this._logger.debug((0, util_1.format)('cipher version: %s', socket.getCipher().version));
        this._logger.debug((0, util_1.format)('remoteAddress: %s:%d', socket.remoteAddress, socket.remotePort));
        this._logger.debug((0, util_1.format)('localAddress: %s:%d', socket.localAddress, socket.localPort));
        const client = new client_1.Client();
        const connectedClient = client;
        client.connMode = client_1.ConnectionMode.Connected;
        client.connMsg = 'connected, incoming';
        client.dirMode = client_1.Direction.Inbound;
        client.socket = socket;
        this._clientBindEvents(connectedClient);
        this._clients.set(client.uuid, connectedClient);
    }
    _onServerClose() {
        this._logger.debug('_onServerClose()');
    }
    _onServerError(error) {
        this._logger.error((0, util_1.format)('_onServerError() %s', error.message));
        this.shutdown(error.message);
    }
    _onServerDrop(socket) {
        this._logger.debug((0, util_1.format)('_onServerDrop(%s) %s:%d', typeof socket, socket.remoteAddress, socket.remotePort));
    }
    _onClientConnect(client) {
        this._logger.debug((0, util_1.format)('_onClientConnect(%s)', client.uuid));
    }
    _onClientReady(client) {
        this._logger.debug((0, util_1.format)('_onClientReady(%s)', client));
        client.connMode = client_1.ConnectionMode.Connected;
        client.connMsg = 'connected, outgoing';
    }
    _onClientData(client, data) {
        this._logger.debug((0, util_1.format)('_onClientData(%s)', client));
        this._logger.debug((0, util_1.format)('data: %d', data.length));
        this._logger.debug((0, util_1.format)('data: %d', data.length));
        const commands = this._parseRaw(data);
        for (const command of commands) {
            this._logger.debug((0, util_1.format)('command: %s', command));
            this._clientHandleCommand(client, command);
        }
    }
    _onClientData2(client, data) {
        this._logger.debug((0, util_1.format)('_onClientData2(%s)', client));
    }
    _onClientEnd(client) {
        this._logger.debug((0, util_1.format)('_onClientEnd(%s)', client));
        this._clients.delete(client.uuid);
        client.reset();
    }
    _onClientClose(client, hadError) {
        this._logger.debug((0, util_1.format)('_onClientClose(%s, %s)', client, hadError));
        this._clients.delete(client.uuid);
        client.reset();
    }
    _onClientError(client, error) {
        this._logger.error((0, util_1.format)('_onClientError(%s, %s)', client, error.message));
    }
    _onClientTimeout(client, socket) {
        this._logger.warn((0, util_1.format)('_onClientTimeout(%s, %s)', client, typeof socket));
    }
    _debugClients() {
        this._logger.info((0, util_1.format)('_debugClients() -> %d', this._clients.size));
        for (const [c_uuid, client] of this._clients) {
            this._logger.debug((0, util_1.format)('debug client %s: %d %s', c_uuid, client.auth, client.connMsg));
        }
    }
    _handleClients() {
        // this._logger.info('_handleClients()');
        var _a;
        for (const [c_uuid, client] of this._clients) {
            // this._logger.debug(f('handle client %s', c_uuid));
            switch (client.connMode) {
                case client_1.ConnectionMode.Disconnected:
                    this._logger.debug((0, util_1.format)('handle client %s, disconnected: %s', c_uuid, client.connMsg));
                    this._clients.delete(client.uuid);
                    (_a = client.socket) === null || _a === void 0 ? void 0 : _a.destroy();
                    client.reset();
                    break;
                case client_1.ConnectionMode.Connecting:
                    this._logger.debug((0, util_1.format)('handle client %s, connecting', c_uuid));
                    break;
                case client_1.ConnectionMode.Connected:
                    this._logger.debug((0, util_1.format)('handle client, auth: %d', client.auth));
                    if ((client.auth & client_1.AuthLevel.SentChallenge) == 0) {
                        this._logger.debug((0, util_1.format)('send CHALLENGE to client %s', c_uuid));
                        const challenge = (0, crypto_1.randomUUID)();
                        const challenge_b = Buffer.from(challenge, 'utf8');
                        client.cash = new cash_1.Cash(challenge_b, this._config.challenge.min);
                        client.auth |= client_1.AuthLevel.SentChallenge;
                        this._logger.debug((0, util_1.format)('client auth: %d', client.auth));
                        this._clientSendChallenge(client, challenge);
                    }
                    else if ((client.auth & client_1.AuthLevel.ReceivedChallenge) != 0 && (client.auth & client_1.AuthLevel.SentId) == 0) {
                        this._logger.debug((0, util_1.format)('send ID to client %s', c_uuid));
                        client.auth |= client_1.AuthLevel.SentId;
                        this._logger.debug((0, util_1.format)('client auth: %d', client.auth));
                        if (client.challenge.proof !== null && client.challenge.nonce !== null) {
                            this._clientSendId(client, client.challenge.proof, client.challenge.nonce);
                        }
                    }
                    else if (client.auth == client_1.AuthLevel.Authenticated) {
                        this._logger.debug((0, util_1.format)('client %s, authenticated', c_uuid));
                        client.connMode = client_1.ConnectionMode.Authenticated;
                    }
                    // TODO: check for timeout
                    break;
                case client_1.ConnectionMode.Authenticated:
                    // this._logger.debug(f('handle client %s, authenticated', c_uuid));
                    break;
                default:
                    this._logger.warn((0, util_1.format)('handle client %s, unknown connection mode %d', c_uuid, client.connMode));
            }
        }
    }
    _pingClients() {
        this._logger.info('_pingClients()');
        for (const [c_uuid, client] of this._clients) {
            this._logger.debug((0, util_1.format)('client %s', c_uuid));
            this._clientSendPing(client);
        }
    }
    _contactAddressBook() {
        this._logger.info('_contactAddressBook()');
        this._logger.info('getAll()');
        const _entries = this._addressbook.getAll();
        this._logger.debug((0, util_1.format)('entries %s', _entries.size));
        this._addressbook.getAll().forEach((client) => {
            this._logger.debug((0, util_1.format)('client %s', client.uuid));
            if (!client.hasContact()) {
                return;
            }
            if (!client.socket) {
                this._logger.debug((0, util_1.format)('client %s, socket is null', client.uuid));
                this._clientConnect(client);
            }
        });
    }
    _clientConnect(client) {
        this._logger.info((0, util_1.format)('_clientConnect(%s) -> %s:%s', client, client.address, client.port));
        const options = {
            host: client.address,
            port: client.port,
            rejectUnauthorized: false,
        };
        const connectedClient = client;
        client.connMode = client_1.ConnectionMode.Connecting;
        client.connMsg = 'connecting, outgoing';
        client.dirMode = client_1.Direction.Outbound;
        client.socket = (0, tls_1.connect)(options, this._onClientConnect.bind(this, client));
        this._clientBindEvents(connectedClient);
        this._clients.set(client.uuid, connectedClient);
    }
    _clientBindEvents(client) {
        client.socket.on('ready', this._onClientReady.bind(this, client));
        client.socket.on('data', this._onClientData.bind(this, client));
        client.socket.on('end', this._onClientEnd.bind(this, client));
        client.socket.on('close', this._onClientClose.bind(this, client));
        client.socket.on('error', this._onClientError.bind(this, client));
        client.socket.on('timeout', this._onClientTimeout.bind(this, client));
    }
    _clientHandleCommand(client, command) {
        return __awaiter(this, void 0, void 0, function* () {
            this._logger.debug((0, util_1.format)('_clientHandleCommand(%s, %s)', client, command));
            //ConnectionMode.Authenticated
            if (command.group >= 2 && client.auth != client_1.AuthLevel.Authenticated) {
                this._logger.warn((0, util_1.format)('client %s not authenticated: %d', client.uuid, client.auth));
                client.connMode = client_1.ConnectionMode.Disconnected;
                client.connMsg = 'not authenticated';
                return;
            }
            switch (command.group) {
                case 0: // Basic
                    switch (command.command) {
                        case 0: // OK
                            this._logger.debug((0, util_1.format)('OK command'));
                            break;
                        default:
                            this._logger.warn((0, util_1.format)('unknown command %d:%d', command.group, command.command));
                            break;
                    }
                    break;
                case 1: // Connection, Authentication, etc
                    switch (command.command) {
                        case 1: // CHALLENGE command
                            this._logger.debug((0, util_1.format)('CHALLENGE command: %s', command.args.toString()));
                            if ((client.auth & client_1.AuthLevel.ReceivedChallenge) != 0) {
                                this._logger.warn((0, util_1.format)('client %s already authenticated', client.uuid));
                                break;
                            }
                            client.auth |= client_1.AuthLevel.ReceivedChallenge;
                            this._logger.debug((0, util_1.format)('client auth: %d', client.auth));
                            client.challenge.min = command.asInt(0);
                            client.challenge.max = command.asInt(1);
                            client.challenge.data = command.asString(2);
                            if (client.challenge.data.length > 36) {
                                this._logger.warn((0, util_1.format)('client %s challenge data too long', client.uuid));
                                client.connMode = client_1.ConnectionMode.Disconnected;
                                client.connMsg = 'challenge data too long';
                                break;
                            }
                            if (client.challenge.min > this._config.challenge.max) {
                                this._logger.warn((0, util_1.format)('client %s challenge min too long: %d > %d', client.uuid, client.challenge.min, this._config.challenge.max));
                                client.connMode = client_1.ConnectionMode.Disconnected;
                                client.connMsg = 'challenge min is too big';
                            }
                            const challengeData = Buffer.from(client.challenge.data);
                            const cash = new cash_1.Cash(challengeData, client.challenge.min);
                            this._logger.debug((0, util_1.format)('mine cash: %s', cash));
                            const cycles = cash.mine();
                            this._logger.debug((0, util_1.format)('mine done: %d', cycles));
                            client.challenge.proof = cash.proof;
                            client.challenge.nonce = cash.nonce;
                            this._logger.debug((0, util_1.format)('cash.min: %s', client.challenge.min));
                            this._logger.debug((0, util_1.format)('cash.max: %s', client.challenge.max));
                            this._logger.debug((0, util_1.format)('cash.data: %s', client.challenge.data));
                            this._logger.debug((0, util_1.format)('cash.proof: %s', cash.proof));
                            this._logger.debug((0, util_1.format)('cash.nonce: %s', cash.nonce));
                            break;
                        case 2: // ID command
                            this._logger.debug((0, util_1.format)('ID command'));
                            if ((client.auth & client_1.AuthLevel.ReceivedChallenge) == 0) {
                                this._logger.warn((0, util_1.format)('client %s not received challenge', client.uuid));
                                break;
                            }
                            if ((client.auth & client_1.AuthLevel.ReceivedId) != 0) {
                                this._logger.warn((0, util_1.format)('client %s already authenticated', client.uuid));
                                break;
                            }
                            const cVersion = command.asInt(0);
                            const cId = command.asString(1);
                            const cContact = command.asString(2);
                            const cProof = command.asString(3);
                            const cNonce = command.asInt(4);
                            this._logger.debug((0, util_1.format)('client version: %s', cVersion));
                            this._logger.debug((0, util_1.format)('client id: %s', cId));
                            this._logger.debug((0, util_1.format)('client contact: %s', cContact));
                            this._logger.debug((0, util_1.format)('client proof: %s', cProof));
                            this._logger.debug((0, util_1.format)('client nonce: %s', cNonce));
                            // Local
                            if (this._localNode.equals(cId)) {
                                this._logger.warn((0, util_1.format)('client %s is local node', client.uuid));
                                client.connMode = client_1.ConnectionMode.Disconnected;
                                client.connMsg = 'client is local node';
                                break;
                            }
                            // Version
                            if (VERSION != cVersion) {
                                this._logger.warn((0, util_1.format)('client %s version mismatch: %s != %s', client.uuid, VERSION, cVersion));
                                client.connMode = client_1.ConnectionMode.Disconnected;
                                client.connMsg = 'version mismatch';
                                break;
                            }
                            // Challenge
                            if (client.cash === null) {
                                this._logger.warn((0, util_1.format)('client %s cash is null', client.uuid));
                                client.connMode = client_1.ConnectionMode.Disconnected;
                                client.connMsg = 'cash is null';
                                break;
                            }
                            this._logger.debug('cash.verify start');
                            const verified = client.cash.verify(cProof, cNonce);
                            this._logger.debug('cash.verify end');
                            if (!verified) {
                                this._logger.warn((0, util_1.format)('client %s cash verify failed', client.uuid));
                                client.connMode = client_1.ConnectionMode.Disconnected;
                                client.connMsg = 'cash verify failed';
                                break;
                            }
                            // Contact
                            const peerAddrInfo = client.socket.address();
                            const contact = yield contact_1.Contact.resolve(cContact, peerAddrInfo.address);
                            let cSwitch = false;
                            let _client = null;
                            switch (client.dirMode) {
                                case client_1.Direction.Inbound:
                                    // Client is incoming
                                    this._logger.debug((0, util_1.format)('client %s, inbound', client.uuid));
                                    if (contact.is_valid) {
                                        // Client sent contact info
                                        const cAddress = contact.address;
                                        const cPort = contact.port;
                                        _client = this._addressbook.getClientById(cId);
                                        if (_client === null) {
                                            this._logger.debug((0, util_1.format)('client not found by ID (A)'));
                                            _client = this._addressbook.getClientByAddrPort(cAddress, cPort);
                                            if (_client === null) {
                                                this._logger.debug((0, util_1.format)('client not found by Addr:Port (B)'));
                                                _client = new client_1.Client();
                                                _client.id = cId;
                                                _client.address = cAddress;
                                                _client.port = cPort;
                                                _client.dirMode = client.dirMode;
                                                _client.debugAdd = `id command, incoming, contact infos, not found by id, not found by addr:port, original: ${client.debugAdd}`;
                                                this._addressbook.addClient(_client);
                                            }
                                            else {
                                                this._logger.debug((0, util_1.format)('client found (B)'));
                                            }
                                        }
                                        else {
                                            this._logger.debug((0, util_1.format)('client found (A)'));
                                        }
                                        _client.address = cAddress;
                                        _client.port = cPort;
                                    }
                                    else {
                                        // Client sent no contact info
                                        _client = this._addressbook.getClientById(cId);
                                        if (_client === null) {
                                            this._logger.debug((0, util_1.format)('client not found by ID (C)'));
                                            _client = new client_1.Client();
                                            _client.id = cId;
                                            _client.dirMode = client.dirMode;
                                            _client.debugAdd = `id command, incoming, no contact infos, not found by id, original: ${client.debugAdd}`;
                                            this._addressbook.addClient(_client);
                                        }
                                        else {
                                            this._logger.debug((0, util_1.format)('client not found by ID (C)'));
                                        }
                                    }
                                    cSwitch = true;
                                    break;
                                case client_1.Direction.Outbound:
                                    // Client is outgoing
                                    this._logger.debug((0, util_1.format)('client is outgoing'));
                                    // TODO: possible wrong approach
                                    _client = client;
                                    if (contact.is_valid) {
                                        this._logger.debug((0, util_1.format)('client has contact infos'));
                                        // Client sent contact info
                                        const cAddress = contact.address;
                                        const cPort = contact.port;
                                        _client.address = cAddress;
                                        _client.port = cPort;
                                    }
                                    else {
                                        this._logger.debug('client has NO contact infos');
                                    }
                                    break;
                                default:
                                    const msg = (0, util_1.format)('client %s, unknown direction mode %d', client.uuid, client.dirMode);
                                    this._logger.error(msg);
                                    throw new Error(msg);
                            }
                            if (_client.id === undefined || _client.id === null) {
                                _client.id = cId;
                            }
                            this._logger.debug((0, util_1.format)('Client A: %s', client));
                            this._logger.debug((0, util_1.format)('Client B: %s', _client));
                            _client.refreshSeenAt();
                            _client.refreshUsedAt();
                            _client.incMeetings();
                            _client.socket = client.socket;
                            _client.connMode = client.connMode;
                            _client.auth |= client.auth | client_1.AuthLevel.ReceivedId;
                            this._logger.debug((0, util_1.format)('client auth: %d', client.auth));
                            // TODO actions
                            _client.challenge = client.challenge;
                            this._addressbook.changed();
                            if (cSwitch && !client.equals(_client)) {
                                this._logger.debug((0, util_1.format)('switch client %s', client.uuid));
                                // TODO: rebind all socket events
                                this._clients.delete(client.uuid);
                                this._clients.set(_client.uuid, _client);
                            }
                            this._clientSendOk(client);
                            this._logger.debug((0, util_1.format)('Client Z: %s', _client));
                            break;
                        case 3: // PING command
                            this._logger.debug((0, util_1.format)('PING command'));
                            this._clientSendPong(client);
                            break;
                        case 4: // PONG command
                            this._logger.debug((0, util_1.format)('PONG command'));
                            break;
                    }
                    break;
                case 2: // Overlay, Address Book, Routing, etc
                    switch (command.command) {
                        case 1: // GET_NEAREST_TO command
                            this._logger.debug((0, util_1.format)('GET_NEAREST_TO command'));
                            const cNode = overlay_1.Node.parse(command.asString(0));
                            this._logger.debug((0, util_1.format)('node: %s', cNode));
                            const clients = this._addressbook.getNearestTo(cNode, true);
                            const clientIds = clients.map((client) => {
                                return `${client.uuid}:${client.address}:${client.port}`;
                            });
                            this._clientSendGetNearestToResponse(client, clientIds);
                            break;
                        case 2: // GET_NEAREST_TO RESPONSE command
                            this._logger.debug((0, util_1.format)('GET_NEAREST_TO RESPONSE command'));
                            break;
                        case 3: // REQUEST PUBLIC KEY FOR NODE command
                            this._logger.debug((0, util_1.format)('REQUEST PUBLIC KEY FOR NODE command'));
                            break;
                        case 4: // RESPONSE PUBLIC KEY FOR NODE command
                            this._logger.debug((0, util_1.format)('RESPONSE PUBLIC KEY FOR NODE command'));
                            break;
                    }
                    break;
                case 3: // Mail
                    switch (command.command) {
                        case 1: // SEND MAIL command
                            this._logger.debug((0, util_1.format)('SEND MAIL command'));
                            break;
                    }
                    break;
                default:
                    this._logger.warn((0, util_1.format)('unknown command %d:%d', command.group, command.command));
                    break;
            }
        });
    }
    _clientSendCommand(client, command) {
        this._logger.debug((0, util_1.format)('_clientSendCommand(%s, %s)', client.uuid, command));
        const data = this._serializeCommand(command);
        // this._logger.debug(f('data', data));
        this._logger.debug((0, util_1.format)('data hex: %s', data.toString('hex')));
        // this._logger.debug(f('data str: "%s"', data.toString()));
        this._logger.debug((0, util_1.format)('write socket: %d', data.length));
        client.socket.write(data);
    }
    _clientSendOk(client) {
        this._logger.debug((0, util_1.format)('_clientSendOk(%s)', client));
        const command = new network_1.Command(0, 0);
        this._clientSendCommand(client, command);
    }
    _clientSendChallenge(client, challenge) {
        this._logger.debug((0, util_1.format)('_clientSendChallenge(%s, %s)', client, challenge));
        const command = new network_1.Command(1, 1, [
            this._config.challenge.min,
            this._config.challenge.max,
            challenge,
        ]);
        this._clientSendCommand(client, command);
    }
    _clientSendId(client, proof, nonce) {
        this._logger.debug((0, util_1.format)('_clientSendId(%s, %s, %d)', client, proof, nonce));
        const command = new network_1.Command(1, 2, [
            VERSION,
            this._config.id,
            this._config.contact,
            proof,
            nonce,
        ]);
        this._clientSendCommand(client, command);
    }
    _clientSendPing(client) {
        this._logger.debug((0, util_1.format)('_clientSendPing(%s)', client));
        const command = new network_1.Command(1, 3);
        this._clientSendCommand(client, command);
    }
    _clientSendPong(client) {
        this._logger.debug((0, util_1.format)('_clientSendPong(%s)', client));
        const command = new network_1.Command(1, 4);
        this._clientSendCommand(client, command);
    }
    _clientSendGetNearestToResponse(client, clientIds) {
        this._logger.debug((0, util_1.format)('_clientSendGetNearestTo(%s, %s)', client, clientIds));
        const command = new network_1.Command(2, 1, clientIds);
        this._clientSendCommand(client, command);
    }
}
exports.Server = Server;