js-libp2p-noise/src/handshake.ts

58 lines
1.5 KiB
TypeScript
Raw Normal View History

2019-11-20 13:23:36 +01:00
import { bytes, bytes32 } from "./@types/basic";
2019-11-12 14:07:25 +01:00
import { NoiseSession, XXHandshake } from "./xx";
2019-11-20 22:52:08 +01:00
import { KeyPair } from "./@types/libp2p";
import { Buffer } from "buffer";
2019-11-20 13:23:36 +01:00
type handshakeType = "XX";
2019-11-11 21:58:04 +01:00
export class Handshake {
2019-11-20 13:23:36 +01:00
private type: handshakeType;
private remotePublicKey: bytes;
private signedPayload: bytes;
private prologue: bytes32;
private staticKeys: KeyPair;
2019-11-20 22:52:08 +01:00
private connection: any;
2019-11-20 13:23:36 +01:00
constructor(
type: handshakeType,
2019-11-11 21:58:04 +01:00
remotePublicKey: bytes,
prologue: bytes32,
signedPayload: bytes,
staticKeys: KeyPair,
2019-11-20 22:52:08 +01:00
connection,
2019-11-20 13:23:36 +01:00
) {
this.type = type;
this.remotePublicKey = remotePublicKey;
this.signedPayload = signedPayload;
this.prologue = prologue;
this.staticKeys = staticKeys;
2019-11-20 22:52:08 +01:00
this.connection = connection;
2019-11-20 13:23:36 +01:00
}
2019-11-20 22:52:08 +01:00
// stage 0
2019-11-20 13:23:36 +01:00
async propose(isInitiator: boolean) : Promise<NoiseSession> {
2019-11-11 21:58:04 +01:00
const xx = new XXHandshake();
2019-11-20 22:52:08 +01:00
const ns = await xx.initSession(isInitiator, this.prologue, this.staticKeys, this.remotePublicKey);
2019-11-20 21:38:14 +01:00
if (isInitiator) {
const message = Buffer.concat([Buffer.alloc(0), this.signedPayload]);
2019-11-20 22:52:08 +01:00
const messageBuffer = await xx.sendMessage(ns, message);
this.connection.writeLP(messageBuffer);
} else {
const receivedMessageBuffer = (await this.connection.readLP()).slice();
const plaintext = await xx.recvMessage(ns, receivedMessageBuffer);
2019-11-20 21:38:14 +01:00
}
2019-11-20 22:52:08 +01:00
return ns;
2019-11-11 21:58:04 +01:00
}
2019-11-20 13:23:36 +01:00
async exchange() : Promise<NoiseSession> {
}
async finish() : Promise<NoiseSession> {
}
2019-11-11 21:58:04 +01:00
}