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 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 | 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 477x 33x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 5027x 1902x 1902x 1877x 1877x 5027x 477x 14818x 477x 1875x 1875x 1875x 1875x 400x 477x 1250x 341x 1250x 477x 3282x 3282x 2279x 2279x 3282x 477x 2032x 2032x 2025x 2025x 2032x 477x 9095x 477x 5936x 377x 5936x 5936x 5936x 5936x 477x 477x 6x 477x 26x 477x 6x 477x 12x 12x 12x 12x 12x 12x 477x 1x 1x 477x 11774x 739x 11774x 2670x 2670x 2670x 2670x 2670x 2670x 477x 477x 477x 1434x 477x 215x 477x 477x 477x 477x 477x 477x 477x 477x 477x 1x 503x 480x 479x 479x 14236x 14x 6x 161x 1178x 1170x 25x 25x 25x 215x 887x 125x 90x 25x 90x 86x 1003x 1002x 1203x 2x 402x 606x 1050x 1050x 4776x 406x 4776x 442x 47x 4729x 182x 16x 4713x 4181x 3507x 1206x 477x 3082x 3082x 3082x 23x 23x 3059x 3059x 8x 8x 477x 3051x 3051x 3051x 880x 880x 880x 880x 2171x 2171x 2171x 2171x 2171x 2171x 2171x 2171x 2171x 2171x 2171x 2171x 84x 84x 84x 2087x 2087x 2032x 55x 55x 2032x 403x 1629x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 7377x 7377x 406x 406x 477x 477x 477x 1875x 400x 400x 1475x 1902x 1902x 1902x 1902x 1902x 1902x 1902x 11880x 11876x 1902x 1877x 14x 8x 14x 8x 14x 14x 477x 477x 93x 91x 93x 478x 1x 477x 477x 477x 477x 477x 477x 478x 1x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x 477x | /* * Copyright © 2019 Lisk Foundation * * See the LICENSE file at the top-level directory of this distribution * for licensing information. * * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, * no part of this software, including this file, may be copied, modified, * propagated, or distributed except according to the terms contained in the * LICENSE file. * * Removal or modification of this copyright notice is prohibited. * */ import { getRandomBytes } from '@liskhq/lisk-cryptography'; import { EventEmitter } from 'events'; import * as http from 'http'; // tslint:disable-next-line no-require-imports import { attach, SCServer, SCServerSocket } from 'socketcluster-server'; import * as url from 'url'; import { ConnectionKind, DEFAULT_BAN_TIME, DEFAULT_FALLBACK_SEED_PEER_DISCOVERY_INTERVAL, DEFAULT_HTTP_PATH, DEFAULT_MAX_INBOUND_CONNECTIONS, DEFAULT_MAX_OUTBOUND_CONNECTIONS, DEFAULT_MAX_PEER_DISCOVERY_RESPONSE_LENGTH, DEFAULT_MAX_PEER_INFO_SIZE, DEFAULT_MIN_PEER_DISCOVERY_THRESHOLD, DEFAULT_MIN_TRIED_PEER_COUNT, DEFAULT_NODE_HOST_IP, DEFAULT_NONCE_LENGTH_BYTES, DEFAULT_OUTBOUND_SHUFFLE_INTERVAL, DEFAULT_PEER_PROTECTION_FOR_LATENCY, DEFAULT_PEER_PROTECTION_FOR_LONGEVITY, DEFAULT_PEER_PROTECTION_FOR_NETGROUP, DEFAULT_PEER_PROTECTION_FOR_USEFULNESS, DEFAULT_POPULATOR_INTERVAL, DEFAULT_RANDOM_SECRET, DEFAULT_RATE_CALCULATION_INTERVAL, DEFAULT_SEND_PEER_LIMIT, DEFAULT_WS_MAX_MESSAGE_RATE, DEFAULT_WS_MAX_MESSAGE_RATE_PENALTY, DEFAULT_WS_MAX_PAYLOAD, DUPLICATE_CONNECTION, DUPLICATE_CONNECTION_REASON, FORBIDDEN_CONNECTION, FORBIDDEN_CONNECTION_REASON, INCOMPATIBLE_PEER_CODE, INCOMPATIBLE_PEER_INFO_CODE, INCOMPATIBLE_PEER_UNKNOWN_REASON, INVALID_CONNECTION_QUERY_CODE, INVALID_CONNECTION_QUERY_REASON, INVALID_CONNECTION_SELF_CODE, INVALID_CONNECTION_SELF_REASON, INVALID_CONNECTION_URL_CODE, INVALID_CONNECTION_URL_REASON, PeerKind, } from './constants'; import { PeerInboundHandshakeError } from './errors'; import { EVENT_BAN_PEER, EVENT_CLOSE_INBOUND, EVENT_CLOSE_OUTBOUND, EVENT_CONNECT_ABORT_OUTBOUND, EVENT_CONNECT_OUTBOUND, EVENT_DISCOVERED_PEER, EVENT_FAILED_PEER_INFO_UPDATE, EVENT_FAILED_TO_ADD_INBOUND_PEER, EVENT_FAILED_TO_COLLECT_PEER_DETAILS_ON_CONNECT, EVENT_FAILED_TO_FETCH_PEER_INFO, EVENT_FAILED_TO_FETCH_PEERS, EVENT_FAILED_TO_PUSH_NODE_INFO, EVENT_FAILED_TO_SEND_MESSAGE, EVENT_INBOUND_SOCKET_ERROR, EVENT_MESSAGE_RECEIVED, EVENT_NETWORK_READY, EVENT_NEW_INBOUND_PEER, EVENT_OUTBOUND_SOCKET_ERROR, EVENT_REMOVE_PEER, EVENT_REQUEST_RECEIVED, EVENT_UNBAN_PEER, EVENT_UPDATED_PEER_INFO, REMOTE_EVENT_RPC_GET_NODE_INFO, REMOTE_EVENT_RPC_GET_PEERS_LIST, } from './events'; import { P2PRequest } from './p2p_request'; import { P2PCheckPeerCompatibility, P2PClosePacket, P2PConfig, P2PInternalState, P2PMessagePacket, P2PNodeInfo, P2PPeerInfo, P2PPenalty, P2PRequestPacket, P2PResponsePacket, PeerLists, ProtocolPeerInfo, } from './p2p_types'; import { PeerBook } from './peer_book'; import { PeerPool, PeerPoolConfig } from './peer_pool'; import { assignInternalInfo, constructPeerId, getByteSize, sanitizeInitialPeerInfo, sanitizePeerLists, selectPeersForConnection, selectPeersForRequest, selectPeersForSend, validateNodeInfo, validatePeerCompatibility, validatePeerInfo, } from './utils'; interface SCServerUpdated extends SCServer { readonly isReady: boolean; } const BASE_10_RADIX = 10; const createPeerPoolConfig = ( config: P2PConfig, peerLists: PeerLists, ): PeerPoolConfig => ({ connectTimeout: config.connectTimeout, ackTimeout: config.ackTimeout, wsMaxPayload: config.wsMaxPayload ? config.wsMaxPayload : DEFAULT_WS_MAX_PAYLOAD, peerSelectionForSend: config.peerSelectionForSend ? config.peerSelectionForSend : selectPeersForSend, peerSelectionForRequest: config.peerSelectionForRequest ? config.peerSelectionForRequest : selectPeersForRequest, peerSelectionForConnection: config.peerSelectionForConnection ? config.peerSelectionForConnection : selectPeersForConnection, sendPeerLimit: config.sendPeerLimit === undefined ? DEFAULT_SEND_PEER_LIMIT : config.sendPeerLimit, peerBanTime: config.peerBanTime ? config.peerBanTime : DEFAULT_BAN_TIME, maxOutboundConnections: config.maxOutboundConnections === undefined ? DEFAULT_MAX_OUTBOUND_CONNECTIONS : config.maxOutboundConnections, maxInboundConnections: config.maxInboundConnections === undefined ? DEFAULT_MAX_INBOUND_CONNECTIONS : config.maxInboundConnections, maxPeerDiscoveryResponseLength: config.maxPeerDiscoveryResponseLength === undefined ? DEFAULT_MAX_PEER_DISCOVERY_RESPONSE_LENGTH : config.maxPeerDiscoveryResponseLength, maxPeerInfoSize: config.maxPeerInfoSize ? config.maxPeerInfoSize : DEFAULT_MAX_PEER_INFO_SIZE, outboundShuffleInterval: config.outboundShuffleInterval ? config.outboundShuffleInterval : DEFAULT_OUTBOUND_SHUFFLE_INTERVAL, netgroupProtectionRatio: typeof config.netgroupProtectionRatio === 'number' ? config.netgroupProtectionRatio : DEFAULT_PEER_PROTECTION_FOR_NETGROUP, latencyProtectionRatio: typeof config.latencyProtectionRatio === 'number' ? config.latencyProtectionRatio : DEFAULT_PEER_PROTECTION_FOR_LATENCY, productivityProtectionRatio: typeof config.productivityProtectionRatio === 'number' ? config.productivityProtectionRatio : DEFAULT_PEER_PROTECTION_FOR_USEFULNESS, longevityProtectionRatio: typeof config.longevityProtectionRatio === 'number' ? config.longevityProtectionRatio : DEFAULT_PEER_PROTECTION_FOR_LONGEVITY, wsMaxMessageRate: typeof config.wsMaxMessageRate === 'number' ? config.wsMaxMessageRate : DEFAULT_WS_MAX_MESSAGE_RATE, wsMaxMessageRatePenalty: typeof config.wsMaxMessageRatePenalty === 'number' ? config.wsMaxMessageRatePenalty : DEFAULT_WS_MAX_MESSAGE_RATE_PENALTY, rateCalculationInterval: typeof config.rateCalculationInterval === 'number' ? config.rateCalculationInterval : DEFAULT_RATE_CALCULATION_INTERVAL, secret: config.secret ? config.secret : DEFAULT_RANDOM_SECRET, peerLists, }); export class P2P extends EventEmitter { private readonly _config: P2PConfig; private readonly _sanitizedPeerLists: PeerLists; private readonly _httpServer: http.Server; private _isActive: boolean; private _hasConnected: boolean; private readonly _peerBook: PeerBook; private readonly _bannedPeers: Set<string>; private readonly _populatorInterval: number; private _nextSeedPeerDiscovery: number; private readonly _fallbackSeedPeerDiscoveryInterval: number; private _populatorIntervalId: NodeJS.Timer | undefined; private _nodeInfo: P2PNodeInfo; private readonly _peerPool: PeerPool; private readonly _scServer: SCServerUpdated; private readonly _secret: number; private readonly _handlePeerPoolRPC: (request: P2PRequest) => void; private readonly _handlePeerPoolMessage: (message: P2PMessagePacket) => void; private readonly _handleDiscoveredPeer: (peerInfo: P2PPeerInfo) => void; private readonly _handleFailedToPushNodeInfo: (error: Error) => void; private readonly _handleFailedToSendMessage: (error: Error) => void; private readonly _handleOutboundPeerConnect: (peerInfo: P2PPeerInfo) => void; private readonly _handleOutboundPeerConnectAbort: ( peerInfo: P2PPeerInfo, ) => void; private readonly _handlePeerCloseOutbound: ( closePacket: P2PClosePacket, ) => void; private readonly _handlePeerCloseInbound: ( closePacket: P2PClosePacket, ) => void; private readonly _handleRemovePeer: (peerId: string) => void; private readonly _handlePeerInfoUpdate: (peerInfo: P2PPeerInfo) => void; private readonly _handleFailedToFetchPeerInfo: (error: Error) => void; private readonly _handleFailedToFetchPeers: (error: Error) => void; private readonly _handleFailedPeerInfoUpdate: (error: Error) => void; private readonly _handleFailedToCollectPeerDetails: (error: Error) => void; private readonly _handleBanPeer: (peerId: string) => void; private readonly _handleUnbanPeer: (peerId: string) => void; private readonly _handleOutboundSocketError: (error: Error) => void; private readonly _handleInboundSocketError: (error: Error) => void; private readonly _peerHandshakeCheck: P2PCheckPeerCompatibility; public constructor(config: P2PConfig) { super(); this._secret = config.secret ? config.secret : DEFAULT_RANDOM_SECRET; this._sanitizedPeerLists = sanitizePeerLists( { seedPeers: config.seedPeers ? config.seedPeers.map(sanitizeInitialPeerInfo) : [], blacklistedIPs: config.blacklistedIPs ? config.blacklistedIPs : [], fixedPeers: config.fixedPeers ? config.fixedPeers.map(sanitizeInitialPeerInfo) : [], whitelisted: config.whitelistedPeers ? config.whitelistedPeers.map(sanitizeInitialPeerInfo) : [], previousPeers: config.previousPeers ? config.previousPeers.map(sanitizeInitialPeerInfo) : [], }, { peerId: constructPeerId( config.hostIp || DEFAULT_NODE_HOST_IP, config.nodeInfo.wsPort, ), ipAddress: config.hostIp || DEFAULT_NODE_HOST_IP, wsPort: config.nodeInfo.wsPort, }, this._secret, ); this._config = config; this._isActive = false; this._hasConnected = false; this._peerBook = new PeerBook({ secret: this._secret, }); this._initializePeerBook(); this._bannedPeers = new Set(); this._httpServer = http.createServer(); this._scServer = attach(this._httpServer, { path: DEFAULT_HTTP_PATH, wsEngineServerOptions: { maxPayload: config.wsMaxPayload ? config.wsMaxPayload : DEFAULT_WS_MAX_PAYLOAD, }, }) as SCServerUpdated; // This needs to be an arrow function so that it can be used as a listener. this._handlePeerPoolRPC = (request: P2PRequest) => { // Process protocol messages switch (request.procedure) { case REMOTE_EVENT_RPC_GET_PEERS_LIST: this._handleGetPeersRequest(request); break; case REMOTE_EVENT_RPC_GET_NODE_INFO: this._handleGetNodeInfo(request); break; default: } // Re-emit the request for external use. this.emit(EVENT_REQUEST_RECEIVED, request); }; // This needs to be an arrow function so that it can be used as a listener. this._handlePeerPoolMessage = (message: P2PMessagePacket) => { // Re-emit the message for external use. this.emit(EVENT_MESSAGE_RECEIVED, message); }; this._handleOutboundPeerConnect = (peerInfo: P2PPeerInfo) => { Iif (!this._peerBook.hasPeer(peerInfo)) { this._peerBook.addPeer(this._assignPeerKind(peerInfo)); } this._peerBook.upgradePeer(peerInfo); // Re-emit the message to allow it to bubble up the class hierarchy. this.emit(EVENT_CONNECT_OUTBOUND, peerInfo); if (this._isNetworkReady()) { this.emit(EVENT_NETWORK_READY); } }; this._handleOutboundPeerConnectAbort = (peerInfo: P2PPeerInfo) => { if ( this._peerBook.hasPeer(peerInfo) && (peerInfo.internalState as P2PInternalState).peerKind !== PeerKind.WHITELISTED_PEER ) { this._peerBook.downgradePeer(peerInfo); } // Re-emit the message to allow it to bubble up the class hierarchy. this.emit(EVENT_CONNECT_ABORT_OUTBOUND, peerInfo); }; this._handlePeerCloseOutbound = (closePacket: P2PClosePacket) => { const { peerInfo } = closePacket; // Update connection kind when closing connection if (this._peerBook.getPeer(closePacket.peerInfo)) { const updatedPeer = { ...peerInfo, internalState: assignInternalInfo(peerInfo, this._secret), }; this._peerBook.updatePeer(updatedPeer); } // Re-emit the message to allow it to bubble up the class hierarchy. this.emit(EVENT_CLOSE_OUTBOUND, closePacket); }; this._handlePeerCloseInbound = (closePacket: P2PClosePacket) => { const { peerInfo } = closePacket; // Update connection kind when closing connection if (this._peerBook.getPeer(closePacket.peerInfo)) { const updatedPeer = { ...peerInfo, internalState: assignInternalInfo(peerInfo, this._secret), }; this._peerBook.updatePeer(updatedPeer); } // Re-emit the message to allow it to bubble up the class hierarchy. this.emit(EVENT_CLOSE_INBOUND, closePacket); }; this._handleRemovePeer = (peerId: string) => { // Re-emit the message to allow it to bubble up the class hierarchy. this.emit(EVENT_REMOVE_PEER, peerId); }; this._handlePeerInfoUpdate = (peerInfo: P2PPeerInfo) => { if (!this._peerBook.hasPeer(peerInfo)) { this._peerBook.addPeer(this._assignPeerKind(peerInfo)); } const isUpdated = this._peerBook.updatePeer(peerInfo); Eif (isUpdated) { // If found and updated successfully then upgrade the peer this._peerBook.upgradePeer(peerInfo); // Re-emit the message to allow it to bubble up the class hierarchy. this.emit(EVENT_UPDATED_PEER_INFO, peerInfo); } }; this._handleFailedPeerInfoUpdate = (error: Error) => { // Re-emit the message to allow it to bubble up the class hierarchy. this.emit(EVENT_FAILED_PEER_INFO_UPDATE, error); }; this._handleFailedToFetchPeerInfo = (error: Error) => { // Re-emit the message to allow it to bubble up the class hierarchy. this.emit(EVENT_FAILED_TO_FETCH_PEER_INFO, error); }; this._handleFailedToFetchPeers = (error: Error) => { // Re-emit the message to allow it to bubble up the class hierarchy. this.emit(EVENT_FAILED_TO_FETCH_PEERS, error); }; this._handleFailedToCollectPeerDetails = (error: Error) => { // Re-emit the message to allow it to bubble up the class hierarchy. this.emit(EVENT_FAILED_TO_COLLECT_PEER_DETAILS_ON_CONNECT, error); }; this._handleBanPeer = (peerId: string) => { this._bannedPeers.add(peerId.split(':')[0]); const isWhitelisted = this._sanitizedPeerLists.whitelisted.find( peer => peer.peerId === peerId, ); const bannedPeerInfo = { ipAddress: peerId.split(':')[0], wsPort: +peerId.split(':')[1], }; Eif ( this._peerBook.hasPeer({ ipAddress: bannedPeerInfo.ipAddress, wsPort: bannedPeerInfo.wsPort, peerId, }) && !isWhitelisted ) { this._peerBook.removePeer({ ipAddress: bannedPeerInfo.ipAddress, wsPort: bannedPeerInfo.wsPort, peerId, }); } // Re-emit the message to allow it to bubble up the class hierarchy. this.emit(EVENT_BAN_PEER, peerId); }; this._handleUnbanPeer = (peerId: string) => { this._bannedPeers.delete(peerId.split(':')[0]); // Re-emit the message to allow it to bubble up the class hierarchy. this.emit(EVENT_UNBAN_PEER, peerId); }; // When peer is fetched for status after connection then update the peerinfo in triedPeer list this._handleDiscoveredPeer = (detailedPeerInfo: P2PPeerInfo) => { // Check blacklist to avoid incoming connections from blacklisted ips const isBlacklisted = this._sanitizedPeerLists.blacklistedIPs.find( blacklistedIP => blacklistedIP === detailedPeerInfo.ipAddress, ); if (!this._peerBook.hasPeer(detailedPeerInfo) && !isBlacklisted) { this._peerBook.addPeer(this._assignPeerKind(detailedPeerInfo)); // Re-emit the message to allow it to bubble up the class hierarchy. // Only emit event when a peer is discovered for the first time. this.emit(EVENT_DISCOVERED_PEER, detailedPeerInfo); Eif (!this._peerPool.hasPeer(detailedPeerInfo.peerId)) { const isUpdated = this._peerBook.updatePeer(detailedPeerInfo); Eif (isUpdated) { // If found and updated successfully then upgrade the peer this._peerBook.upgradePeer(detailedPeerInfo); } } } }; this._handleFailedToPushNodeInfo = (error: Error) => { // Re-emit the error to allow it to bubble up the class hierarchy. this.emit(EVENT_FAILED_TO_PUSH_NODE_INFO, error); }; this._handleFailedToSendMessage = (error: Error) => { // Re-emit the error to allow it to bubble up the class hierarchy. this.emit(EVENT_FAILED_TO_SEND_MESSAGE, error); }; this._handleOutboundSocketError = (error: Error) => { // Re-emit the error to allow it to bubble up the class hierarchy. this.emit(EVENT_OUTBOUND_SOCKET_ERROR, error); }; this._handleInboundSocketError = (error: Error) => { // Re-emit the error to allow it to bubble up the class hierarchy. this.emit(EVENT_INBOUND_SOCKET_ERROR, error); }; const peerPoolConfig = createPeerPoolConfig( config, this._sanitizedPeerLists, ); this._peerPool = new PeerPool(peerPoolConfig); this._bindHandlersToPeerPool(this._peerPool); this._nodeInfo = { ...config.nodeInfo, nonce: getRandomBytes(DEFAULT_NONCE_LENGTH_BYTES).toString('hex'), }; this.applyNodeInfo(this._nodeInfo); this._populatorInterval = config.populatorInterval ? config.populatorInterval : DEFAULT_POPULATOR_INTERVAL; this._fallbackSeedPeerDiscoveryInterval = config.fallbackSeedPeerDiscoveryInterval ? config.fallbackSeedPeerDiscoveryInterval : DEFAULT_FALLBACK_SEED_PEER_DISCOVERY_INTERVAL; this._nextSeedPeerDiscovery = Date.now() + this._fallbackSeedPeerDiscoveryInterval; this._peerHandshakeCheck = config.peerHandshakeCheck ? config.peerHandshakeCheck : validatePeerCompatibility; } public get config(): P2PConfig { return this._config; } public get isActive(): boolean { return this._isActive; } /** * This is not a declared as a setter because this method will need * invoke an async RPC on Peers to give them our new node status. */ public applyNodeInfo(nodeInfo: P2PNodeInfo): void { validateNodeInfo( nodeInfo, this._config.maxPeerInfoSize ? this._config.maxPeerInfoSize : DEFAULT_MAX_PEER_INFO_SIZE, ); this._nodeInfo = { ...nodeInfo, nonce: this.nodeInfo.nonce, }; this._peerPool.applyNodeInfo(this._nodeInfo); } public get nodeInfo(): P2PNodeInfo { return this._nodeInfo; } public applyPenalty(peerPenalty: P2PPenalty): void { if (!this._isTrustedPeer(peerPenalty.peerId)) { this._peerPool.applyPenalty(peerPenalty); } } public getTriedPeers(): ReadonlyArray<ProtocolPeerInfo> { return this._peerBook.triedPeers.map(peer => ({ ...peer.sharedState, ipAddress: peer.ipAddress, wsPort: peer.wsPort, })); } // Make sure you always share shared peer state to a user public getConnectedPeers(): ReadonlyArray<ProtocolPeerInfo> { // Only share the shared state to the user return this._peerPool .getAllConnectedPeerInfos() .filter( peer => !(peer.internalState && !peer.internalState.advertiseAddress), ) .map(peer => ({ ...peer.sharedState, ipAddress: peer.ipAddress, wsPort: peer.wsPort, peerId: peer.peerId, })); } // Make sure you always share shared peer state to a user public getDisconnectedPeers(): ReadonlyArray<ProtocolPeerInfo> { const allPeers = this._peerBook.allPeers; const connectedPeers = this.getConnectedPeers(); const disconnectedPeers = allPeers.filter(peer => { if ( connectedPeers.find( connectedPeer => peer.peerId === (connectedPeer.peerId as string), ) ) { return false; } return true; }); // Only share the shared state to the user and remove private peers return disconnectedPeers .filter( peer => !(peer.internalState && !peer.internalState.advertiseAddress), ) .map(peer => ({ ...peer.sharedState, ipAddress: peer.ipAddress, wsPort: peer.wsPort, peerId: peer.peerId, })); } public async request(packet: P2PRequestPacket): Promise<P2PResponsePacket> { const response = await this._peerPool.request(packet); return response; } public send(message: P2PMessagePacket): void { this._peerPool.send(message); } public broadcast(message: P2PMessagePacket): void { this._peerPool.broadcast(message); } public async requestFromPeer( packet: P2PRequestPacket, peerId: string, ): Promise<P2PResponsePacket> { return this._peerPool.requestFromPeer(packet, peerId); } public sendToPeer(message: P2PMessagePacket, peerId: string): void { this._peerPool.sendToPeer(message, peerId); } private _disconnectSocketDueToFailedHandshake( socket: SCServerSocket, statusCode: number, closeReason: string, ): void { socket.disconnect(statusCode, closeReason); this.emit( EVENT_FAILED_TO_ADD_INBOUND_PEER, new PeerInboundHandshakeError( closeReason, statusCode, socket.remoteAddress, socket.request.url, ), ); } private _assignPeerKind(peerInfo: P2PPeerInfo): P2PPeerInfo { Iif ( this._sanitizedPeerLists.blacklistedIPs.find( blacklistedIP => blacklistedIP === peerInfo.ipAddress, ) ) { return { ...peerInfo, internalState: { ...assignInternalInfo(peerInfo, this._secret), peerKind: PeerKind.BLACKLISTED_PEER, }, }; } if ( this._sanitizedPeerLists.fixedPeers.find( peer => peer.ipAddress === peerInfo.ipAddress, ) ) { return { ...peerInfo, internalState: { ...assignInternalInfo(peerInfo, this._secret), peerKind: PeerKind.FIXED_PEER, }, }; } if ( this._sanitizedPeerLists.whitelisted.find( peer => peer.ipAddress === peerInfo.ipAddress, ) ) { return { ...peerInfo, internalState: { ...assignInternalInfo(peerInfo, this._secret), peerKind: PeerKind.WHITELISTED_PEER, }, }; } if ( this._sanitizedPeerLists.seedPeers.find( peer => peer.ipAddress === peerInfo.ipAddress, ) ) { return { ...peerInfo, internalState: { ...assignInternalInfo(peerInfo, this._secret), peerKind: PeerKind.SEED_PEER, }, }; } return { ...peerInfo, internalState: { ...assignInternalInfo(peerInfo, this._secret), peerKind: PeerKind.NONE, }, }; } private async _startPeerServer(): Promise<void> { this._scServer.on('handshake', (socket: SCServerSocket): void => { // Terminate the connection the moment it receive ping frame (socket as any).socket.on('ping', () => { (socket as any).socket.terminate(); return; }); // Terminate the connection the moment it receive pong frame (socket as any).socket.on('pong', () => { (socket as any).socket.terminate(); return; }); if (this._bannedPeers.has(socket.remoteAddress)) { this._disconnectSocketDueToFailedHandshake( socket, FORBIDDEN_CONNECTION, FORBIDDEN_CONNECTION_REASON, ); return; } // Check blacklist to avoid incoming connections from blacklisted ips Eif (this._sanitizedPeerLists.blacklistedIPs) { if ( this._sanitizedPeerLists.blacklistedIPs.includes(socket.remoteAddress) ) { this._disconnectSocketDueToFailedHandshake( socket, FORBIDDEN_CONNECTION, FORBIDDEN_CONNECTION_REASON, ); return; } } }); this._scServer.on('connection', (socket: SCServerSocket): void => { Iif (!socket.request.url) { this._disconnectSocketDueToFailedHandshake( socket, INVALID_CONNECTION_URL_CODE, INVALID_CONNECTION_URL_REASON, ); return; } const queryObject = url.parse(socket.request.url, true).query; if (queryObject.nonce === this._nodeInfo.nonce) { this._disconnectSocketDueToFailedHandshake( socket, INVALID_CONNECTION_SELF_CODE, INVALID_CONNECTION_SELF_REASON, ); const selfWSPort = queryObject.wsPort ? +queryObject.wsPort : this._nodeInfo.wsPort; // Delete you peerinfo from both the lists this._peerBook.removePeer({ peerId: constructPeerId(socket.remoteAddress, selfWSPort), ipAddress: socket.remoteAddress, wsPort: selfWSPort, }); return; } Iif ( typeof queryObject.wsPort !== 'string' || typeof queryObject.version !== 'string' || typeof queryObject.networkId !== 'string' ) { this._disconnectSocketDueToFailedHandshake( socket, INVALID_CONNECTION_QUERY_CODE, INVALID_CONNECTION_QUERY_REASON, ); return; } const remoteWSPort: number = parseInt(queryObject.wsPort, BASE_10_RADIX); const peerId = constructPeerId(socket.remoteAddress, remoteWSPort); // tslint:disable-next-line no-let let queryOptions; try { queryOptions = typeof queryObject.options === 'string' ? JSON.parse(queryObject.options) : undefined; } catch (error) { this._disconnectSocketDueToFailedHandshake( socket, INVALID_CONNECTION_QUERY_CODE, INVALID_CONNECTION_QUERY_REASON, ); return; } // Remove these wsPort and ip from the query object const { wsPort, ipAddress, advertiseAddress, ...restOfQueryObject } = queryObject; const peerInPeerBook = this._peerBook.getPeer({ peerId, ipAddress: socket.remoteAddress, wsPort: remoteWSPort, }); const incomingPeerInfo: P2PPeerInfo = peerInPeerBook ? { ...peerInPeerBook, internalState: { ...(peerInPeerBook.internalState ? peerInPeerBook.internalState : assignInternalInfo(peerInPeerBook, this._secret)), advertiseAddress: advertiseAddress !== 'false', connectionKind: ConnectionKind.INBOUND, }, } : this._assignPeerKind({ sharedState: { ...restOfQueryObject, ...queryOptions, height: queryObject.height ? +queryObject.height : 0, // TODO: Remove the usage of height for choosing among peers having same ipAddress, instead use productivity and reputation protocolVersion: queryObject.protocolVersion, }, internalState: { ...assignInternalInfo( { peerId, ipAddress: socket.remoteAddress, wsPort: remoteWSPort, }, this._secret, ), advertiseAddress: advertiseAddress !== 'false', connectionKind: ConnectionKind.INBOUND, }, peerId, ipAddress: socket.remoteAddress, wsPort: remoteWSPort, }); try { validatePeerInfo( incomingPeerInfo, this._config.maxPeerInfoSize ? this._config.maxPeerInfoSize : DEFAULT_MAX_PEER_INFO_SIZE, ); } catch (error) { this._disconnectSocketDueToFailedHandshake( socket, INCOMPATIBLE_PEER_INFO_CODE, error, ); } const { success, error } = this._peerHandshakeCheck( incomingPeerInfo, this._nodeInfo, ); if (!success) { const incompatibilityReason = error || INCOMPATIBLE_PEER_UNKNOWN_REASON; this._disconnectSocketDueToFailedHandshake( socket, INCOMPATIBLE_PEER_CODE, incompatibilityReason, ); return; } try { this._peerPool.addInboundPeer(incomingPeerInfo, socket); this.emit(EVENT_NEW_INBOUND_PEER, incomingPeerInfo); } catch (err) { this._disconnectSocketDueToFailedHandshake( socket, DUPLICATE_CONNECTION, DUPLICATE_CONNECTION_REASON, ); return; } if (this._peerBook.hasPeer(incomingPeerInfo)) { return; } this._peerBook.addPeer({ ...incomingPeerInfo, sourceAddress: socket.remoteAddress, }); }); this._httpServer.listen( this._nodeInfo.wsPort, this._config.hostIp || DEFAULT_NODE_HOST_IP, ); Iif (this._scServer.isReady) { this._isActive = true; return; } return new Promise<void>(resolve => { this._scServer.once('ready', () => { this._isActive = true; resolve(); }); }); } private async _stopHTTPServer(): Promise<void> { return new Promise<void>(resolve => { this._httpServer.close(() => { resolve(); }); }); } private async _stopWSServer(): Promise<void> { return new Promise<void>(resolve => { this._scServer.close(() => { resolve(); }); }); } private async _stopPeerServer(): Promise<void> { await this._stopWSServer(); await this._stopHTTPServer(); } private _startPopulator(): void { Iif (this._populatorIntervalId) { throw new Error('Populator is already running'); } this._populatorIntervalId = setInterval(() => { this._peerPool.triggerNewConnections( this._peerBook.newPeers, this._peerBook.triedPeers, ); // LIP-0004 re-discovery SeedPeers when Outboundconnection < maxOutboundconnections if ( this._nextSeedPeerDiscovery < Date.now() && this._peerPool.getFreeOutboundSlots() > 0 ) { this._peerPool.discoverFromSeedPeers(); this._nextSeedPeerDiscovery = Date.now() + this._fallbackSeedPeerDiscoveryInterval; } }, this._populatorInterval); // Initial Populator this._peerPool.triggerNewConnections( this._peerBook.newPeers, this._peerBook.triedPeers, ); } private _stopPopulator(): void { Eif (this._populatorIntervalId) { clearInterval(this._populatorIntervalId); } } private _isNetworkReady(): boolean { if (!this._hasConnected && this._peerPool.getConnectedPeers().length > 0) { this._hasConnected = true; return true; } return false; } private _handleGetPeersRequest(request: P2PRequest): void { const minimumPeerDiscoveryThreshold = this._config .minimumPeerDiscoveryThreshold ? this._config.minimumPeerDiscoveryThreshold : DEFAULT_MIN_PEER_DISCOVERY_THRESHOLD; const maxPeerDiscoveryResponseLength = this._config .maxPeerDiscoveryResponseLength ? this._config.maxPeerDiscoveryResponseLength : DEFAULT_MAX_PEER_DISCOVERY_RESPONSE_LENGTH; const wsMaxPayload = this._config.wsMaxPayload ? this._config.wsMaxPayload : DEFAULT_WS_MAX_PAYLOAD; const maxPeerInfoSize = this._config.maxPeerInfoSize ? this._config.maxPeerInfoSize : DEFAULT_MAX_PEER_INFO_SIZE; const safeMaxPeerInfoLength = Math.floor(DEFAULT_WS_MAX_PAYLOAD / maxPeerInfoSize) - 1; const selectedPeers = this._peerBook.getRandomizedPeerList( minimumPeerDiscoveryThreshold, maxPeerDiscoveryResponseLength, ); // Remove internal state to check byte size const sanitizedPeerInfoList: ProtocolPeerInfo[] = selectedPeers .filter( peer => !(peer.internalState && !peer.internalState.advertiseAddress), ) .map(peer => ({ ipAddress: peer.ipAddress, wsPort: peer.wsPort, ...peer.sharedState, })); request.end({ success: true, peers: getByteSize(sanitizedPeerInfoList) < wsMaxPayload ? sanitizedPeerInfoList : sanitizedPeerInfoList.slice(0, safeMaxPeerInfoLength), }); } private _handleGetNodeInfo(request: P2PRequest): void { request.end(this._nodeInfo); } private _isTrustedPeer(peerId: string): boolean { const isSeed = this._sanitizedPeerLists.seedPeers.find( seedPeer => peerId === seedPeer.peerId, ); const isWhitelisted = this._sanitizedPeerLists.whitelisted.find( peer => peer.peerId === peerId, ); const isFixed = this._sanitizedPeerLists.fixedPeers.find( peer => peer.peerId === peerId, ); return !!isSeed || !!isWhitelisted || !!isFixed; } private _initializePeerBook(): void { const newPeersToAdd = [ ...this._sanitizedPeerLists.fixedPeers, ...this._sanitizedPeerLists.whitelisted, ...this._sanitizedPeerLists.previousPeers, ]; // Add peers to tried peers if want to re-use previously tried peers // According to LIP, add whitelist peers to triedPeer by upgrading them initially. newPeersToAdd.forEach(peerInfo => { if (!this._peerBook.hasPeer(peerInfo)) { this._peerBook.addPeer(this._assignPeerKind(peerInfo)); } this._peerBook.upgradePeer(peerInfo); }); } public async start(): Promise<void> { if (this._isActive) { throw new Error('Node cannot start because it is already active.'); } await this._startPeerServer(); // We need this check this._isActive in case the P2P library is shut down while it was in the middle of starting up. Eif (this._isActive) { // Initial discovery and disconnect from SeedPeers (LIP-0004) Eif (this._peerBook.triedPeers.length < DEFAULT_MIN_TRIED_PEER_COUNT) { this._peerPool.discoverFromSeedPeers(); this._nextSeedPeerDiscovery = Date.now() + this._fallbackSeedPeerDiscoveryInterval; } this._startPopulator(); } } public async stop(): Promise<void> { if (!this._isActive) { throw new Error('Node cannot be stopped because it is not active.'); } this._isActive = false; this._hasConnected = false; this._stopPopulator(); this._peerPool.removeAllPeers(); await this._stopPeerServer(); } private _bindHandlersToPeerPool(peerPool: PeerPool): void { peerPool.on(EVENT_REQUEST_RECEIVED, this._handlePeerPoolRPC); peerPool.on(EVENT_MESSAGE_RECEIVED, this._handlePeerPoolMessage); peerPool.on(EVENT_CONNECT_OUTBOUND, this._handleOutboundPeerConnect); peerPool.on( EVENT_CONNECT_ABORT_OUTBOUND, this._handleOutboundPeerConnectAbort, ); peerPool.on(EVENT_CLOSE_INBOUND, this._handlePeerCloseInbound); peerPool.on(EVENT_CLOSE_OUTBOUND, this._handlePeerCloseOutbound); peerPool.on(EVENT_REMOVE_PEER, this._handleRemovePeer); peerPool.on(EVENT_UPDATED_PEER_INFO, this._handlePeerInfoUpdate); peerPool.on( EVENT_FAILED_PEER_INFO_UPDATE, this._handleFailedPeerInfoUpdate, ); peerPool.on( EVENT_FAILED_TO_FETCH_PEER_INFO, this._handleFailedToFetchPeerInfo, ); peerPool.on(EVENT_FAILED_TO_FETCH_PEERS, this._handleFailedToFetchPeers); peerPool.on( EVENT_FAILED_TO_COLLECT_PEER_DETAILS_ON_CONNECT, this._handleFailedToCollectPeerDetails, ); peerPool.on(EVENT_DISCOVERED_PEER, this._handleDiscoveredPeer); peerPool.on( EVENT_FAILED_TO_PUSH_NODE_INFO, this._handleFailedToPushNodeInfo, ); peerPool.on(EVENT_FAILED_TO_SEND_MESSAGE, this._handleFailedToSendMessage); peerPool.on(EVENT_OUTBOUND_SOCKET_ERROR, this._handleOutboundSocketError); peerPool.on(EVENT_INBOUND_SOCKET_ERROR, this._handleInboundSocketError); peerPool.on(EVENT_BAN_PEER, this._handleBanPeer); peerPool.on(EVENT_UNBAN_PEER, this._handleUnbanPeer); } // tslint:disable-next-line:max-file-line-count } |