All files / src/peer_book base_list.ts

98.04% Statements 50/51
96.43% Branches 27/28
100% Functions 12/12
98.04% Lines 50/51

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                            36x   36x                                         36x                               1048x           1048x 1048x 1048x       6439x   6439x 603200x   21670x       6439x       51557x           25973x 2x     25971x                 25971x       25971x           25971x 25971x   25971x       11517x   11517x 7326x     4191x       2923x   2923x 1x     2922x         2922x 2922x   2922x       13564x   13564x 6796x 6796x       6796x     6768x         1601x         29x             26147x                 26147x       16489x   16489x 6770x     9719x   9719x       9719x         1048x     100618x              
/*
 * 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 { ExistingPeerError } from '../errors';
import { P2PEnhancedPeerInfo, P2PPeerInfo } from '../p2p_types';
import {
	evictPeerRandomlyFromBucket,
	getBucketId,
	PEER_TYPE,
	sanitizeEnhancedPeerInfo,
} from '../utils';
 
export interface PeerListConfig {
	readonly numOfBuckets: number;
	readonly bucketSize: number;
	readonly secret: number;
	readonly peerType: PEER_TYPE;
}
 
export type Bucket = Map<string, P2PEnhancedPeerInfo>;
 
export interface BucketInfo {
	readonly bucketId: number;
	readonly bucket: Bucket;
}
 
export class BaseList {
	protected bucketIdToBucket: Map<number, Bucket>;
	/* 
		Auxillary map for direct peerId => peerInfo lookups
		Required because peerLists may be provided by discrete sources
	*/
	protected peerIdToPeerInfo: Map<string, P2PEnhancedPeerInfo>;
	protected type: PEER_TYPE | undefined;
	protected readonly peerListConfig: PeerListConfig;
 
	public constructor({
		bucketSize,
		numOfBuckets,
		secret,
		peerType,
	}: PeerListConfig) {
		this.peerListConfig = {
			bucketSize,
			numOfBuckets,
			peerType,
			secret,
		};
		this.bucketIdToBucket = new Map();
		this._initBuckets();
		this.peerIdToPeerInfo = new Map();
	}
 
	public get peerList(): ReadonlyArray<P2PPeerInfo> {
		const peerListMap: P2PPeerInfo[] = [];
 
		for (const peerList of [...this.bucketIdToBucket.values()]) {
			for (const peer of [...peerList.values()]) {
				// Remove internal fields before sharing
				peerListMap.push(sanitizeEnhancedPeerInfo(peer));
			}
		}
 
		return peerListMap;
	}
 
	public hasPeer(incomingPeerId: string): boolean {
		return this.peerIdToPeerInfo.has(incomingPeerId);
	}
 
	public addPeer(
		incomingPeerInfo: P2PEnhancedPeerInfo,
	): P2PEnhancedPeerInfo | undefined {
		if (this.hasPeer(incomingPeerInfo.peerId)) {
			throw new ExistingPeerError(incomingPeerInfo);
		}
 
		const { bucketId, bucket } = this.calculateBucket(
			incomingPeerInfo.ipAddress,
			this.type === PEER_TYPE.NEW_PEER
				? incomingPeerInfo.sourceAddress
				: undefined,
		);
 
		// If bucket is full, evict a peer to make space for incoming peer
		const evictedPeer =
			bucket.size >= this.peerListConfig.bucketSize
				? this.makeSpace(bucket)
				: undefined;
 
		const internalPeerInfo = {
			...incomingPeerInfo,
			numOfConnectionFailures: 0,
			dateAdded: new Date(),
			bucketId,
		};
		bucket.set(incomingPeerInfo.peerId, internalPeerInfo);
		this.peerIdToPeerInfo.set(incomingPeerInfo.peerId, internalPeerInfo);
 
		return evictedPeer;
	}
 
	public getPeer(incomingPeerId: string): P2PPeerInfo | undefined {
		const peerInfo = this.peerIdToPeerInfo.get(incomingPeerId);
 
		if (!peerInfo) {
			return undefined;
		}
 
		return sanitizeEnhancedPeerInfo(peerInfo);
	}
 
	public updatePeer(incomingPeerInfo: P2PEnhancedPeerInfo): boolean {
		const bucket = this.getBucket(incomingPeerInfo.peerId);
 
		if (!bucket) {
			return false;
		}
 
		const updatedInternalPeerInfo = {
			...bucket.get(incomingPeerInfo.peerId),
			...incomingPeerInfo,
		};
 
		bucket.set(incomingPeerInfo.peerId, updatedInternalPeerInfo);
		this.peerIdToPeerInfo.set(incomingPeerInfo.peerId, updatedInternalPeerInfo);
 
		return true;
	}
 
	public removePeer(incomingPeerInfo: P2PPeerInfo): boolean {
		const bucket = this.getBucket(incomingPeerInfo.peerId);
 
		if (bucket?.has(incomingPeerInfo.peerId)) {
			const removedFromBucket = bucket.delete(incomingPeerInfo.peerId);
			const removedFromPeerLookup = this.peerIdToPeerInfo.delete(
				incomingPeerInfo.peerId,
			);
 
			return removedFromBucket && removedFromPeerLookup;
		}
 
		return false;
	}
 
	// tslint:disable-next-line prefer-function-over-method
	public makeSpace(bucket: Bucket): P2PEnhancedPeerInfo | undefined {
		return evictPeerRandomlyFromBucket(bucket);
	}
 
	// This action is called when a peer is disconnected
	public failedConnectionAction(incomingPeerInfo: P2PPeerInfo): boolean {
		return this.removePeer(incomingPeerInfo);
	}
 
	public calculateBucket(
		targetAddress: string,
		sourceAddress?: string,
	): BucketInfo {
		const bucketId = getBucketId({
			secret: this.peerListConfig.secret,
			peerType: this.peerListConfig.peerType,
			targetAddress,
			sourceAddress:
				this.type === PEER_TYPE.NEW_PEER ? sourceAddress : undefined,
			bucketCount: this.peerListConfig.numOfBuckets,
		});
 
		return { bucketId, bucket: this.bucketIdToBucket.get(bucketId) as Bucket };
	}
 
	protected getBucket(peerId: string): Bucket | undefined {
		const internalPeerInfo = this.peerIdToPeerInfo.get(peerId);
 
		if (typeof internalPeerInfo?.bucketId !== 'number') {
			return undefined;
		}
 
		const bucket = this.bucketIdToBucket.get(internalPeerInfo.bucketId);
 
		Iif (!bucket) {
			return undefined;
		}
 
		return bucket;
	}
 
	private _initBuckets(): void {
		// Init the Map with all the buckets
		for (const bucketId of [
			...new Array(this.peerListConfig.numOfBuckets).keys(),
		]) {
			this.bucketIdToBucket.set(
				bucketId,
				new Map<string, P2PEnhancedPeerInfo>(),
			);
		}
	}
}