js-libp2p-noise/src/noise.ts

56 lines
1.6 KiB
TypeScript
Raw Normal View History

2019-11-11 15:39:09 +01:00
import { x25519 } from 'bcrypto';
2019-11-08 14:03:34 +01:00
import { bytes } from "./types/basic";
import { Connection } from "./types/libp2p";
2019-11-11 15:39:09 +01:00
import { KeyPair, XXHandshake } from "./xx";
import { signPayload } from "../test/utils";
import {Buffer} from "buffer";
2019-11-08 14:03:34 +01:00
export class Noise {
2019-11-11 15:39:09 +01:00
private readonly privateKey: bytes;
private staticKeys?: KeyPair;
private earlyData?: bytes;
2019-11-08 14:03:34 +01:00
constructor(privateKey: bytes, staticNoiseKey?: bytes, earlyData?: bytes) {
2019-11-11 15:39:09 +01:00
this.privateKey = privateKey;
this.earlyData = earlyData;
2019-11-08 14:03:34 +01:00
2019-11-11 15:39:09 +01:00
if (staticNoiseKey) {
const publicKey = x25519.publicKeyCreate(staticNoiseKey);
this.staticKeys = {
privateKey: staticNoiseKey,
publicKey,
}
}
2019-11-08 14:03:34 +01:00
}
public tag() {
return '/noise';
}
2019-11-11 15:39:09 +01:00
public async encrypt(InsecureConnection: Connection, remotePublicKey: bytes) {
const isInitiator = InsecureConnection.stats.direction === "outbound";
const secretKey = await this.doHandshake(isInitiator, remotePublicKey);
}
private async doHandshake(isInitiator: boolean, remotePublicKey: bytes) : Promise<bytes> {
const xx = new XXHandshake();
if (!this.staticKeys) {
this.staticKeys = await xx.generateKeypair();
}
let signedPayload;
if (this.earlyData) {
const payload = Buffer.concat([this.earlyData, this.staticKeys.publicKey])
signedPayload = await signPayload(this.privateKey, payload);
}
2019-11-08 14:03:34 +01:00
2019-11-11 15:39:09 +01:00
const prologue = Buffer.from(this.tag());
const nsInit = await xx.initSession(isInitiator, prologue, this.staticKeys, remotePublicKey);
// TODO: Send messages, confirm handshake and return shared key
return Buffer.alloc(0);
2019-11-08 14:03:34 +01:00
}
}