2021-10-02 00:16:34 +00:00
|
|
|
"use strict";
|
|
|
|
|
2022-01-08 16:59:08 +00:00
|
|
|
import fs from 'fs';
|
2021-10-02 00:16:34 +00:00
|
|
|
import os from 'os';
|
|
|
|
|
2022-01-08 21:37:03 +00:00
|
|
|
import log from 'log'; const l = log.get("agent");
|
2021-10-02 00:16:34 +00:00
|
|
|
import systeminfo from 'systeminformation';
|
|
|
|
|
2022-01-08 21:37:03 +00:00
|
|
|
import settings from '../../settings.mjs';
|
|
|
|
|
2022-01-08 16:59:08 +00:00
|
|
|
import PeerServer from './PeerServer.mjs';
|
2021-10-02 00:16:34 +00:00
|
|
|
import hash from '../crypto/hash.mjs';
|
2022-01-08 16:59:08 +00:00
|
|
|
import parse_peer_name from '../parse/peer_name.mjs';
|
2021-10-02 00:16:34 +00:00
|
|
|
|
|
|
|
class Agent {
|
2022-01-08 16:59:08 +00:00
|
|
|
constructor(config) {
|
|
|
|
this.config = config;
|
2021-10-02 00:16:34 +00:00
|
|
|
}
|
|
|
|
|
2022-01-08 16:59:08 +00:00
|
|
|
async find_secret() {
|
|
|
|
if(this.config.secret_join_filepath !== "CHANGE_ME"
|
|
|
|
&& fs.existsSync(this.config.secret_join_filepath))
|
2022-01-08 21:37:03 +00:00
|
|
|
return await fs.promises.readFile(
|
|
|
|
path.resolve(
|
|
|
|
path.dirname(settings.cli.config),
|
|
|
|
this.config.secret_join_filepath
|
|
|
|
),
|
|
|
|
"utf-8");
|
2022-01-08 16:59:08 +00:00
|
|
|
|
|
|
|
if(this.config.secret_join !== "CHANGE_ME")
|
|
|
|
return this.config.secret_join;
|
2021-10-02 00:16:34 +00:00
|
|
|
|
2022-01-08 16:59:08 +00:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
async init() {
|
2021-10-02 00:16:34 +00:00
|
|
|
/** Our peer id - calculated automatically from the system's uuid */
|
|
|
|
this.peer_id = hash("sha256", "base64", await systeminfo.system().serial)
|
|
|
|
.replace(/[+/=]/g, "");
|
|
|
|
this.peer_name = os.hostname();
|
|
|
|
|
2022-01-08 16:59:08 +00:00
|
|
|
this.server = new PeerServer(
|
|
|
|
this.peer_id,
|
|
|
|
await this.find_secret()
|
|
|
|
);
|
|
|
|
this.server.retries = this.config.net.peer_retries;
|
2021-10-02 00:16:34 +00:00
|
|
|
|
2022-01-08 16:59:08 +00:00
|
|
|
l.log(`Starting peer listener....`);
|
|
|
|
await this.server.listen(
|
|
|
|
this.config.net.port,
|
|
|
|
this.config.net.bind_address
|
|
|
|
);
|
|
|
|
l.log(`Listening on ${this.config.net.bind_address}:${this.config.net.port}`);
|
2021-10-02 00:16:34 +00:00
|
|
|
|
2022-01-08 16:59:08 +00:00
|
|
|
await this.server.add_peers(...this.config.peers.map(
|
|
|
|
peer => parse_peer_name(peer)
|
|
|
|
));
|
|
|
|
l.log(`Added ${this.config.peers.length} initial peers`);
|
|
|
|
if(this.config.peers.length < 1)
|
|
|
|
l.warn(`No initial peers were specified! It's recommended that you specify at least 1 on every host.`);
|
2021-10-02 00:16:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Agent;
|