js-libp2p-noise/test/handshake.test.ts

60 lines
2.2 KiB
TypeScript
Raw Normal View History

2019-11-22 13:06:51 +01:00
import {assert} from "chai";
2019-11-22 12:52:59 +01:00
import Duplex from 'it-pair/duplex';
import {Buffer} from "buffer";
import Wrap from "it-pb-rpc";
2019-11-21 14:43:12 +01:00
2019-11-22 12:52:59 +01:00
import {Handshake} from "../src/handshake";
import {generateKeypair} from "../src/utils";
2019-11-29 16:23:24 +01:00
import {createPeerIds} from "./fixtures/peer";
2019-11-28 17:32:46 +01:00
2019-11-21 14:43:12 +01:00
describe("Handshake", () => {
it("should propose, exchange and finish handshake", async() => {
try {
const duplex = Duplex();
const connectionFrom = Wrap(duplex[0]);
const connectionTo = Wrap(duplex[1]);
const prologue = Buffer.from('/noise');
const staticKeysInitiator = generateKeypair();
const staticKeysResponder = generateKeypair();
const [peerA, peerB] = await createPeerIds(2);
const initiatorPrivKey = peerA.privKey.marshal().slice(0, 32);
2019-12-03 13:39:33 +01:00
const initiatorPubKey = peerA.marshalPubKey();
const handshakeInitator = new Handshake(true, initiatorPrivKey, initiatorPubKey, prologue, staticKeysInitiator, connectionFrom, peerB);
const responderPrivKey = peerB.privKey.marshal().slice(0, 32);
2019-12-03 13:39:33 +01:00
const responderPubKey = peerB.marshalPubKey();
const handshakeResponder = new Handshake(false, responderPrivKey, responderPubKey, prologue, staticKeysResponder, connectionTo, peerA);
await handshakeInitator.propose();
await handshakeResponder.propose();
await handshakeResponder.exchange();
await handshakeInitator.exchange();
await handshakeInitator.finish();
await handshakeResponder.finish();
const sessionInitator = handshakeInitator.session;
const sessionResponder = handshakeResponder.session;
// Test shared key
if (sessionInitator.cs1 && sessionResponder.cs1 && sessionInitator.cs2 && sessionResponder.cs2) {
assert(sessionInitator.cs1.k.equals(sessionResponder.cs1.k));
assert(sessionInitator.cs2.k.equals(sessionResponder.cs2.k));
} else {
assert(false);
}
// Test encryption and decryption
const encrypted = handshakeInitator.encrypt(Buffer.from("encryptthis"), handshakeInitator.session);
const decrypted = handshakeResponder.decrypt(encrypted, handshakeResponder.session);
assert(decrypted.equals(Buffer.from("encryptthis")));
} catch (e) {
assert(false, e.message);
2019-11-22 13:06:51 +01:00
}
});
2019-11-21 14:43:12 +01:00
});