Network.jsx 16.8 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 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
// @flow

// Copyright 2018 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

import React, {Component} from 'react';

import Table from '@material-ui/core/Table';
import TableHead from '@material-ui/core/TableHead';
import TableBody from '@material-ui/core/TableBody';
import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell';
import Grid from '@material-ui/core/Grid/Grid';
import Typography from '@material-ui/core/Typography';
import {AreaChart, Area, Tooltip, YAxis} from 'recharts';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faCircle as fasCircle} from '@fortawesome/free-solid-svg-icons';
import {faCircle as farCircle} from '@fortawesome/free-regular-svg-icons';
import convert from 'color-convert';

import CustomTooltip, {bytePlotter, multiplier} from 'CustomTooltip';
import type {Network as NetworkType, PeerEvent} from '../types/content';
import {styles as commonStyles, chartStrokeWidth, hues, hueScale} from '../common';

// Peer chart dimensions.
const trafficChartHeight = 18;
const trafficChartWidth  = 400;

// setMaxIngress adjusts the peer chart's gradient values based on the given value.
const setMaxIngress = (peer, value) => {
	peer.maxIngress = value;
	peer.ingressGradient = [];
	peer.ingressGradient.push({offset: hueScale[0], color: hues[0]});
	let i = 1;
	for (; i < hues.length && value > hueScale[i]; i++) {
		peer.ingressGradient.push({offset: Math.floor(hueScale[i] * 100 / value), color: hues[i]});
	}
	i--;
	if (i < hues.length - 1) {
		// Usually the maximum value gets between two points on the predefined
		// color scale (e.g. 123KB is somewhere between 100KB (#FFFF00) and
		// 1MB (#FF0000)), and the charts need to be comparable by the colors,
		// so we have to calculate the last hue using the maximum value and the
		// surrounding hues in order to avoid the uniformity of the top colors
		// on the charts. For this reason the two hues are translated into the
		// CIELAB color space, and the top color will be their weighted average
		// (CIELAB is perceptually uniform, meaning that any point on the line
		// between two pure color points is also a pure color, so the weighted
		// average will not lose from the saturation).
		//
		// In case the maximum value is greater than the biggest predefined
		// scale value, the top of the chart will have uniform color.
		const lastHue = convert.hex.lab(hues[i]);
		const proportion = (value - hueScale[i]) * 100 / (hueScale[i + 1] - hueScale[i]);
		convert.hex.lab(hues[i + 1]).forEach((val, j) => {
			lastHue[j] = (lastHue[j] * proportion + val * (100 - proportion)) / 100;
		});
		peer.ingressGradient.push({offset: 100, color: `#${convert.lab.hex(lastHue)}`});
	}
};

// setMaxEgress adjusts the peer chart's gradient values based on the given value.
// In case of the egress the chart is upside down, so the gradients need to be
// calculated inversely compared to the ingress.
const setMaxEgress = (peer, value) => {
	peer.maxEgress = value;
	peer.egressGradient = [];
	peer.egressGradient.push({offset: 100 - hueScale[0], color: hues[0]});
	let i = 1;
	for (; i < hues.length && value > hueScale[i]; i++) {
		peer.egressGradient.unshift({offset: 100 - Math.floor(hueScale[i] * 100 / value), color: hues[i]});
	}
	i--;
	if (i < hues.length - 1) {
		// Calculate the last hue.
		const lastHue = convert.hex.lab(hues[i]);
		const proportion = (value - hueScale[i]) * 100 / (hueScale[i + 1] - hueScale[i]);
		convert.hex.lab(hues[i + 1]).forEach((val, j) => {
			lastHue[j] = (lastHue[j] * proportion + val * (100 - proportion)) / 100;
		});
		peer.egressGradient.unshift({offset: 0, color: `#${convert.lab.hex(lastHue)}`});
	}
};


// setIngressChartAttributes searches for the maximum value of the ingress
// samples, and adjusts the peer chart's gradient values accordingly.
const setIngressChartAttributes = (peer) => {
	let max = 0;
	peer.ingress.forEach(({value}) => {
		if (value > max) {
			max = value;
		}
	});
	setMaxIngress(peer, max);
};

// setEgressChartAttributes searches for the maximum value of the egress
// samples, and adjusts the peer chart's gradient values accordingly.
const setEgressChartAttributes = (peer) => {
	let max = 0;
	peer.egress.forEach(({value}) => {
		if (value > max) {
			max = value;
		}
	});
	setMaxEgress(peer, max);
};

// inserter is a state updater function for the main component, which handles the peers.
export const inserter = (sampleLimit: number) => (update: NetworkType, prev: NetworkType) => {
	// The first message contains the metered peer history.
	if (update.peers && update.peers.bundles) {
		prev.peers = update.peers;
		Object.values(prev.peers.bundles).forEach((bundle) => {
			if (bundle.knownPeers) {
				Object.values(bundle.knownPeers).forEach((peer) => {
					if (!peer.maxIngress) {
						setIngressChartAttributes(peer);
					}
					if (!peer.maxEgress) {
						setEgressChartAttributes(peer);
					}
				});
			}
		});
	}
	if (Array.isArray(update.diff)) {
		update.diff.forEach((event: PeerEvent) => {
			if (!event.ip) {
				console.error('Peer event without IP', event);
				return;
			}
			switch (event.remove) {
			case 'bundle': {
				delete prev.peers.bundles[event.ip];
				return;
			}
			case 'known': {
				if (!event.id) {
					console.error('Remove known peer event without ID', event.ip);
					return;
				}
				const bundle = prev.peers.bundles[event.ip];
				if (!bundle || !bundle.knownPeers || !bundle.knownPeers[event.id]) {
					console.error('No known peer to remove', event.ip, event.id);
					return;
				}
				delete bundle.knownPeers[event.id];
				return;
			}
			case 'attempt': {
				const bundle = prev.peers.bundles[event.ip];
				if (!bundle || !Array.isArray(bundle.attempts) || bundle.attempts.length < 1) {
					console.error('No unknown peer to remove', event.ip);
					return;
				}
				bundle.attempts.splice(0, 1);
				return;
			}
			}
			if (!prev.peers.bundles[event.ip]) {
				prev.peers.bundles[event.ip] = {
					location: {
						country:   '',
						city:      '',
						latitude:  0,
						longitude: 0,
					},
					knownPeers: {},
					attempts:   [],
				};
			}
			const bundle = prev.peers.bundles[event.ip];
			if (event.location) {
				bundle.location = event.location;
				return;
			}
			if (!event.id) {
				if (!bundle.attempts) {
					bundle.attempts = [];
				}
				bundle.attempts.push({
					connected:    event.connected,
					disconnected: event.disconnected,
				});
				return;
			}
			if (!bundle.knownPeers) {
				bundle.knownPeers = {};
			}
			if (!bundle.knownPeers[event.id]) {
				bundle.knownPeers[event.id] = {
					connected:    [],
					disconnected: [],
					ingress:      [],
					egress:       [],
					active:       false,
				};
			}
			const peer = bundle.knownPeers[event.id];
			if (!peer.maxIngress) {
				setIngressChartAttributes(peer);
			}
			if (!peer.maxEgress) {
				setEgressChartAttributes(peer);
			}
			if (event.connected) {
				if (!peer.connected) {
					console.warn('peer.connected should exist');
					peer.connected = [];
				}
				peer.connected.push(event.connected);
			}
			if (event.disconnected) {
				if (!peer.disconnected) {
					console.warn('peer.disconnected should exist');
					peer.disconnected = [];
				}
				peer.disconnected.push(event.disconnected);
			}
			switch (event.activity) {
			case 'active':
				peer.active = true;
				break;
			case 'inactive':
				peer.active = false;
				break;
			}
			if (Array.isArray(event.ingress) && Array.isArray(event.egress)) {
				if (event.ingress.length !== event.egress.length) {
					console.error('Different traffic sample length', event);
					return;
				}
				// Check if there is a new maximum value, and reset the colors in case.
				let maxIngress = peer.maxIngress;
				event.ingress.forEach(({value}) => {
					if (value > maxIngress) {
						maxIngress = value;
					}
				});
				if (maxIngress > peer.maxIngress) {
					setMaxIngress(peer, maxIngress);
				}
				// Push the new values.
				peer.ingress.splice(peer.ingress.length, 0, ...event.ingress);
				const ingressDiff = peer.ingress.length - sampleLimit;
				if (ingressDiff > 0) {
					// Check if the maximum value is in the beginning.
					let i = 0;
					while (i < ingressDiff && peer.ingress[i].value < peer.maxIngress) {
						i++;
					}
					// Remove the old values from the beginning.
					peer.ingress.splice(0, ingressDiff);
					if (i < ingressDiff) {
						// Reset the colors if the maximum value leaves the chart.
						setIngressChartAttributes(peer);
					}
				}
				// Check if there is a new maximum value, and reset the colors in case.
				let maxEgress = peer.maxEgress;
				event.egress.forEach(({value}) => {
					if (value > maxEgress) {
						maxEgress = value;
					}
				});
				if (maxEgress > peer.maxEgress) {
					setMaxEgress(peer, maxEgress);
				}
				// Push the new values.
				peer.egress.splice(peer.egress.length, 0, ...event.egress);
				const egressDiff = peer.egress.length - sampleLimit;
				if (egressDiff > 0) {
					// Check if the maximum value is in the beginning.
					let i = 0;
					while (i < egressDiff && peer.egress[i].value < peer.maxEgress) {
						i++;
					}
					// Remove the old values from the beginning.
					peer.egress.splice(0, egressDiff);
					if (i < egressDiff) {
						// Reset the colors if the maximum value leaves the chart.
						setEgressChartAttributes(peer);
					}
				}
			}
		});
	}
	return prev;
};

// styles contains the constant styles of the component.
const styles = {
	tableHead: {
		height: 'auto',
	},
	tableRow: {
		height: 'auto',
	},
	tableCell: {
		paddingTop:    0,
		paddingRight:  5,
		paddingBottom: 0,
		paddingLeft:   5,
		border:        'none',
	},
};

export type Props = {
    container:    Object,
    content:      NetworkType,
    shouldUpdate: Object,
};

type State = {};

// Network renders the network page.
class Network extends Component<Props, State> {
	componentDidMount() {
		const {container} = this.props;
		if (typeof container === 'undefined') {
			return;
		}
		container.scrollTop = 0;
	}

	formatTime = (t: string) => {
		const time = new Date(t);
		if (isNaN(time)) {
			return '';
		}
		const month = `0${time.getMonth() + 1}`.slice(-2);
		const date = `0${time.getDate()}`.slice(-2);
		const hours = `0${time.getHours()}`.slice(-2);
		const minutes = `0${time.getMinutes()}`.slice(-2);
		const seconds = `0${time.getSeconds()}`.slice(-2);
		return `${month}/${date}/${hours}:${minutes}:${seconds}`;
	};

	copyToClipboard = (id) => (event) => {
		event.preventDefault();
		navigator.clipboard.writeText(id).then(() => {}, () => {
			console.error("Failed to copy node id", id);
		});
	};

	peerTableRow = (ip, id, bundle, peer) => {
		const ingressValues = peer.ingress.map(({value}) => ({ingress: value || 0.001}));
		const egressValues = peer.egress.map(({value}) => ({egress: -value || -0.001}));

		return (
			<TableRow key={`known_${ip}_${id}`} style={styles.tableRow}>
				<TableCell style={styles.tableCell}>
					{peer.active
						? <FontAwesomeIcon icon={fasCircle} color='green' />
						: <FontAwesomeIcon icon={farCircle} style={commonStyles.light} />
					}
				</TableCell>
				<TableCell style={{fontFamily: 'monospace', cursor: 'copy', ...styles.tableCell, ...commonStyles.light}} onClick={this.copyToClipboard(id)}>
					{id.substring(0, 10)}
				</TableCell>
				<TableCell style={styles.tableCell}>
					{bundle.location ? (() => {
						const l = bundle.location;
						return `${l.country ? l.country : ''}${l.city ? `/${l.city}` : ''}`;
					})() : ''}
				</TableCell>
				<TableCell style={styles.tableCell}>
					<AreaChart
						width={trafficChartWidth}
						height={trafficChartHeight}
						data={ingressValues}
						margin={{top: 5, right: 5, bottom: 0, left: 5}}
						syncId={`peerIngress_${ip}_${id}`}
					>
						<defs>
							<linearGradient id={`ingressGradient_${ip}_${id}`} x1='0' y1='1' x2='0' y2='0'>
								{peer.ingressGradient
								&& peer.ingressGradient.map(({offset, color}, i) => (
									<stop
										key={`ingressStop_${ip}_${id}_${i}`}
										offset={`${offset}%`}
										stopColor={color}
									/>
								))}
							</linearGradient>
						</defs>
						<Tooltip cursor={false} content={<CustomTooltip tooltip={bytePlotter('Download')} />} />
						<YAxis hide scale='sqrt' domain={[0.001, dataMax => Math.max(dataMax, 0)]} />
						<Area
							dataKey='ingress'
							isAnimationActive={false}
							type='monotone'
							fill={`url(#ingressGradient_${ip}_${id})`}
							stroke={peer.ingressGradient[peer.ingressGradient.length - 1].color}
							strokeWidth={chartStrokeWidth}
						/>
					</AreaChart>
					<AreaChart
						width={trafficChartWidth}
						height={trafficChartHeight}
						data={egressValues}
						margin={{top: 0, right: 5, bottom: 5, left: 5}}
						syncId={`peerIngress_${ip}_${id}`}
					>
						<defs>
							<linearGradient id={`egressGradient_${ip}_${id}`} x1='0' y1='1' x2='0' y2='0'>
								{peer.egressGradient
								&& peer.egressGradient.map(({offset, color}, i) => (
									<stop
										key={`egressStop_${ip}_${id}_${i}`}
										offset={`${offset}%`}
										stopColor={color}
									/>
								))}
							</linearGradient>
						</defs>
						<Tooltip cursor={false} content={<CustomTooltip tooltip={bytePlotter('Upload', multiplier(-1))} />} />
						<YAxis hide scale='sqrt' domain={[dataMin => Math.min(dataMin, 0), -0.001]} />
						<Area
							dataKey='egress'
							isAnimationActive={false}
							type='monotone'
							fill={`url(#egressGradient_${ip}_${id})`}
							stroke={peer.egressGradient[0].color}
							strokeWidth={chartStrokeWidth}
						/>
					</AreaChart>
				</TableCell>
			</TableRow>
		);
	};

	render() {
		return (
			<Grid container direction='row' justify='space-between'>
				<Grid item>
					<Table>
						<TableHead style={styles.tableHead}>
							<TableRow style={styles.tableRow}>
								<TableCell style={styles.tableCell} />
								<TableCell style={styles.tableCell}>Node ID</TableCell>
								<TableCell style={styles.tableCell}>Location</TableCell>
								<TableCell style={styles.tableCell}>Traffic</TableCell>
							</TableRow>
						</TableHead>
						<TableBody>
							{Object.entries(this.props.content.peers.bundles).map(([ip, bundle]) => {
								if (!bundle.knownPeers || Object.keys(bundle.knownPeers).length < 1) {
									return null;
								}
								return Object.entries(bundle.knownPeers).map(([id, peer]) => {
									if (peer.active === false) {
										return null;
									}
									return this.peerTableRow(ip, id, bundle, peer);
								});
							})}
						</TableBody>
						<TableBody>
							{Object.entries(this.props.content.peers.bundles).map(([ip, bundle]) => {
								if (!bundle.knownPeers || Object.keys(bundle.knownPeers).length < 1) {
									return null;
								}
								return Object.entries(bundle.knownPeers).map(([id, peer]) => {
									if (peer.active === true) {
										return null;
									}
									return this.peerTableRow(ip, id, bundle, peer);
								});
							})}
						</TableBody>
					</Table>
				</Grid>
				<Grid item>
					<Typography variant='subtitle1' gutterBottom>
						Connection attempts
					</Typography>
					<Table>
						<TableHead style={styles.tableHead}>
							<TableRow style={styles.tableRow}>
								<TableCell style={styles.tableCell}>IP</TableCell>
								<TableCell style={styles.tableCell}>Location</TableCell>
								<TableCell style={styles.tableCell}>Nr</TableCell>
							</TableRow>
						</TableHead>
						<TableBody>
							{Object.entries(this.props.content.peers.bundles).map(([ip, bundle]) => {
								if (!bundle.attempts || bundle.attempts.length < 1) {
									return null;
								}
								return (
									<TableRow key={`attempt_${ip}`} style={styles.tableRow}>
										<TableCell style={styles.tableCell}>{ip}</TableCell>
										<TableCell style={styles.tableCell}>
											{bundle.location ? (() => {
												const l = bundle.location;
												return `${l.country ? l.country : ''}${l.city ? `/${l.city}` : ''}`;
											})() : ''}
										</TableCell>
										<TableCell style={styles.tableCell}>
											{Object.values(bundle.attempts).length}
										</TableCell>
									</TableRow>
								);
							})}
						</TableBody>
					</Table>
				</Grid>
			</Grid>
		);
	}
}

export default Network;