Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
robert-cronin committed Oct 15, 2020
1 parent a39e7b1 commit 10ed7cf
Show file tree
Hide file tree
Showing 12 changed files with 215 additions and 444 deletions.
247 changes: 70 additions & 177 deletions nix/generated/node-packages.nix

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions proto/js/Peer.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1282,8 +1282,8 @@ declare namespace Peer {
/** PeerDHTFindNodeMessage publicKey */
publicKey?: (string|null);

/** PeerDHTFindNodeMessage kNodes */
kNodes?: (string[]|null);
/** PeerDHTFindNodeMessage closestPeers */
closestPeers?: (peerInterface.IPeerInfoMessage[]|null);
}

/** Represents a PeerDHTFindNodeMessage. */
Expand All @@ -1298,8 +1298,8 @@ declare namespace Peer {
/** PeerDHTFindNodeMessage publicKey. */
public publicKey: string;

/** PeerDHTFindNodeMessage kNodes. */
public kNodes: string[];
/** PeerDHTFindNodeMessage closestPeers. */
public closestPeers: peerInterface.IPeerInfoMessage[];

/**
* Creates a new PeerDHTFindNodeMessage instance using the specified properties.
Expand Down
22 changes: 11 additions & 11 deletions proto/js/Peer.js
Original file line number Diff line number Diff line change
Expand Up @@ -2544,7 +2544,7 @@ $root.peerInterface = (function() {
* @memberof peerInterface
* @interface IPeerDHTFindNodeMessage
* @property {string|null} [publicKey] PeerDHTFindNodeMessage publicKey
* @property {Array.<string>|null} [kNodes] PeerDHTFindNodeMessage kNodes
* @property {Array.<peerInterface.IPeerInfoMessage>|null} [closestPeers] PeerDHTFindNodeMessage closestPeers
*/

/**
Expand All @@ -2556,7 +2556,7 @@ $root.peerInterface = (function() {
* @param {peerInterface.IPeerDHTFindNodeMessage=} [p] Properties to set
*/
function PeerDHTFindNodeMessage(p) {
this.kNodes = [];
this.closestPeers = [];
if (p)
for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
if (p[ks[i]] != null)
Expand All @@ -2572,12 +2572,12 @@ $root.peerInterface = (function() {
PeerDHTFindNodeMessage.prototype.publicKey = "";

/**
* PeerDHTFindNodeMessage kNodes.
* @member {Array.<string>} kNodes
* PeerDHTFindNodeMessage closestPeers.
* @member {Array.<peerInterface.IPeerInfoMessage>} closestPeers
* @memberof peerInterface.PeerDHTFindNodeMessage
* @instance
*/
PeerDHTFindNodeMessage.prototype.kNodes = $util.emptyArray;
PeerDHTFindNodeMessage.prototype.closestPeers = $util.emptyArray;

/**
* Creates a new PeerDHTFindNodeMessage instance using the specified properties.
Expand Down Expand Up @@ -2605,9 +2605,9 @@ $root.peerInterface = (function() {
w = $Writer.create();
if (m.publicKey != null && Object.hasOwnProperty.call(m, "publicKey"))
w.uint32(10).string(m.publicKey);
if (m.kNodes != null && m.kNodes.length) {
for (var i = 0; i < m.kNodes.length; ++i)
w.uint32(18).string(m.kNodes[i]);
if (m.closestPeers != null && m.closestPeers.length) {
for (var i = 0; i < m.closestPeers.length; ++i)
$root.peerInterface.PeerInfoMessage.encode(m.closestPeers[i], w.uint32(18).fork()).ldelim();
}
return w;
};
Expand Down Expand Up @@ -2647,9 +2647,9 @@ $root.peerInterface = (function() {
m.publicKey = r.string();
break;
case 2:
if (!(m.kNodes && m.kNodes.length))
m.kNodes = [];
m.kNodes.push(r.string());
if (!(m.closestPeers && m.closestPeers.length))
m.closestPeers = [];
m.closestPeers.push($root.peerInterface.PeerInfoMessage.decode(r, r.uint32()));
break;
default:
r.skipType(t & 7);
Expand Down
6 changes: 4 additions & 2 deletions src/agent/PolykeyAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,7 @@ class PolykeyAgent implements IAgentServer {
const publicKeys = this.pk.peerManager.listPeers();
const response = new agent.StringListMessage();
response.setSList(publicKeys);
callback(null, response);
} catch (error) {
callback(error, null);
}
Expand Down Expand Up @@ -868,10 +869,11 @@ class PolykeyAgent implements IAgentServer {
try {
this.failOnLocked();
const { publicKey, peerAddress, apiAddress } = call.request!.toObject();
if (!this.pk.peerManager.hasPeer(publicKey)) {
const peerId = PeerInfo.publicKeyToId(publicKey)
if (!this.pk.peerManager.hasPeer(peerId)) {
throw Error('peer does not exist in store');
}
const peerInfo = this.pk.peerManager.getPeer(publicKey)!;
const peerInfo = this.pk.peerManager.getPeer(peerId)!;
peerInfo.peerAddress = Address.parse(peerAddress);
peerInfo.apiAddress = Address.parse(apiAddress);
this.pk.peerManager.updatePeer(peerInfo);
Expand Down
14 changes: 5 additions & 9 deletions src/bin/peers/peerCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,28 +86,21 @@ function makeGetPeerInfoCommand() {
.option('-k, --node-path <nodePath>', 'provide the polykey path')
.option('-b64, --base64', 'output peer info as a base64 string')
.option('-cn, --current-node', 'only list the peer information for the current node, useful for sharing')
.option('-pk, --public-key <publicKey>', 'path to the file which contains the public key')
.option('-pi, --peer-id <peerId>', 'unique hash of public key that identifies the peer')
.option('-v, --verbose', 'increase verbosity level by one')
.action(
actionRunner(async (options) => {
const nodePath = determineNodePath(options.nodePath);
const client = await getAgentClient(nodePath);

const publicKeyPath = options.publicKey;
// read in publicKey if it exists
let publicKey: string | undefined;
if (publicKeyPath) {
publicKey = fs.readFileSync(publicKeyPath).toString();
}

let res: pb.PeerInfoMessage;
if (options.currentNode) {
res = (await promisifyGrpc(client.getLocalPeerInfo.bind(client))(
new pb.EmptyMessage(),
)) as pb.PeerInfoMessage;
} else {
const request = new pb.StringMessage();
request.setS(publicKey!);
request.setS(options.peerId!);
res = (await promisifyGrpc(client.getPeerInfo.bind(client))(request)) as pb.PeerInfoMessage;
}
const peerInfo = new PeerInfo(
Expand All @@ -119,6 +112,9 @@ function makeGetPeerInfoCommand() {
if (<boolean>options.base64) {
pkLogger(peerInfo.toStringB64(), PKMessageType.SUCCESS);
} else {
pkLogger('Peer Id:', PKMessageType.INFO);
pkLogger(peerInfo.id, PKMessageType.SUCCESS);

pkLogger('Peer Public Key:', PKMessageType.INFO);
pkLogger(peerInfo.publicKey, PKMessageType.SUCCESS);

Expand Down
1 change: 0 additions & 1 deletion src/peers/PeerInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ class PeerInfo {
}
}


public get publicKey() : string {
return this.readonlyPublicKey
}
Expand Down
73 changes: 39 additions & 34 deletions src/peers/PeerManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class PeerManager {
private peerStoreMetadataPath: string;

peerInfo: PeerInfo;
// peerId -> PeerInfo
private peerStore: Map<string, PeerInfo>;
private keyManager: KeyManager;
multicastBroadcaster: MulticastBroadcaster;
Expand All @@ -63,10 +64,11 @@ class PeerManager {
this.fileSystem = fileSystem;

this.peerStore = new Map();
this.peerRelayClients = new Map();

this.fileSystem.mkdirSync(polykeyPath, { recursive: true });
this.peerInfoMetadataPath = path.join(polykeyPath, '.peerInfo');
this.peerStoreMetadataPath = path.join(polykeyPath, '.peerStore');
this.peerInfoMetadataPath = path.join(polykeyPath, '.peers', '.peerInfo');
this.peerStoreMetadataPath = path.join(polykeyPath, '.peers', '.peerStore');

// Set given variables
this.keyManager = keyManager;
Expand Down Expand Up @@ -97,15 +99,20 @@ class PeerManager {
this.peerServer = new PeerServer(this, this.keyManager);
this.peerConnections = new Map();

///////////////////
// Relay Clients //
///////////////////
this.peerRelayClients = new Map();
//////////////
// Peer DHT //
//////////////
this.peerDHT = new PeerDHT(
polykeyPath,
this.fileSystem,
this.peerInfo.publicKey,
this.connectToPeer.bind(this)
(() => this.peerInfo.id),
this.connectToPeer.bind(this),
((id: string) => this.getPeer(id)).bind(this),
((peerInfo: PeerInfo) => {
if (!this.hasPeer(peerInfo.id)) {
this.addPeer(peerInfo)
}
}).bind(this)
)
}

Expand Down Expand Up @@ -138,8 +145,8 @@ class PeerManager {
if (this.hasPeer(publicKey)) {
throw Error('peer already exists in peer store');
}
this.peerStore.set(publicKey, peerInfo.deepCopy());
this.peerRelayClients.set(publicKey, new RelayClient(publicKey, this))
this.peerStore.set(peerInfo.id, peerInfo.deepCopy());
this.peerRelayClients.set(peerInfo.id, new RelayClient(publicKey, this))
this.writeMetadata();
}

Expand All @@ -148,50 +155,49 @@ class PeerManager {
* @param peerInfo Info of the peer to be updated
*/
updatePeer(peerInfo: PeerInfo): void {
const publicKey = PeerInfo.formatPublicKey(peerInfo.publicKey);
if (!this.hasPeer(publicKey)) {
if (!this.hasPeer(peerInfo.id)) {
throw Error('peer does not exist in peer store');
}
this.peerStore.set(publicKey, peerInfo.deepCopy());
this.peerRelayClients.get(publicKey)?.resetConnection()
this.peerStore.set(peerInfo.id, peerInfo.deepCopy());
this.peerRelayClients.get(peerInfo.id)?.resetConnection()
this.writeMetadata();
}

/**
* Delete a peer from the peerStore
* @param peerInfo Info of the peer to be updated
*/
deletePeer(publicKey: string): void {
if (!this.hasPeer(publicKey)) {
deletePeer(id: string): void {
if (!this.hasPeer(id)) {
throw Error('peer does not exist in peer store');
}
this.peerStore.delete(publicKey);
this.peerRelayClients.get(publicKey)?.terminate()
this.peerRelayClients.delete(publicKey)
this.peerStore.delete(id);
this.peerRelayClients.get(id)?.terminate()
this.peerRelayClients.delete(id)
this.writeMetadata();
}

/**
* Retrieves a peer for the given public key
* @param publicKey Public key of the desired peer
* @param publicKey ID of the desired peer
*/
getPeer(publicKey: string): PeerInfo | null {
return this.peerStore.get(PeerInfo.formatPublicKey(publicKey))?.deepCopy() ?? null;
getPeer(id: string): PeerInfo | null {
return this.peerStore.get(id)?.deepCopy() ?? null;
}

/**
* Determines if the peerStore contains the desired peer
* @param publicKey Public key of the desired peer
* @param id ID of the desired peer
*/
hasPeer(publicKey: string): boolean {
return this.peerStore.has(PeerInfo.formatPublicKey(publicKey));
hasPeer(id: string): boolean {
return this.peerStore.has(id);
}

/**
* List all peer public keys in the peer store
*/
listPeers(): string[] {
return Array.from(this.peerStore.values()).map((p) => p.publicKey);
return Array.from(this.peerStore.values()).map((p) => p.id);
}

//////////////////////
Expand Down Expand Up @@ -238,21 +244,21 @@ class PeerManager {
* Get a secure connection to the peer
* @param publicKey Public key of an existing peer or address of new peer
*/
connectToPeer(publicKey: string): PeerConnection {
connectToPeer(peerId: string): PeerConnection {
// Throw error if trying to connect to self
if (publicKey == this.peerInfo.publicKey) {
if (peerId == this.peerInfo.id) {
throw Error('Cannot connect to self');
}

const existingSocket = this.peerConnections.get(publicKey);
const existingSocket = this.peerConnections.get(peerId);
if (existingSocket) {
return existingSocket;
}

// try to create a connection to the address
const peerConnection = new PeerConnection(publicKey, this.keyManager, this);
const peerConnection = new PeerConnection(peerId, this.keyManager, this);

this.peerConnections.set(publicKey, peerConnection);
this.peerConnections.set(peerId, peerConnection);

return peerConnection;
}
Expand All @@ -271,7 +277,6 @@ class PeerManager {
peerAddress: peerInfo.peerAddress?.toString(),
apiAddress: peerInfo.apiAddress?.toString(),
}).finish();
console.log(this.peerInfoMetadataPath);

this.fileSystem.writeFileSync(this.peerInfoMetadataPath, metadata);
// write peer store
Expand Down Expand Up @@ -308,8 +313,8 @@ class PeerManager {
peerInfoMessage.peerAddress ?? undefined,
peerInfoMessage.apiAddress ?? undefined,
);
this.peerRelayClients.set(peerInfo.publicKey, new RelayClient(peerInfo.publicKey, this))
this.peerStore.set(peerInfo.publicKey, peerInfo);
this.peerStore.set(peerInfo.id, peerInfo);
this.peerRelayClients.set(peerInfo.id, new RelayClient(peerInfo.publicKey, this))
}
}
}
Expand Down
12 changes: 6 additions & 6 deletions src/peers/peer-connection/PeerConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ import { PeerClient } from '../../../proto/compiled/Peer_grpc_pb';
import { PeerMessage, SubServiceType } from '../../../proto/compiled/Peer_pb';

class PeerConnection {
private publicKey: string;
private peerId: string;
private keyManager: KeyManager;
private peerManager: PeerManager;

private peerClient: PeerClient;
private connected: boolean = false;
private credentials: grpc.ChannelCredentials;

constructor(publicKey: string, keyManager: KeyManager, peerManager: PeerManager) {
this.publicKey = publicKey;
constructor(peerId: string, keyManager: KeyManager, peerManager: PeerManager) {
this.peerId = peerId;
this.keyManager = keyManager;
this.peerManager = peerManager;

Expand Down Expand Up @@ -132,10 +132,10 @@ class PeerConnection {
}

private getPeerInfo() {
if (!this.peerManager.hasPeer(this.publicKey)) {
if (!this.peerManager.hasPeer(this.peerId)) {
throw Error('peer does not exist in peer store');
}
return this.peerManager.getPeer(this.publicKey)!;
return this.peerManager.getPeer(this.peerId)!;
}

private async sendPingRequest(timeout?: number): Promise<boolean> {
Expand Down Expand Up @@ -209,7 +209,7 @@ class PeerConnection {
private async encodeRequest(type: SubServiceType, request: Uint8Array): Promise<PeerMessage> {
// encrypt message
const requestString = protobufToString(request);
const encryptedMessage = await this.keyManager.encryptData(Buffer.from(requestString), Buffer.from(this.publicKey));
const encryptedMessage = await this.keyManager.encryptData(Buffer.from(requestString), Buffer.from(this.getPeerInfo().publicKey));
// sign message
const signedMessage = await this.keyManager.signData(encryptedMessage);
const subMessage = signedMessage.toString();
Expand Down
Loading

0 comments on commit 10ed7cf

Please sign in to comment.