From e53d002761a82959cd1a6d9c479713c04cdd0675 Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Mon, 25 May 2020 16:39:41 +0530 Subject: [PATCH 01/16] Added RemoteKeyClient and RemoteKeyHost and testcases for the same --- src/core/domain-services/index.ts | 1 + .../domain-services/remote-key-service.ts | 105 ++++++++++++++++++ .../crux-messenger/test-remote-key-client.ts | 68 ++++++++++++ 3 files changed, 174 insertions(+) create mode 100644 src/core/domain-services/remote-key-service.ts create mode 100644 src/test/crux-messenger/test-remote-key-client.ts diff --git a/src/core/domain-services/index.ts b/src/core/domain-services/index.ts index ed78b501..c9646e43 100644 --- a/src/core/domain-services/index.ts +++ b/src/core/domain-services/index.ts @@ -1 +1,2 @@ export * from "./crux-messenger"; +export * from "./remote-key-service"; diff --git a/src/core/domain-services/remote-key-service.ts b/src/core/domain-services/remote-key-service.ts new file mode 100644 index 00000000..4b2db916 --- /dev/null +++ b/src/core/domain-services/remote-key-service.ts @@ -0,0 +1,105 @@ +import {makeUUID4} from "blockstack/lib"; +import { CruxId } from "src/packages"; +import { IKeyManager } from "../interfaces"; +import { SecureCruxIdMessenger } from "./crux-messenger"; + +const VALID_METHODS = ["signWebToken", "getPubKey", "deriveSharedSecret", "decryptMessage"]; + +export class RemoteKeyClient { + private secureCruxIdMessenger: SecureCruxIdMessenger; + private remoteUserId: CruxId; + + constructor(secureCruxIdMessenger: SecureCruxIdMessenger, remoteUserId: CruxId) { + this.secureCruxIdMessenger = secureCruxIdMessenger; + this.remoteUserId = remoteUserId; + } + + public async invoke(method: string, args: any[]) { + if (!this.secureCruxIdMessenger) { + throw Error("RemoteKeyClient cannot send with no selfMessenger"); + } + const methodData = this.generateMethodData(method, args); + + await this.secureCruxIdMessenger.send(methodData, this.remoteUserId); + } + + public invokeResult = (resultCallback: (msg: any, senderId: CruxId | undefined) => any, errorCallback: (err: any) => any): void => { + if (!this.secureCruxIdMessenger) { + throw Error("RemoteKeyClient cannot listen with no selfMessenger"); + } + console.log("hello"); + this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => { + console.log("hello dope"); + resultCallback(msg, senderId); + }, (err: any) => { + errorCallback(err); + return; + }); + } + + private generateMethodData(method: string, args: any[]) { + return { + args, + invocationId: makeUUID4(), + method, + }; + } +} + +export class RemoteKeyHost { + private secureCruxIdMessenger: SecureCruxIdMessenger; + private keyManager: IKeyManager; + + constructor(secureCruxIdMessenger: SecureCruxIdMessenger, keyManager: IKeyManager) { + this.secureCruxIdMessenger = secureCruxIdMessenger; + this.keyManager = keyManager; + } + + public async sendInvocationResult(result: any, receiverId: CruxId) { + if (!this.secureCruxIdMessenger) { + throw Error("RemoteKeyClient cannot send with no selfMessenger"); + } + const resultData = this.generateInvocationResponse(result); + console.log(resultData); + await this.secureCruxIdMessenger.send(resultData, receiverId); + } + + public invocationListener = (resultCallback: (msg: any, senderId: CruxId | undefined) => any, errorCallback: (err: any) => any): void => { + if (!this.secureCruxIdMessenger) { + throw Error("RemoteKeyClient cannot listen with no selfMessenger"); + } + this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => { + this.handleMessage(msg); + resultCallback(msg, senderId); + }, (err: any) => { + errorCallback(err); + return; + }); + } + + public async handleMessage(message: any) { + if (!VALID_METHODS.includes(message.method)) { + throw new Error("Invalid key manager method"); + } + if (!this.keyManager) { + throw new Error("Key Manager not available"); + } + let data; + if (message.method === "signWebToken") { + data = await this.keyManager.signWebToken(message.agrs[0]); + } else if (message.method === "getPubKey") { + data = await this.keyManager.getPubKey(); + } + return { + data, + invocationId: message.invocationId, + }; + } + + private generateInvocationResponse(result: any) { + return { + invocationId: result.invocationId, + result, + }; + } +} diff --git a/src/test/crux-messenger/test-remote-key-client.ts b/src/test/crux-messenger/test-remote-key-client.ts new file mode 100644 index 00000000..34ce0478 --- /dev/null +++ b/src/test/crux-messenger/test-remote-key-client.ts @@ -0,0 +1,68 @@ +import * as chai from "chai"; +import sinon from "sinon"; +import chaiAsPromised from "chai-as-promised"; +import 'mocha'; +import {SecureCruxIdMessenger, RemoteKeyClient, RemoteKeyHost} from "../../core/domain-services"; +import {BasicKeyManager} from "../../infrastructure/implementations"; +import {CruxId} from "../../packages"; +import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies} from "../test-utils"; +import {InMemoryPubSubClientFactory, InMemoryMaliciousPubSubClientFactory} from "./inmemory-implementations"; +import {getMockUserBar123CSTestWallet, getMockUserFoo123CSTestWallet, getMockUserFooBar123CSTestWallet} from "./utils"; + +patchMissingDependencies(); + +chai.use(chaiAsPromised); +chai.should(); +const expect = require('chai').expect; + + +describe('Test RemoteKeyClient', function() { + beforeEach(async function() { + const userStore = new MockUserStore(); + const user1Data = getMockUserFoo123CSTestWallet(); + const user2Data = getMockUserBar123CSTestWallet(); + // const user3Data = getMockUserFooBar123CSTestWallet(); + this.user1Data = user1Data; + this.user2Data = user2Data; + // this.user3Data = user3Data; + userStore.store(user1Data.cruxUser); + userStore.store(user2Data.cruxUser); + this.inmemUserRepo = new InMemoryCruxUserRepository(userStore); + this.pubsubClientFactory = new InMemoryPubSubClientFactory(); + this.user1KeyManager = new BasicKeyManager(this.user1Data.pvtKey); + this.user2KeyManager = new BasicKeyManager(this.user2Data.pvtKey); + }); + + it('Basic Key Manager Send Receive', async function() { + const testPublicKey = '03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318'; + return new Promise(async (resolve, reject) => { + const remoteKeyClient = new RemoteKeyClient(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { + cruxId: this.user1Data.cruxUser.cruxID, + keyManager: this.user1KeyManager + }), this.user2Data.cruxUser.cruxID); + + const remoteKeyHost = new RemoteKeyHost(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { + cruxId: this.user2Data.cruxUser.cruxID, + keyManager: this.user2KeyManager + }), this.user2KeyManager); + + remoteKeyClient.invokeResult((msg, senderId) => { + expect(msg.result.data).equals(testPublicKey); + resolve(msg) + },(err) => { + reject(err) + }); + remoteKeyHost.invocationListener((msg, senderId) => { + if(msg.method === "getPubKey"){ + new Promise(async (resolve, reject) => { + const data = await remoteKeyHost.handleMessage(msg); + remoteKeyHost.sendInvocationResult(data, senderId); + resolve(); + }); + } + },(err) => { + }); + await remoteKeyClient.invoke("getPubKey", []); + }); + }); +}) From 6ad46721307dca37a0f9a08cb36be0c5f3bc189d Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Mon, 25 May 2020 20:54:02 +0530 Subject: [PATCH 02/16] added RemoteKeyManager and testcases for the same and added implementation for deriveSharedSecret,decryptMessage methods --- .../domain-services/remote-key-service.ts | 72 +++++++++++++++++- .../crux-messenger/test-remote-key-client.ts | 74 +++++++++++++++++-- 2 files changed, 134 insertions(+), 12 deletions(-) diff --git a/src/core/domain-services/remote-key-service.ts b/src/core/domain-services/remote-key-service.ts index 4b2db916..11e0d09c 100644 --- a/src/core/domain-services/remote-key-service.ts +++ b/src/core/domain-services/remote-key-service.ts @@ -27,9 +27,7 @@ export class RemoteKeyClient { if (!this.secureCruxIdMessenger) { throw Error("RemoteKeyClient cannot listen with no selfMessenger"); } - console.log("hello"); this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => { - console.log("hello dope"); resultCallback(msg, senderId); }, (err: any) => { errorCallback(err); @@ -69,7 +67,7 @@ export class RemoteKeyHost { throw Error("RemoteKeyClient cannot listen with no selfMessenger"); } this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => { - this.handleMessage(msg); + // this.handleMessage(msg); resultCallback(msg, senderId); }, (err: any) => { errorCallback(err); @@ -79,6 +77,7 @@ export class RemoteKeyHost { public async handleMessage(message: any) { if (!VALID_METHODS.includes(message.method)) { + // console.log("yolo"); throw new Error("Invalid key manager method"); } if (!this.keyManager) { @@ -86,9 +85,15 @@ export class RemoteKeyHost { } let data; if (message.method === "signWebToken") { - data = await this.keyManager.signWebToken(message.agrs[0]); + data = await this.keyManager.signWebToken(message.args[0]); } else if (message.method === "getPubKey") { data = await this.keyManager.getPubKey(); + } else if (message.method === "deriveSharedSecret") { + // @ts-ignore + data = await this.keyManager.deriveSharedSecret(message.args[0]); + } else if (message.method === "decryptMessage") { + // @ts-ignore + data = await this.keyManager.decryptMessage(message.args[0]); } return { data, @@ -103,3 +108,62 @@ export class RemoteKeyHost { }; } } + +export class RemoteKeyManager implements IKeyManager { + private remoteKeyClient: RemoteKeyClient; + private remoteUserId: CruxId; + + constructor(secureCruxIdMessenger: SecureCruxIdMessenger, remoteUserId: CruxId) { + this.remoteKeyClient = new RemoteKeyClient(secureCruxIdMessenger, remoteUserId); + this.remoteUserId = remoteUserId; + } + // @ts-ignore + public async signWebToken(token: any) { + const temp = [token]; + return new Promise(async (resolve, reject) => { + this.remoteKeyClient.invokeResult((msg, senderId) => { + console.log("sign+++====", msg); + resolve(msg.result.data); + }, (err) => { + reject(err); + }); + await this.remoteKeyClient.invoke("signWebToken", [token]); + }); + } + // @ts-ignore + public async getPubKey() { + return new Promise(async (resolve, reject) => { + this.remoteKeyClient.invokeResult((msg, senderId) => { + console.log("pub+++====", msg); + resolve(msg.result.data); + }, (err) => { + reject(err); + }); + await this.remoteKeyClient.invoke("getPubKey", []); + }); + } + // @ts-ignore + public async deriveSharedSecret(publicKey: string) { + return new Promise(async (resolve, reject) => { + this.remoteKeyClient.invokeResult((msg, senderId) => { + console.log("secret+++====", msg); + resolve(msg.result.data); + }, (err) => { + reject(err); + }); + await this.remoteKeyClient.invoke("deriveSharedSecret", [publicKey]); + }); + } + // @ts-ignore + public async decryptMessage(encryptedMessage: string) { + return new Promise(async (resolve, reject) => { + this.remoteKeyClient.invokeResult((msg, senderId) => { + console.log("decrypt+++====", msg); + resolve(msg.result.data); + }, (err) => { + reject(err); + }); + await this.remoteKeyClient.invoke("decryptMessage", [encryptedMessage]); + }); + } +} diff --git a/src/test/crux-messenger/test-remote-key-client.ts b/src/test/crux-messenger/test-remote-key-client.ts index 34ce0478..ef84b082 100644 --- a/src/test/crux-messenger/test-remote-key-client.ts +++ b/src/test/crux-messenger/test-remote-key-client.ts @@ -2,7 +2,7 @@ import * as chai from "chai"; import sinon from "sinon"; import chaiAsPromised from "chai-as-promised"; import 'mocha'; -import {SecureCruxIdMessenger, RemoteKeyClient, RemoteKeyHost} from "../../core/domain-services"; +import {SecureCruxIdMessenger, RemoteKeyClient, RemoteKeyHost, RemoteKeyManager} from "../../core/domain-services"; import {BasicKeyManager} from "../../infrastructure/implementations"; import {CruxId} from "../../packages"; import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies} from "../test-utils"; @@ -53,16 +53,74 @@ describe('Test RemoteKeyClient', function() { reject(err) }); remoteKeyHost.invocationListener((msg, senderId) => { - if(msg.method === "getPubKey"){ - new Promise(async (resolve, reject) => { - const data = await remoteKeyHost.handleMessage(msg); - remoteKeyHost.sendInvocationResult(data, senderId); - resolve(); - }); - } + new Promise(async (resolve, reject) => { + const data = await remoteKeyHost.handleMessage(msg); + remoteKeyHost.sendInvocationResult(data, senderId); + resolve(); + }); },(err) => { }); await remoteKeyClient.invoke("getPubKey", []); }); }); + + it('Invalid Basic Key Manager Send Receive ()', async function() { + const testErrorMsg = 'Invalid key manager method'; + return new Promise(async (resolve, reject) => { + const remoteKeyClient = new RemoteKeyClient(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { + cruxId: this.user1Data.cruxUser.cruxID, + keyManager: this.user1KeyManager + }), this.user2Data.cruxUser.cruxID); + + const remoteKeyHost = new RemoteKeyHost(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { + cruxId: this.user2Data.cruxUser.cruxID, + keyManager: this.user2KeyManager + }), this.user2KeyManager); + + remoteKeyHost.invocationListener(async (msg, senderId) => { + await expect(remoteKeyHost.handleMessage(msg)).to.be.rejectedWith(Error); + resolve(); + },(err) => { + }); + await remoteKeyClient.invoke("getPublicKey", []); + }); + }); + + it('Basic Key Manager Send Receive - RemoteKeyManager', async function() { + const testPubKey = "03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318"; + return new Promise(async (resolve, reject) => { + const remoteKeyManager = new RemoteKeyManager(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { + cruxId: this.user1Data.cruxUser.cruxID, + keyManager: this.user1KeyManager + }), this.user2Data.cruxUser.cruxID); + + const remoteKeyHost = new RemoteKeyHost(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { + cruxId: this.user2Data.cruxUser.cruxID, + keyManager: this.user2KeyManager + }), this.user2KeyManager); + + remoteKeyHost.invocationListener((msg, senderId) => { + new Promise(async (resolve, reject) => { + console.log(msg); + const data = await remoteKeyHost.handleMessage(msg); + remoteKeyHost.sendInvocationResult(data, senderId); + resolve(); + }); + },(err) => { + }); + const signedWebToken = await remoteKeyManager.signWebToken("1234567") + // console.log(signedWebToken); + expect(signedWebToken).to.have.length(138); + const publicKey = await remoteKeyManager.getPubKey(); + // console.log(publicKey); + expect(publicKey).to.equals(testPubKey); + const sharedSecret = await remoteKeyManager.deriveSharedSecret(testPubKey) + // console.log(sharedSecret); + expect(sharedSecret).to.equals("3380b4752c9cebf96bc55491ef0ee67ae1d564c0bb931a0c6e8875be6e3bee5"); + // const decryptedMessage = await remoteKeyManager.decryptMessage("4b4f34746f434c30354349312b41314b554f644542773d3d"); + // console.log(decryptedMessage); + // expect(decryptedMessage).to.equals(""); + resolve(); + }); + }); }) From 736638c9da5cb92eaa631e4b3b163bff7c7b135d Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Tue, 26 May 2020 14:35:30 +0530 Subject: [PATCH 03/16] defined message schema for RemoteKeyManager requests and responses --- .../implementations/crux-messenger.ts | 26 ++ .../test-key-management-protocol.ts | 273 ++++++++++++++++++ .../crux-messenger/test-remote-key-client.ts | 2 +- 3 files changed, 300 insertions(+), 1 deletion(-) create mode 100644 src/test/crux-messenger/test-key-management-protocol.ts diff --git a/src/infrastructure/implementations/crux-messenger.ts b/src/infrastructure/implementations/crux-messenger.ts index 9394fa61..3016423c 100644 --- a/src/infrastructure/implementations/crux-messenger.ts +++ b/src/infrastructure/implementations/crux-messenger.ts @@ -117,3 +117,29 @@ export const cruxPaymentProtocol: IMessageSchema[] = [{ .required().min(36).max(36), }), }]; + +export const keyManagementProtocol: IMessageSchema[] = [ + { + messageType: "KEY_MANAGER_REQUEST", + schema: Joi.object({ + args: Joi.array() + .required(), + + invocationId: Joi.string() + .required().min(36).max(36), + + method: Joi.string().valid("signWebToken", "getPubKey", "deriveSharedSecret", "decryptMessage") + .required(), + }), + }, + { + messageType: "KEY_MANAGER_RESPONSE", + schema: Joi.object({ + data: Joi.any() + .required(), + + invocationId: Joi.string() + .required().min(36).max(36), + }), + }, +]; diff --git a/src/test/crux-messenger/test-key-management-protocol.ts b/src/test/crux-messenger/test-key-management-protocol.ts new file mode 100644 index 00000000..cc6da230 --- /dev/null +++ b/src/test/crux-messenger/test-key-management-protocol.ts @@ -0,0 +1,273 @@ +import * as chai from "chai"; +import sinon from "sinon"; +import chaiAsPromised from "chai-as-promised"; +import 'mocha'; +import {SecureCruxIdMessenger, CertificateManager, CruxConnectProtocolMessenger} from "../../core/domain-services"; +import {ICruxUserRepository, IProtocolMessage, IPubSubClientFactory} from "../../core/interfaces"; +import {BasicKeyManager, cruxPaymentProtocol, keyManagementProtocol} from "../../infrastructure/implementations"; +import {CruxId} from "../../packages"; +import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies} from "../test-utils"; +import {InMemoryPubSubClientFactory, InMemoryMaliciousPubSubClientFactory} from "./inmemory-implementations"; +import {getMockUserBar123CSTestWallet, getMockUserFoo123CSTestWallet, getMockUserFooBar123CSTestWallet} from "./utils"; + +patchMissingDependencies(); + +chai.use(chaiAsPromised); +chai.should(); +const expect = require('chai').expect; + + + +describe('Test Key Management Protocol', function() { + beforeEach(async function() { + const userStore = new MockUserStore(); + const user1Data = getMockUserFoo123CSTestWallet(); + const user2Data = getMockUserBar123CSTestWallet(); + const user3Data = getMockUserFooBar123CSTestWallet(); + this.user1Data = user1Data; + this.user2Data = user2Data; + this.user3Data = user3Data; + userStore.store(user1Data.cruxUser); + userStore.store(user2Data.cruxUser); + const inmemUserRepo = new InMemoryCruxUserRepository(userStore); + const pubsubClientFactory = new InMemoryPubSubClientFactory(); + const user1Messenger = new SecureCruxIdMessenger(inmemUserRepo, pubsubClientFactory, { + cruxId: this.user1Data.cruxUser.cruxID, + keyManager: new BasicKeyManager(this.user1Data.pvtKey) + }); + const user2Messenger = new SecureCruxIdMessenger(inmemUserRepo, pubsubClientFactory, { + cruxId: this.user2Data.cruxUser.cruxID, + keyManager: new BasicKeyManager(this.user2Data.pvtKey) + }); + this.user1KeyManagerProtocolMessenger = new CruxConnectProtocolMessenger(user1Messenger, keyManagementProtocol); + this.user2KeyManagerProtocolMessenger = new CruxConnectProtocolMessenger(user2Messenger, keyManagementProtocol); + + }); + + describe('Test Key Management Protocol - (Request)', function() { + it('Valid Key Manager Request - Get Public Key', async function() { + return new Promise(async (res, rej) => { + const validKeyManagerRequest = { + args: [], + invocationId: '7c3baa3c-f5e8-490a-88a1-e0a052b7caa4', + method: "getPubKey" + } + const testMessage: IProtocolMessage = { + type: "KEY_MANAGER_REQUEST", + content: validKeyManagerRequest + } + const that = this; + this.user2KeyManagerProtocolMessenger.on('KEY_MANAGER_REQUEST', async (msg: any, senderId?: CruxId)=>{ + try { + expect(msg).to.deep.equal(validKeyManagerRequest); + expect(senderId!.toString()).equals(that.user1Data.cruxUser.cruxID.toString()); + } catch (e) { + rej(e) + } + res() + }, (err: any)=>{ + rej(err) + }); + await this.user1KeyManagerProtocolMessenger.send(testMessage, this.user2Data.cruxUser.cruxID) + }); + }); + it('Valid Key Manager Request - Sign Web Token', async function() { + return new Promise(async (res, rej) => { + const validKeyManagerRequest = { + args: ['webtoken'], + invocationId: '7c3baa3c-f5e8-490a-88a1-e0a052b7caa4', + method: "signWebToken" + } + const testMessage: IProtocolMessage = { + type: "KEY_MANAGER_REQUEST", + content: validKeyManagerRequest + } + const that = this; + this.user2KeyManagerProtocolMessenger.on('KEY_MANAGER_REQUEST', async (msg: any, senderId?: CruxId)=>{ + try { + expect(msg).to.deep.equal(validKeyManagerRequest); + expect(senderId!.toString()).equals(that.user1Data.cruxUser.cruxID.toString()); + } catch (e) { + rej(e) + } + res() + }, (err: any)=>{ + rej(err) + }); + await this.user1KeyManagerProtocolMessenger.send(testMessage, this.user2Data.cruxUser.cruxID) + }); + }); + it('Valid Key Manager Request - Derive Shared Secret', async function() { + const testPubKey = "03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318"; + return new Promise(async (res, rej) => { + const validKeyManagerRequest = { + args: [testPubKey], + invocationId: '7c3baa3c-f5e8-490a-88a1-e0a052b7caa4', + method: "deriveSharedSecret" + } + const testMessage: IProtocolMessage = { + type: "KEY_MANAGER_REQUEST", + content: validKeyManagerRequest + } + const that = this; + this.user2KeyManagerProtocolMessenger.on('KEY_MANAGER_REQUEST', async (msg: any, senderId?: CruxId)=>{ + try { + expect(msg).to.deep.equal(validKeyManagerRequest); + expect(senderId!.toString()).equals(that.user1Data.cruxUser.cruxID.toString()); + } catch (e) { + rej(e) + } + res() + }, (err: any)=>{ + rej(err) + }); + await this.user1KeyManagerProtocolMessenger.send(testMessage, this.user2Data.cruxUser.cruxID) + }); + }); + it('Valid Key Manager Request - Decrypt Message', async function() { + const testEncryptedMessage = "4b4f34746f434c30354349312b41314b554f644542773d3d" + return new Promise(async (res, rej) => { + const validKeyManagerRequest = { + args: [testEncryptedMessage], + invocationId: '7c3baa3c-f5e8-490a-88a1-e0a052b7caa4', + method: "decryptMessage" + } + const testMessage: IProtocolMessage = { + type: "KEY_MANAGER_REQUEST", + content: validKeyManagerRequest + } + const that = this; + this.user2KeyManagerProtocolMessenger.on('KEY_MANAGER_REQUEST', async (msg: any, senderId?: CruxId)=>{ + try { + expect(msg).to.deep.equal(validKeyManagerRequest); + expect(senderId!.toString()).equals(that.user1Data.cruxUser.cruxID.toString()); + } catch (e) { + rej(e) + } + res() + }, (err: any)=>{ + rej(err) + }); + await this.user1KeyManagerProtocolMessenger.send(testMessage, this.user2Data.cruxUser.cruxID) + }); + }); + it('Invalid Key Manager Request - Wrong method', async function() { + const invalidKeyManagerRequest = { + args: ['token'], + invocationId: '7c3baa3c-f5e8-490a-88a1-e0a052b7caa4', + method: "getPublicKey" + } + const testMessage: IProtocolMessage = { + type: "KEY_MANAGER_REQUEST", + content: invalidKeyManagerRequest + } + const promise = this.user1KeyManagerProtocolMessenger.send(testMessage, this.user2Data.cruxUser.cruxID); + return expect(promise).to.be.eventually.rejected; + }); + }); + + describe('Test Key Management Protocol - (Response)', function() { + it('Valid Key Manager Response - String output', async function() { + return new Promise(async (res, rej) => { + const validKeyManagerResponse = { + data: "03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318", + invocationId: '7c3baa3c-f5e8-490a-88a1-e0a052b7caa4', + } + const testMessage: IProtocolMessage = { + type: "KEY_MANAGER_RESPONSE", + content: validKeyManagerResponse + } + const that = this; + this.user2KeyManagerProtocolMessenger.on('KEY_MANAGER_RESPONSE', async (msg: any, senderId?: CruxId)=>{ + try { + expect(msg).to.deep.equal(validKeyManagerResponse); + expect(senderId!.toString()).equals(that.user1Data.cruxUser.cruxID.toString()); + } catch (e) { + rej(e) + } + res() + }, (err: any)=>{ + rej(err) + }); + await this.user1KeyManagerProtocolMessenger.send(testMessage, this.user2Data.cruxUser.cruxID) + }); + }); + it('Valid Key Manager Response - Object Output', async function() { + return new Promise(async (res, rej) => { + const validKeyManagerResponse = { + data: [{ + 'webtoken': "hello" + }], + invocationId: '7c3baa3c-f5e8-490a-88a1-e0a052b7caa4' + } + const testMessage: IProtocolMessage = { + type: "KEY_MANAGER_RESPONSE", + content: validKeyManagerResponse + } + const that = this; + this.user2KeyManagerProtocolMessenger.on('KEY_MANAGER_RESPONSE', async (msg: any, senderId?: CruxId)=>{ + try { + expect(msg).to.deep.equal(validKeyManagerResponse); + expect(senderId!.toString()).equals(that.user1Data.cruxUser.cruxID.toString()); + } catch (e) { + rej(e) + } + res() + }, (err: any)=>{ + rej(err) + }); + await this.user1KeyManagerProtocolMessenger.send(testMessage, this.user2Data.cruxUser.cruxID) + }); + }); + it('Valid Key Manager Response - Array Output', async function() { + return new Promise(async (res, rej) => { + const validKeyManagerResponse = { + data: ['webtoken'], + invocationId: '7c3baa3c-f5e8-490a-88a1-e0a052b7caa4' + } + const testMessage: IProtocolMessage = { + type: "KEY_MANAGER_RESPONSE", + content: validKeyManagerResponse + } + const that = this; + this.user2KeyManagerProtocolMessenger.on('KEY_MANAGER_RESPONSE', async (msg: any, senderId?: CruxId)=>{ + try { + expect(msg).to.deep.equal(validKeyManagerResponse); + expect(senderId!.toString()).equals(that.user1Data.cruxUser.cruxID.toString()); + } catch (e) { + rej(e) + } + res() + }, (err: any)=>{ + rej(err) + }); + await this.user1KeyManagerProtocolMessenger.send(testMessage, this.user2Data.cruxUser.cruxID) + }); + }); + + it('Invalid Key Manager Response - Missing data', async function() { + const validKeyManagerResponse = { + invocationId: '7c3baa3c-f5e8-490a-88a1-e0a052b7caa4' + } + const testMessage: IProtocolMessage = { + type: "KEY_MANAGER_RESPONSE", + content: validKeyManagerResponse + } + const promise = this.user1KeyManagerProtocolMessenger.send(testMessage, this.user2Data.cruxUser.cruxID); + return expect(promise).to.be.eventually.rejected; + }); + it('Invalid Key Manager Response - invocationId wrong length', async function() { + const validKeyManagerResponse = { + data: ['webtoken'], + invocationId: '7c3baa3c-f5e8-490a-88a1-e0a02b7caa4' + } + const testMessage: IProtocolMessage = { + type: "KEY_MANAGER_RESPONSE", + content: validKeyManagerResponse + } + const promise = this.user1KeyManagerProtocolMessenger.send(testMessage, this.user2Data.cruxUser.cruxID); + return expect(promise).to.be.eventually.rejected; + }); + }); + +}) diff --git a/src/test/crux-messenger/test-remote-key-client.ts b/src/test/crux-messenger/test-remote-key-client.ts index ef84b082..02b46ac2 100644 --- a/src/test/crux-messenger/test-remote-key-client.ts +++ b/src/test/crux-messenger/test-remote-key-client.ts @@ -64,7 +64,7 @@ describe('Test RemoteKeyClient', function() { }); }); - it('Invalid Basic Key Manager Send Receive ()', async function() { + it('Invalid Basic Key Manager Send Receive (wrong method)', async function() { const testErrorMsg = 'Invalid key manager method'; return new Promise(async (resolve, reject) => { const remoteKeyClient = new RemoteKeyClient(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { From 2d8519c415b489f51ee8c95b61f0cf812d79794c Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Wed, 27 May 2020 17:44:25 +0530 Subject: [PATCH 04/16] added test for CruxServiceClient --- .vscode/launch.json | 2 +- .vscode/settings.json | 2 +- package.json | 2 +- .../clients/crux-service-client.ts | 14 +++ src/application/clients/crux-wallet-client.ts | 41 +++++-- src/application/clients/index.ts | 1 + src/core/domain-services/crux-messenger.ts | 10 ++ .../domain-services/remote-key-service.ts | 38 ++++-- src/core/entities/crux-user.ts | 1 + .../implementations/basic-key-manager.ts | 3 + .../blockstack-crux-user-repository.ts | 9 +- .../implementations/crux-messenger.ts | 4 +- .../test-crux-service-client-prod.ts | 114 ++++++++++++++++++ .../crux-messenger/test-remote-key-client.ts | 6 +- 14 files changed, 224 insertions(+), 23 deletions(-) create mode 100644 src/application/clients/crux-service-client.ts create mode 100644 src/test/crux-messenger/test-crux-service-client-prod.ts diff --git a/.vscode/launch.json b/.vscode/launch.json index e9df9d25..3b9fd80c 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -22,7 +22,7 @@ "jsdom-global/register", "--allow-uncaught", "--colors", - "--timeout 5000", + "--timeout 50000", // "--reporter", // "mocha-reporter", "${workspaceFolder}/src/test/*.ts" diff --git a/.vscode/settings.json b/.vscode/settings.json index 19adfd71..157d7095 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -6,7 +6,7 @@ }, "mochaExplorer.files": ["src/test/*.ts", "src/test/crux-messenger/*.ts"], "mochaExplorer.require": ["ts-node/register", "mock-local-storage", "jsdom-global/register"], - "mochaExplorer.timeout": 5000, + "mochaExplorer.timeout": 80000, "testExplorer.codeLens": true, "testExplorer.gutterDecoration": true, "testExplorer.onStart": "reset", diff --git a/package.json b/package.json index e9a376ab..a2b79732 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "main": "lib/index.js", "types": "lib/index.d.ts", "scripts": { - "test": "TS_NODE_PROJECT='./src/test/tsconfig.commonjs.json' TS_NODE_TRANSPILE_ONLY=true ./node_modules/.bin/mocha --exit --require ts-node/register --require mock-local-storage --require jsdom-global/register --allow-uncaught --colors --reporter mocha-reporter --timeout 5000 src/test/*.ts src/test/crux-messenger/*.ts", + "test": "TS_NODE_PROJECT='./src/test/tsconfig.commonjs.json' TS_NODE_TRANSPILE_ONLY=true ./node_modules/.bin/mocha --exit --require ts-node/register --require mock-local-storage --require jsdom-global/register --allow-uncaught --colors --reporter mocha-reporter --timeout 50000 src/test/*.ts src/test/crux-messenger/*.ts", "start-bridge-server": "node dist/crux-gateway-bridge-without-auth.js &", "stop-bridge-server": "pkill -- signal SIGINT crux-gateway-bridge-server-without-auth", "integration-test": "TS_NODE_PROJECT='./src/test/tsconfig.commonjs.json' TS_NODE_TRANSPILE_ONLY=true ./node_modules/.bin/mocha --exit --require ts-node/register --require mock-local-storage --require jsdom-global/register --allow-uncaught --colors --reporter mocha-reporter --timeout 50000 src/test/integration-tests/crux-messenger/*.ts", diff --git a/src/application/clients/crux-service-client.ts b/src/application/clients/crux-service-client.ts new file mode 100644 index 00000000..30253d6e --- /dev/null +++ b/src/application/clients/crux-service-client.ts @@ -0,0 +1,14 @@ +import { CruxId } from "src/packages"; +import { RemoteKeyManager, SecureCruxIdMessenger } from "../../core/domain-services"; +import { CruxWalletClient } from "./crux-wallet-client"; + +export class CruxServiceClient { + + public getWalletClientForUser(secureCruxIdMessenger: SecureCruxIdMessenger, remoteUserId: CruxId) { + console.log("Hd"); + return new CruxWalletClient({ + privateKey: new RemoteKeyManager(secureCruxIdMessenger, remoteUserId), + walletClientName: remoteUserId.components.domain, + }); + } +} diff --git a/src/application/clients/crux-wallet-client.ts b/src/application/clients/crux-wallet-client.ts index 2c1fba37..21eacc61 100644 --- a/src/application/clients/crux-wallet-client.ts +++ b/src/application/clients/crux-wallet-client.ts @@ -1,6 +1,6 @@ // Importing packages import Logger from "js-logger"; -import {CruxConnectProtocolMessenger, SecureCruxIdMessenger} from "../../core/domain-services"; +import {CruxConnectProtocolMessenger, SecureCruxIdMessenger, RemoteKeyHost} from "../../core/domain-services"; import { CruxDomain, CruxSpec, @@ -79,6 +79,7 @@ export interface ICruxWalletClientOptions { cacheStorage?: StorageService; walletClientName: string; debugLogging?: boolean; + isHost?: boolean; } export interface ICruxIDState { @@ -114,6 +115,7 @@ export class CruxWalletClient { private cacheStorage?: StorageService; private selfCruxUser?: CruxUser; private paymentProtocolMessenger?: CruxConnectProtocolMessenger; + private remoteKeyHost?: RemoteKeyHost; constructor(options: ICruxWalletClientOptions) { getLogger(cruxWalletClientDebugLoggerName).setLevel(options.debugLogging ? Logger.DEBUG : Logger.OFF); @@ -122,6 +124,7 @@ export class CruxWalletClient { this.walletClientName = options.walletClientName; if (options.privateKey) { if (typeof options.privateKey === "string") { + console.log("================", options.privateKey); this.keyManager = new BasicKeyManager(options.privateKey); } else if (isInstanceOfKeyManager(options.privateKey)) { this.keyManager = options.privateKey; @@ -131,7 +134,7 @@ export class CruxWalletClient { } this.cruxDomainRepo = getCruxDomainRepository({cacheStorage: this.cacheStorage, blockstackInfrastructure: this.cruxBlockstackInfrastructure}); this.cruxDomainId = new CruxDomainId(this.walletClientName); - this.initPromise = this.asyncInit(); + this.initPromise = this.asyncInit(options); } @throwCruxClientError @@ -197,9 +200,16 @@ export class CruxWalletClient { @throwCruxClientError public getAddressMap = async (): Promise => { - await this.initPromise; + console.log("LMAO"); + console.log("Hieeee", this.getKeyManager()); + // await this.initPromise; + console.log("after promise"); + console.log("Hoilaaaaaa", await this.getKeyManager().getPubKey()); + console.log("Aloha"); const cruxUser = await this.cruxUserRepository.getWithKey(this.getKeyManager()); + console.log("&&&&&&{}{}", cruxUser); if (cruxUser) { + console.log("dude"); const assetIdAddressMap = cruxUser.getAddressMap(); return this.cruxAssetTranslator.assetIdAddressMapToSymbolAddressMap(assetIdAddressMap); } @@ -392,17 +402,19 @@ export class CruxWalletClient { return this.cruxDomain; } - private asyncInit = async (): Promise => { + private asyncInit = async (options: ICruxWalletClientOptions): Promise => { this.cruxDomain = await this.cruxDomainRepo.get(this.cruxDomainId); if (!this.cruxDomain) { throw ErrorHelper.getPackageError(null, PackageErrorCode.InvalidWalletClientName); } + console.log("YOLO"); this.cruxUserRepository = getCruxUserRepository({cacheStorage: this.cacheStorage, blockstackInfrastructure: this.cruxBlockstackInfrastructure, cruxDomain: this.cruxDomain}); if (!this.cruxDomain.config) { throw ErrorHelper.getPackageError(null, PackageErrorCode.CouldNotFindBlockstackConfigurationServiceClientConfig); } + console.log("Bol"); this.cruxAssetTranslator = new CruxAssetTranslator(this.cruxDomain.config.assetMapping, this.cruxDomain.config.assetList); - // await this.setupCruxMessenger(); + await this.setupCruxMessenger(options); } private getSelfClaim = async (): Promise => { @@ -421,17 +433,30 @@ export class CruxWalletClient { } return selfClaim; } - private setupCruxMessenger = async () => { + private setupCruxMessenger = async (options: ICruxWalletClientOptions) => { const selfIdClaim = await this.getSelfClaim(); if (!selfIdClaim) { throw Error("Self ID Claim is required to setup messenger"); } const pubsubClientFactory = new CruxNetPubSubClientFactory({defaultLinkServer: { - host: "localhost", - port: 4005, + host: "127.0.0.1", + port: 1883, }}); const secureCruxMessenger = new SecureCruxIdMessenger(this.cruxUserRepository, pubsubClientFactory, selfIdClaim); this.paymentProtocolMessenger = new CruxConnectProtocolMessenger(secureCruxMessenger, cruxPaymentProtocol); + if (options.isHost) { + const remoteKeyHost = new RemoteKeyHost(secureCruxMessenger, this.keyManager!); + this.remoteKeyHost = remoteKeyHost; + console.log("setupRemoteKeyHost__________", selfIdClaim.cruxId.toString()); + remoteKeyHost.invocationListener(async (msg, senderId) => { + console.log("%%%%%%%%%%%%%", msg, senderId); + const data = await remoteKeyHost.handleMessage(msg); + remoteKeyHost.sendInvocationResult(data, senderId); + }, (err) => { + console.log("[][][][", err); + remoteKeyHost.sendInvocationResult(err, senderId); + }); + } } } diff --git a/src/application/clients/index.ts b/src/application/clients/index.ts index a1346961..d16e255a 100644 --- a/src/application/clients/index.ts +++ b/src/application/clients/index.ts @@ -1,3 +1,4 @@ export * from "./crux-explorer-client"; export * from "./crux-wallet-client"; export * from "./crux-wallet-onboarding"; +export * from "./crux-service-client"; diff --git a/src/core/domain-services/crux-messenger.ts b/src/core/domain-services/crux-messenger.ts index d1ed59f3..50a88257 100644 --- a/src/core/domain-services/crux-messenger.ts +++ b/src/core/domain-services/crux-messenger.ts @@ -20,6 +20,8 @@ import { export class CertificateManager { public static make = async (idClaim: ICruxIdClaim): Promise => { const payload = idClaim.cruxId.toString(); + console.log("%&%&%&%&%", idClaim.keyManager); + console.log(payload); const signedProof = await idClaim.keyManager.signWebToken(payload); return { claim: idClaim.cruxId.toString(), @@ -28,7 +30,9 @@ export class CertificateManager { } public static verify = (certificate: ICruxIdCertificate, senderPubKey: any) => { const proof: any = decodeToken(certificate.proof).payload; + console.log(":::::::::;", certificate.claim, proof, senderPubKey); const verified = new TokenVerifier("ES256K", senderPubKey).verify(certificate.proof); + console.log("&*&**&*&", verified, certificate.claim, proof); if (proof && proof === certificate.claim && verified) { return true; } @@ -140,7 +144,9 @@ export class SecureCruxIdMessenger { // TODO: Do we need to validate selfIdClaim? } public send = async (data: any, recipientCruxId: CruxId): Promise => { + console.log("inside send: ", recipientCruxId.toString()); const recipientCruxUser: CruxUser | undefined = await this.cruxUserRepo.getByCruxId(recipientCruxId); + console.log("~~~~~~~", recipientCruxUser); if (!recipientCruxUser) { throw Error("No Such CRUX User Found"); } @@ -162,6 +168,7 @@ export class SecureCruxIdMessenger { } this.selfMessenger.on(EventBusEventNames.newMessage, async (encryptedString: string) => { try { + console.log("inside listen and on :::::"); const serializedSecurePacket: string = await EncryptionManager.decrypt(encryptedString, this.selfIdClaim!.keyManager); const securePacket: ISecurePacket = JSON.parse(serializedSecurePacket); let senderUser: CruxUser | undefined; @@ -172,6 +179,8 @@ export class SecureCruxIdMessenger { return; } const isVerified = CertificateManager.verify(securePacket.certificate, senderUser.publicKey!); + console.log("********", securePacket.certificate); + console.log("??????????", senderUser.publicKey); if (!isVerified) { errorCallback(new Error("Could not validate identity")); return; @@ -179,6 +188,7 @@ export class SecureCruxIdMessenger { } newMessageCallback(securePacket.data, senderUser ? senderUser.cruxID : undefined); } catch (error) { + console.log("listen on error", error); errorCallback(error); return; } diff --git a/src/core/domain-services/remote-key-service.ts b/src/core/domain-services/remote-key-service.ts index 11e0d09c..b0233e48 100644 --- a/src/core/domain-services/remote-key-service.ts +++ b/src/core/domain-services/remote-key-service.ts @@ -1,4 +1,5 @@ import {makeUUID4} from "blockstack/lib"; +import { createNanoEvents, DefaultEvents, Emitter } from "nanoevents"; import { CruxId } from "src/packages"; import { IKeyManager } from "../interfaces"; import { SecureCruxIdMessenger } from "./crux-messenger"; @@ -8,19 +9,30 @@ const VALID_METHODS = ["signWebToken", "getPubKey", "deriveSharedSecret", "decry export class RemoteKeyClient { private secureCruxIdMessenger: SecureCruxIdMessenger; private remoteUserId: CruxId; + private emitter: Emitter; constructor(secureCruxIdMessenger: SecureCruxIdMessenger, remoteUserId: CruxId) { this.secureCruxIdMessenger = secureCruxIdMessenger; this.remoteUserId = remoteUserId; + this.emitter = createNanoEvents(); + this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => { + console.log("inside invokeresult::::::", msg, senderId); + this.emitter.emit(msg.invocationId, msg, senderId); + }, (err: any) => { + this.emitter.emit("error", err); + return; + }); } public async invoke(method: string, args: any[]) { + console.log("inside Invoke::::::"); if (!this.secureCruxIdMessenger) { throw Error("RemoteKeyClient cannot send with no selfMessenger"); } const methodData = this.generateMethodData(method, args); - + console.log("^^^^^^", this.remoteUserId, methodData); await this.secureCruxIdMessenger.send(methodData, this.remoteUserId); + return methodData.invocationId; } public invokeResult = (resultCallback: (msg: any, senderId: CruxId | undefined) => any, errorCallback: (err: any) => any): void => { @@ -28,6 +40,7 @@ export class RemoteKeyClient { throw Error("RemoteKeyClient cannot listen with no selfMessenger"); } this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => { + console.log("inside invokeresult::::::", msg, senderId); resultCallback(msg, senderId); }, (err: any) => { errorCallback(err); @@ -35,6 +48,14 @@ export class RemoteKeyClient { }); } + public listenToInvocation = (invocationId: string, resultCallback: (msg: any, senderId: CruxId | undefined) => any, errorCallback: (err: any) => any): void => { + if (!this.secureCruxIdMessenger) { + throw Error("RemoteKeyClient cannot listen with no selfMessenger"); + } + this.emitter.on(invocationId, resultCallback); + this.emitter.on("error", errorCallback); + } + private generateMethodData(method: string, args: any[]) { return { args, @@ -68,8 +89,10 @@ export class RemoteKeyHost { } this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => { // this.handleMessage(msg); + console.log("#####", msg, senderId); resultCallback(msg, senderId); }, (err: any) => { + console.log("errorinvocationListener", err); errorCallback(err); return; }); @@ -119,27 +142,30 @@ export class RemoteKeyManager implements IKeyManager { } // @ts-ignore public async signWebToken(token: any) { + console.log("Boli"); const temp = [token]; return new Promise(async (resolve, reject) => { - this.remoteKeyClient.invokeResult((msg, senderId) => { + const invocationId = await this.remoteKeyClient.invoke("signWebToken", [token]); + this.remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { console.log("sign+++====", msg); resolve(msg.result.data); }, (err) => { reject(err); }); - await this.remoteKeyClient.invoke("signWebToken", [token]); }); } // @ts-ignore public async getPubKey() { + console.log("Holi"); return new Promise(async (resolve, reject) => { - this.remoteKeyClient.invokeResult((msg, senderId) => { + const invocationId = await this.remoteKeyClient.invoke("getPubKey", []); + this.remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { console.log("pub+++====", msg); resolve(msg.result.data); }, (err) => { reject(err); }); - await this.remoteKeyClient.invoke("getPubKey", []); + console.log("getPubKey:Method"); }); } // @ts-ignore @@ -151,7 +177,6 @@ export class RemoteKeyManager implements IKeyManager { }, (err) => { reject(err); }); - await this.remoteKeyClient.invoke("deriveSharedSecret", [publicKey]); }); } // @ts-ignore @@ -163,7 +188,6 @@ export class RemoteKeyManager implements IKeyManager { }, (err) => { reject(err); }); - await this.remoteKeyClient.invoke("decryptMessage", [encryptedMessage]); }); } } diff --git a/src/core/entities/crux-user.ts b/src/core/entities/crux-user.ts index 5a68f730..b3ea1b67 100644 --- a/src/core/entities/crux-user.ts +++ b/src/core/entities/crux-user.ts @@ -72,6 +72,7 @@ export class CruxUser { this.setCruxUserConfig(cruxUserData.configuration); this.setPublicKey(publicKey); this.setCruxUserPrivateAddresses(cruxUserData.privateAddresses); + console.log("CruxUser initialised"); log.debug("CruxUser initialised"); } get cruxID() { diff --git a/src/infrastructure/implementations/basic-key-manager.ts b/src/infrastructure/implementations/basic-key-manager.ts index 27901749..0d0f361b 100644 --- a/src/infrastructure/implementations/basic-key-manager.ts +++ b/src/infrastructure/implementations/basic-key-manager.ts @@ -20,11 +20,13 @@ export class BasicKeyManager implements IKeyManager { public signWebToken = async (payload: any): Promise => { await this.initPromise; let privateKey = await this.getDecryptedPrivateKey(); + console.log("privateKey: ", privateKey); const signedMsg = new TokenSigner("ES256K", privateKey).sign(payload); privateKey = "0".repeat(privateKey.length); return signedMsg; } public getPubKey = async (): Promise => { + console.log("*()"); await this.initPromise; return this.publicKey; } @@ -52,6 +54,7 @@ export class BasicKeyManager implements IKeyManager { encryptionConstant = getRandomHexString(); this.ephemeralEncryptionConstant = encryptionConstant; } + console.log("&&*&*&", privateKey); const keyPair = getKeyPairFromPrivKey(privateKey); this.publicKey = keyPair.pubKey; this.encryptedPrivateKey = JSON.stringify(await Encryption.encryptText(keyPair.privKey, encryptionConstant)); diff --git a/src/infrastructure/implementations/blockstack-crux-user-repository.ts b/src/infrastructure/implementations/blockstack-crux-user-repository.ts index b24086e7..7be06363 100644 --- a/src/infrastructure/implementations/blockstack-crux-user-repository.ts +++ b/src/infrastructure/implementations/blockstack-crux-user-repository.ts @@ -13,6 +13,7 @@ import { cloneValue } from "../../packages/utils"; import { BlockstackService } from "../services/blockstack-service"; import { GaiaService } from "../services/gaia-service"; import { BlockstackCruxDomainRepository } from "./blockstack-crux-domain-repository"; +import { keyManagementProtocol } from "./crux-messenger"; const log = getLogger(__filename); export interface ICruxpayObject { @@ -72,10 +73,12 @@ export class BlockstackCruxUserRepository implements ICruxUserRepository { return this.blockstackService.isCruxIdAvailable(this.getCruxIdFromSubdomain(cruxIdSubdomain)); } public getByCruxId = async (cruxID: CruxId, tag?: string, onlyRegistered: boolean = false): Promise => { + console.log("inside getByCruxId::::::"); const cruxUserInformation = await this.blockstackService.getCruxIdInformation(cruxID, tag, onlyRegistered); if (cruxUserInformation.registrationStatus.status === SubdomainRegistrationStatus.NONE) { return; } + console.log("+++$$$$$", cruxUserInformation); let addressMap = {}; let cruxUserData: ICruxUserData = { configuration: { @@ -95,10 +98,13 @@ export class BlockstackCruxUserRepository implements ICruxUserRepository { cruxUserData = dereferencedCruxpayObject.cruxUserData; } } + console.log("$$$$#####$$", cruxUserInformation); return new CruxUser(cruxID.components.subdomain, await this.getUserCruxDomain(cruxID) as CruxDomain, addressMap, cruxUserInformation, cruxUserData, cruxpayPubKey); } - public getWithKey = async (keyManager: IKeyManager): Promise => { + public getWithKey = async (keyManager: IKeyManager): Promise => { + console.log("+++@@@@@@@", await keyManager.getPubKey()); const cruxID = await this.blockstackService.getCruxIdWithKeyManager(keyManager, this.getCruxDomain().id); + console.log("*()(*()(*()", cruxID); if (!cruxID) { return; } @@ -125,6 +131,7 @@ export class BlockstackCruxUserRepository implements ICruxUserRepository { cruxUserData = dereferencedCruxpayObject.cruxUserData; } } + console.log("holo"); return new CruxUser(cruxID.components.subdomain, this.getCruxDomain(), addressMap, cruxUserInformation, cruxUserData, cruxpayPubKey); } public save = async (cruxUser: CruxUser, keyManager: IKeyManager): Promise => { diff --git a/src/infrastructure/implementations/crux-messenger.ts b/src/infrastructure/implementations/crux-messenger.ts index 3016423c..f0bd0368 100644 --- a/src/infrastructure/implementations/crux-messenger.ts +++ b/src/infrastructure/implementations/crux-messenger.ts @@ -41,10 +41,12 @@ export class StrongPubSubClient implements IPubSubClient { } public publish(topic: string, data: any): void { this.ensureClient(); + console.log("Message Published: ", topic, data); this.client.publish(topic, data); } public subscribe(topic: string, callback: any): void { this.ensureClient(); + console.log("SUBSCRIBED", topic); this.client.subscribe(topic, this.config.subscribeOptions); this.client.on("message", callback); } @@ -65,7 +67,7 @@ export class CruxNetPubSubClientFactory implements IPubSubClientFactory { constructor(options: ICruxNetClientFactoryOptions) { this.options = options; this.defaultSubscribeOptions = { - qos: 0, + qos: 2, }; this.defaultClientMqttOptions = { clean: false, diff --git a/src/test/crux-messenger/test-crux-service-client-prod.ts b/src/test/crux-messenger/test-crux-service-client-prod.ts new file mode 100644 index 00000000..30db5da8 --- /dev/null +++ b/src/test/crux-messenger/test-crux-service-client-prod.ts @@ -0,0 +1,114 @@ +import * as chai from "chai"; +import * as blockstack from "blockstack"; +import sinon from "sinon"; +import chaiAsPromised from "chai-as-promised"; +import 'mocha'; +import * as elliptic from "elliptic"; +import Client from "strong-pubsub"; +import MqttAdapter from "strong-pubsub-mqtt"; +import {SecureCruxIdMessenger, RemoteKeyClient, RemoteKeyHost, RemoteKeyManager} from "../../core/domain-services"; +import {CruxServiceClient, getCruxUserRepository, CruxWalletClient} from "../../application/clients" +import {BasicKeyManager, CruxNetPubSubClientFactory, StrongPubSubClient} from "../../infrastructure/implementations"; +import {patchMissingDependencies, getCruxdevCruxDomain} from "../test-utils"; +import { CruxSpec } from "../../core/entities"; +import {IKeyManager} from "../../core/interfaces"; +import { CruxId } from "../../packages"; +import { bip32 } from "bitcoinjs-lib"; +import * as bip39 from "bip39"; + +patchMissingDependencies(); + +chai.use(chaiAsPromised); +chai.should(); +const expect = require('chai').expect; + +const user1PvtKey = "cdf2d276caf0c9c34258ed6ebd0e60e0e8b3d9a7b8a9a717f2e19ed9b37f7c6f"; // mascot6699@cruxdex.crux +// const user2PvtKey = "KyBuSe1MMV6NjJgZfyWuvgmxUeAYswLC2HrfYLUri9aP3AS5FBfr"; // release020@cruxdev.crux + +var EC = elliptic.ec; +const curve = new EC("secp256k1"); + +const _generateMnemonic = (): string => { + return blockstack.BlockstackWallet.generateMnemonic(); +} + +const _generateIdentityKeyPair = async (mnemonic: string): Promise => { + const wallet = new blockstack.BlockstackWallet(bip32.fromSeed(bip39.mnemonicToSeedSync(mnemonic))); + const { address, key, keyID} = wallet.getIdentityKeyPair(0); + const identityKeyPair: any = { + address, + privKey: key, + pubKey: keyID, + }; + return identityKeyPair; +} + +describe('Test CruxServiceClient', function() { + beforeEach(async function() { + const HOST = "127.0.0.1"; + const PORT = 1883; + const newMnemonic = _generateMnemonic(); + const identityKeyPair = await _generateIdentityKeyPair(newMnemonic); + console.log("+++++()()()", identityKeyPair); + // const keyPair = curve.genKeyPair(); + // console.log(keyPair.getPublic('hex')); + this.user2CruxId = "release020@cruxdev.crux"; + this.user1KeyManager = new BasicKeyManager(user1PvtKey); + console.log("!!!", this.user1KeyManager); + this.user2KeyManager = new BasicKeyManager(identityKeyPair.privKey); + console.log("===", this.user2KeyManager); + this.userRepo = getCruxUserRepository({ + blockstackInfrastructure: CruxSpec.blockstack.infrastructure, + cruxDomain: getCruxdevCruxDomain() + }); + this.user1Data = await this.userRepo.getWithKey(this.user1KeyManager); + this.pubsubClientFactory = new CruxNetPubSubClientFactory({ + defaultLinkServer: { + host: HOST, + port: PORT, + } + }); + this.subscriberUserName = "release020@cruxdev.crux"; + this.subscriberConfig = { + clientOptions: { + host: HOST, + port: PORT, + mqtt: { + clean: false, + clientId: this.subscriberUserName, + }, + }, + subscribeOptions: { + qos: 2, + } + }; + this.subscriber = new StrongPubSubClient(this.subscriberConfig); + this.client = new Client(this.subscriberConfig.clientOptions, MqttAdapter); + }); + it('Basic Key Manager Send Receive - CruxServiceClient', async function() { + const cruxWalletClient = new CruxWalletClient({ + privateKey: user1PvtKey, + walletClientName: "cruxdev", + isHost: true, + }); + // const user1Messenger = new SecureCruxIdMessenger(this.userRepo, this.pubsubClientFactory, { + // cruxId: this.user1Data.cruxID, + // keyManager: new BasicKeyManager(user1PvtKey) + // }); + // new Promise(async (resolve, reject) => { + // this.client.subscribe("topic_mascot6699@cruxdev.crux", this.subscriberConfig.subscribeOptions); + // this.client.on("message", (topic, msg) => { + // console.log("--------------", topic, msg) + // resolve(); + // }); + // }); + const cruxServiceClient = new CruxServiceClient(); + const serviceWalletClient = cruxServiceClient.getWalletClientForUser(new SecureCruxIdMessenger(this.userRepo, this.pubsubClientFactory, { + cruxId: CruxId.fromString(this.user2CruxId), + keyManager: this.user2KeyManager + }), this.user1Data.cruxID); + console.log("++++++$$#####", serviceWalletClient); + console.log("=======++++++++", await serviceWalletClient.getAddressMap()); + console.log("@@@@@"); + }); +}); \ No newline at end of file diff --git a/src/test/crux-messenger/test-remote-key-client.ts b/src/test/crux-messenger/test-remote-key-client.ts index 02b46ac2..28accce7 100644 --- a/src/test/crux-messenger/test-remote-key-client.ts +++ b/src/test/crux-messenger/test-remote-key-client.ts @@ -109,13 +109,13 @@ describe('Test RemoteKeyClient', function() { },(err) => { }); const signedWebToken = await remoteKeyManager.signWebToken("1234567") - // console.log(signedWebToken); + console.log(signedWebToken); expect(signedWebToken).to.have.length(138); const publicKey = await remoteKeyManager.getPubKey(); - // console.log(publicKey); + console.log(publicKey); expect(publicKey).to.equals(testPubKey); const sharedSecret = await remoteKeyManager.deriveSharedSecret(testPubKey) - // console.log(sharedSecret); + console.log(sharedSecret); expect(sharedSecret).to.equals("3380b4752c9cebf96bc55491ef0ee67ae1d564c0bb931a0c6e8875be6e3bee5"); // const decryptedMessage = await remoteKeyManager.decryptMessage("4b4f34746f434c30354349312b41314b554f644542773d3d"); // console.log(decryptedMessage); From 706be90ee3b037e7acdd8fb6e7f66881e381893b Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Wed, 27 May 2020 20:24:40 +0530 Subject: [PATCH 05/16] added remote key client test --- src/core/domain-services/crux-messenger.ts | 4 +- .../domain-services/remote-key-service.ts | 1 + .../test-remote-key-client-prod.ts | 105 ++++++++++++++++++ 3 files changed, 109 insertions(+), 1 deletion(-) create mode 100644 src/test/crux-messenger/test-remote-key-client-prod.ts diff --git a/src/core/domain-services/crux-messenger.ts b/src/core/domain-services/crux-messenger.ts index 50a88257..1dfa2099 100644 --- a/src/core/domain-services/crux-messenger.ts +++ b/src/core/domain-services/crux-messenger.ts @@ -21,7 +21,7 @@ export class CertificateManager { public static make = async (idClaim: ICruxIdClaim): Promise => { const payload = idClaim.cruxId.toString(); console.log("%&%&%&%&%", idClaim.keyManager); - console.log(payload); + console.log("@@#@#@#@", idClaim.keyManager.getPubKey(), payload); const signedProof = await idClaim.keyManager.signWebToken(payload); return { claim: idClaim.cruxId.toString(), @@ -173,7 +173,9 @@ export class SecureCruxIdMessenger { const securePacket: ISecurePacket = JSON.parse(serializedSecurePacket); let senderUser: CruxUser | undefined; if (securePacket.certificate) { + console.log("~~!!!!!~~~", securePacket.certificate.claim); senderUser = await this.cruxUserRepo.getByCruxId(CruxId.fromString(securePacket.certificate.claim)); + console.log(senderUser); if (!senderUser) { errorCallback(new Error("Claimed sender user in certificate does not exist")); return; diff --git a/src/core/domain-services/remote-key-service.ts b/src/core/domain-services/remote-key-service.ts index b0233e48..999f7d39 100644 --- a/src/core/domain-services/remote-key-service.ts +++ b/src/core/domain-services/remote-key-service.ts @@ -52,6 +52,7 @@ export class RemoteKeyClient { if (!this.secureCruxIdMessenger) { throw Error("RemoteKeyClient cannot listen with no selfMessenger"); } + console.log("%$%$%^%$%^%", invocationId); this.emitter.on(invocationId, resultCallback); this.emitter.on("error", errorCallback); } diff --git a/src/test/crux-messenger/test-remote-key-client-prod.ts b/src/test/crux-messenger/test-remote-key-client-prod.ts new file mode 100644 index 00000000..97799a06 --- /dev/null +++ b/src/test/crux-messenger/test-remote-key-client-prod.ts @@ -0,0 +1,105 @@ +import * as chai from "chai"; +import sinon from "sinon"; +import chaiAsPromised from "chai-as-promised"; +import 'mocha'; +import * as blockstack from "blockstack"; +import {SecureCruxIdMessenger, RemoteKeyClient, RemoteKeyHost, RemoteKeyManager} from "../../core/domain-services"; +import {BasicKeyManager, CruxNetPubSubClientFactory} from "../../infrastructure/implementations"; +import {CruxId} from "../../packages"; +import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies, getCruxdevCruxDomain} from "../test-utils"; +import { bip32 } from "bitcoinjs-lib"; +import * as bip39 from "bip39"; +import { getCruxUserRepository } from "../../application/clients"; +import { CruxSpec } from "../../core/entities"; + +patchMissingDependencies(); + +chai.use(chaiAsPromised); +chai.should(); +const expect = require('chai').expect; + +const _generateMnemonic = (): string => { + return blockstack.BlockstackWallet.generateMnemonic(); +} + +const _generateIdentityKeyPair = async (mnemonic: string): Promise => { + const wallet = new blockstack.BlockstackWallet(bip32.fromSeed(bip39.mnemonicToSeedSync(mnemonic))); + const { address, key, keyID} = wallet.getIdentityKeyPair(0); + const identityKeyPair: any = { + address, + privKey: key, + pubKey: keyID, + }; + return identityKeyPair; +} + +const user1PvtKey = "cdf2d276caf0c9c34258ed6ebd0e60e0e8b3d9a7b8a9a717f2e19ed9b37f7c6f"; // mascot6699@cruxdex.crux +const user2PvtKey = "KyBuSe1MMV6NjJgZfyWuvgmxUeAYswLC2HrfYLUri9aP3AS5FBfr"; // release020@cruxdev.crux + +describe('Test RemoteKeyClient - PROD', function() { + beforeEach(async function() { + const HOST = "127.0.0.1"; + const PORT = 1883; + const newMnemonic = _generateMnemonic(); + const identityKeyPair = await _generateIdentityKeyPair(newMnemonic); + console.log("+++++()()()", identityKeyPair, identityKeyPair.privKey); + // const keyPair = curve.genKeyPair(); + // console.log(keyPair.getPublic('hex')); + this.user2CruxId = "release020@cruxdev.crux"; + this.user1KeyManager = new BasicKeyManager(user1PvtKey); + console.log("!!!", this.user1KeyManager); + this.user2KeyManager = new BasicKeyManager(user2PvtKey); + console.log("===", this.user2KeyManager); + this.userRepo = getCruxUserRepository({ + blockstackInfrastructure: CruxSpec.blockstack.infrastructure, + cruxDomain: getCruxdevCruxDomain() + }); + this.user1Data = await this.userRepo.getWithKey(this.user1KeyManager); + this.user2Data = await this.userRepo.getWithKey(this.user2KeyManager); + this.pubsubClientFactory = new CruxNetPubSubClientFactory({ + defaultLinkServer: { + host: HOST, + port: PORT, + } + }); + }); + + it('Basic Key Manager Send Receive - RemoteKeyManager - Prod', async function() { + const testPubKey = "03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318"; + return new Promise(async (resolve, reject) => { + const remoteKeyManager = new RemoteKeyManager(new SecureCruxIdMessenger(this.userRepo, this.pubsubClientFactory, { + cruxId: this.user2Data.cruxID, + keyManager: this.user2KeyManager + }), this.user1Data.cruxID); + + const remoteKeyHost = new RemoteKeyHost(new SecureCruxIdMessenger(this.userRepo, this.pubsubClientFactory, { + cruxId: this.user1Data.cruxID, + keyManager: this.user1KeyManager + }), this.user1KeyManager); + + remoteKeyHost.invocationListener((msg, senderId) => { + new Promise(async (resolve, reject) => { + console.log("&^%$#%^&*&^%$", msg); + const data = await remoteKeyHost.handleMessage(msg); + console.log("+++^^^&^^", data); + remoteKeyHost.sendInvocationResult(data, senderId); + resolve(); + }); + },(err) => { + }); + const signedWebToken = await remoteKeyManager.signWebToken("1234567") + console.log(signedWebToken); + expect(signedWebToken).to.have.length(138); + const publicKey = await remoteKeyManager.getPubKey(); + console.log(publicKey); + // expect(publicKey).to.equals(testPubKey); + const sharedSecret = await remoteKeyManager.deriveSharedSecret(testPubKey) + console.log(sharedSecret); + // expect(sharedSecret).to.equals("3380b4752c9cebf96bc55491ef0ee67ae1d564c0bb931a0c6e8875be6e3bee5"); + // const decryptedMessage = await remoteKeyManager.decryptMessage("4b4f34746f434c30354349312b41314b554f644542773d3d"); + // console.log(decryptedMessage); + // expect(decryptedMessage).to.equals(""); + resolve(); + }); + }); +}) From 5275f8559ff654ad44befd16a999701203b72721 Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Thu, 28 May 2020 14:42:49 +0530 Subject: [PATCH 06/16] added logging for debugging --- .../clients/crux-service-client.ts | 4 +- src/application/clients/crux-wallet-client.ts | 30 ++------ src/core/domain-services/crux-messenger.ts | 18 ++--- .../domain-services/remote-key-service.ts | 73 ++++++++++--------- src/core/entities/crux-user.ts | 1 - .../implementations/basic-key-manager.ts | 3 - .../blockstack-crux-user-repository.ts | 6 -- .../implementations/crux-messenger.ts | 4 +- .../test-crux-service-client-prod.ts | 56 +++----------- .../test-remote-key-client-prod.ts | 48 ++---------- 10 files changed, 75 insertions(+), 168 deletions(-) diff --git a/src/application/clients/crux-service-client.ts b/src/application/clients/crux-service-client.ts index 30253d6e..bcc2d733 100644 --- a/src/application/clients/crux-service-client.ts +++ b/src/application/clients/crux-service-client.ts @@ -1,12 +1,12 @@ -import { CruxId } from "src/packages"; import { RemoteKeyManager, SecureCruxIdMessenger } from "../../core/domain-services"; +import { CruxId, InMemStorage } from "../../packages/"; import { CruxWalletClient } from "./crux-wallet-client"; export class CruxServiceClient { public getWalletClientForUser(secureCruxIdMessenger: SecureCruxIdMessenger, remoteUserId: CruxId) { - console.log("Hd"); return new CruxWalletClient({ + cacheStorage: new InMemStorage(), privateKey: new RemoteKeyManager(secureCruxIdMessenger, remoteUserId), walletClientName: remoteUserId.components.domain, }); diff --git a/src/application/clients/crux-wallet-client.ts b/src/application/clients/crux-wallet-client.ts index 21eacc61..9bbc4165 100644 --- a/src/application/clients/crux-wallet-client.ts +++ b/src/application/clients/crux-wallet-client.ts @@ -1,6 +1,6 @@ // Importing packages import Logger from "js-logger"; -import {CruxConnectProtocolMessenger, SecureCruxIdMessenger, RemoteKeyHost} from "../../core/domain-services"; +import {CruxConnectProtocolMessenger, RemoteKeyHost, SecureCruxIdMessenger} from "../../core/domain-services"; import { CruxDomain, CruxSpec, @@ -124,7 +124,6 @@ export class CruxWalletClient { this.walletClientName = options.walletClientName; if (options.privateKey) { if (typeof options.privateKey === "string") { - console.log("================", options.privateKey); this.keyManager = new BasicKeyManager(options.privateKey); } else if (isInstanceOfKeyManager(options.privateKey)) { this.keyManager = options.privateKey; @@ -200,17 +199,14 @@ export class CruxWalletClient { @throwCruxClientError public getAddressMap = async (): Promise => { - console.log("LMAO"); - console.log("Hieeee", this.getKeyManager()); - // await this.initPromise; - console.log("after promise"); - console.log("Hoilaaaaaa", await this.getKeyManager().getPubKey()); - console.log("Aloha"); + console.log("CruxWalletClient::getAddressMap::keyManager: ", this.getKeyManager()); + await this.initPromise; + console.log("CruxWalletClient::getAddressMap::publickKey: ", await this.getKeyManager().getPubKey()); const cruxUser = await this.cruxUserRepository.getWithKey(this.getKeyManager()); - console.log("&&&&&&{}{}", cruxUser); + console.log("CruxWalletClient::getAddressMap::cruxUser: ", cruxUser); if (cruxUser) { - console.log("dude"); const assetIdAddressMap = cruxUser.getAddressMap(); + console.log("CruxWalletClient::getAddressMap::assetIdAddressMap"); return this.cruxAssetTranslator.assetIdAddressMapToSymbolAddressMap(assetIdAddressMap); } return {}; @@ -407,12 +403,10 @@ export class CruxWalletClient { if (!this.cruxDomain) { throw ErrorHelper.getPackageError(null, PackageErrorCode.InvalidWalletClientName); } - console.log("YOLO"); this.cruxUserRepository = getCruxUserRepository({cacheStorage: this.cacheStorage, blockstackInfrastructure: this.cruxBlockstackInfrastructure, cruxDomain: this.cruxDomain}); if (!this.cruxDomain.config) { throw ErrorHelper.getPackageError(null, PackageErrorCode.CouldNotFindBlockstackConfigurationServiceClientConfig); } - console.log("Bol"); this.cruxAssetTranslator = new CruxAssetTranslator(this.cruxDomain.config.assetMapping, this.cruxDomain.config.assetList); await this.setupCruxMessenger(options); } @@ -441,21 +435,13 @@ export class CruxWalletClient { const pubsubClientFactory = new CruxNetPubSubClientFactory({defaultLinkServer: { host: "127.0.0.1", port: 1883, - }}); + }}); const secureCruxMessenger = new SecureCruxIdMessenger(this.cruxUserRepository, pubsubClientFactory, selfIdClaim); this.paymentProtocolMessenger = new CruxConnectProtocolMessenger(secureCruxMessenger, cruxPaymentProtocol); if (options.isHost) { const remoteKeyHost = new RemoteKeyHost(secureCruxMessenger, this.keyManager!); this.remoteKeyHost = remoteKeyHost; - console.log("setupRemoteKeyHost__________", selfIdClaim.cruxId.toString()); - remoteKeyHost.invocationListener(async (msg, senderId) => { - console.log("%%%%%%%%%%%%%", msg, senderId); - const data = await remoteKeyHost.handleMessage(msg); - remoteKeyHost.sendInvocationResult(data, senderId); - }, (err) => { - console.log("[][][][", err); - remoteKeyHost.sendInvocationResult(err, senderId); - }); + console.log("setupCruxMessenger::remoteKeyHostSetup::hostCruxId", selfIdClaim.cruxId.toString()); } } diff --git a/src/core/domain-services/crux-messenger.ts b/src/core/domain-services/crux-messenger.ts index 1dfa2099..df45b4ba 100644 --- a/src/core/domain-services/crux-messenger.ts +++ b/src/core/domain-services/crux-messenger.ts @@ -20,8 +20,7 @@ import { export class CertificateManager { public static make = async (idClaim: ICruxIdClaim): Promise => { const payload = idClaim.cruxId.toString(); - console.log("%&%&%&%&%", idClaim.keyManager); - console.log("@@#@#@#@", idClaim.keyManager.getPubKey(), payload); + console.log("CertificateManager::make:claim: ",payload); const signedProof = await idClaim.keyManager.signWebToken(payload); return { claim: idClaim.cruxId.toString(), @@ -30,9 +29,8 @@ export class CertificateManager { } public static verify = (certificate: ICruxIdCertificate, senderPubKey: any) => { const proof: any = decodeToken(certificate.proof).payload; - console.log(":::::::::;", certificate.claim, proof, senderPubKey); const verified = new TokenVerifier("ES256K", senderPubKey).verify(certificate.proof); - console.log("&*&**&*&", verified, certificate.claim, proof); + console.log("CertificateManager::verify:: verified, claim, proof", verified, certificate.claim, proof); if (proof && proof === certificate.claim && verified) { return true; } @@ -144,12 +142,12 @@ export class SecureCruxIdMessenger { // TODO: Do we need to validate selfIdClaim? } public send = async (data: any, recipientCruxId: CruxId): Promise => { - console.log("inside send: ", recipientCruxId.toString()); + console.log("SecureCruxIdMessenger::send::entry"); const recipientCruxUser: CruxUser | undefined = await this.cruxUserRepo.getByCruxId(recipientCruxId); - console.log("~~~~~~~", recipientCruxUser); if (!recipientCruxUser) { throw Error("No Such CRUX User Found"); } + console.log("SecureCruxIdMessenger::send::data: ", data); const certificate = this.selfIdClaim ? await CertificateManager.make(this.selfIdClaim) : undefined; const securePacket: ISecurePacket = { certificate, @@ -166,23 +164,21 @@ export class SecureCruxIdMessenger { if (!this.selfMessenger) { throw Error("Cannot listen with no selfMessenger"); } + console.log("SecureCruxIdMessenger::listen::entry"); this.selfMessenger.on(EventBusEventNames.newMessage, async (encryptedString: string) => { try { - console.log("inside listen and on :::::"); + console.log("SecureCruxIdMessenger::listen::onblock::entry"); const serializedSecurePacket: string = await EncryptionManager.decrypt(encryptedString, this.selfIdClaim!.keyManager); const securePacket: ISecurePacket = JSON.parse(serializedSecurePacket); let senderUser: CruxUser | undefined; if (securePacket.certificate) { - console.log("~~!!!!!~~~", securePacket.certificate.claim); + console.log("SecureCruxIdMessenger::listen::onblock::claim: ", securePacket.certificate.claim); senderUser = await this.cruxUserRepo.getByCruxId(CruxId.fromString(securePacket.certificate.claim)); - console.log(senderUser); if (!senderUser) { errorCallback(new Error("Claimed sender user in certificate does not exist")); return; } const isVerified = CertificateManager.verify(securePacket.certificate, senderUser.publicKey!); - console.log("********", securePacket.certificate); - console.log("??????????", senderUser.publicKey); if (!isVerified) { errorCallback(new Error("Could not validate identity")); return; diff --git a/src/core/domain-services/remote-key-service.ts b/src/core/domain-services/remote-key-service.ts index 999f7d39..4a7c64b9 100644 --- a/src/core/domain-services/remote-key-service.ts +++ b/src/core/domain-services/remote-key-service.ts @@ -16,7 +16,7 @@ export class RemoteKeyClient { this.remoteUserId = remoteUserId; this.emitter = createNanoEvents(); this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => { - console.log("inside invokeresult::::::", msg, senderId); + console.log("Inside RemoteKeyClient Constructor:: ", msg, senderId); this.emitter.emit(msg.invocationId, msg, senderId); }, (err: any) => { this.emitter.emit("error", err); @@ -25,12 +25,12 @@ export class RemoteKeyClient { } public async invoke(method: string, args: any[]) { - console.log("inside Invoke::::::"); + console.log("RemoteKeyClient::Inside Invoke"); if (!this.secureCruxIdMessenger) { throw Error("RemoteKeyClient cannot send with no selfMessenger"); } const methodData = this.generateMethodData(method, args); - console.log("^^^^^^", this.remoteUserId, methodData); + console.log("RemoteKeyClient::Inside Invoke, RemoteUserId, MethodData", this.remoteUserId, methodData); await this.secureCruxIdMessenger.send(methodData, this.remoteUserId); return methodData.invocationId; } @@ -40,7 +40,7 @@ export class RemoteKeyClient { throw Error("RemoteKeyClient cannot listen with no selfMessenger"); } this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => { - console.log("inside invokeresult::::::", msg, senderId); + console.log("RemoteKeyClient::Inside invokeresult", msg, senderId); resultCallback(msg, senderId); }, (err: any) => { errorCallback(err); @@ -52,7 +52,7 @@ export class RemoteKeyClient { if (!this.secureCruxIdMessenger) { throw Error("RemoteKeyClient cannot listen with no selfMessenger"); } - console.log("%$%$%^%$%^%", invocationId); + console.log("RemoteKeyClient::ListenToInvocation::invocationId", invocationId); this.emitter.on(invocationId, resultCallback); this.emitter.on("error", errorCallback); } @@ -71,37 +71,30 @@ export class RemoteKeyHost { private keyManager: IKeyManager; constructor(secureCruxIdMessenger: SecureCruxIdMessenger, keyManager: IKeyManager) { - this.secureCruxIdMessenger = secureCruxIdMessenger; this.keyManager = keyManager; + this.secureCruxIdMessenger = secureCruxIdMessenger; + this.secureCruxIdMessenger.listen(async (msg: any, senderId: CruxId | undefined) => { + console.log("Inside RemoteKeyHost::Constructor::Msg, senderId: ", msg, senderId); + const data = await this.handleMessage(msg); + console.log("Inside RemoteKeyHost::Constructor::Data(handleMessage): ", data); + this.sendInvocationResult(data, senderId); + }, (err: any) => { + console.log("errorinvocationListener", err); + return; + }); } - public async sendInvocationResult(result: any, receiverId: CruxId) { + private async sendInvocationResult(result: any, receiverId: CruxId) { if (!this.secureCruxIdMessenger) { throw Error("RemoteKeyClient cannot send with no selfMessenger"); } const resultData = this.generateInvocationResponse(result); - console.log(resultData); + console.log("RemoteKeyHost::Inside sendInvocationResult::resultData: ", resultData); await this.secureCruxIdMessenger.send(resultData, receiverId); } - public invocationListener = (resultCallback: (msg: any, senderId: CruxId | undefined) => any, errorCallback: (err: any) => any): void => { - if (!this.secureCruxIdMessenger) { - throw Error("RemoteKeyClient cannot listen with no selfMessenger"); - } - this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => { - // this.handleMessage(msg); - console.log("#####", msg, senderId); - resultCallback(msg, senderId); - }, (err: any) => { - console.log("errorinvocationListener", err); - errorCallback(err); - return; - }); - } - - public async handleMessage(message: any) { + private async handleMessage(message: any) { if (!VALID_METHODS.includes(message.method)) { - // console.log("yolo"); throw new Error("Invalid key manager method"); } if (!this.keyManager) { @@ -109,15 +102,23 @@ export class RemoteKeyHost { } let data; if (message.method === "signWebToken") { + console.log("HandleMessage entrance:signWebToken"); data = await this.keyManager.signWebToken(message.args[0]); + console.log("HandleMessage exit:signWebToken", data); } else if (message.method === "getPubKey") { + console.log("HandleMessage entrance:getPubKey"); data = await this.keyManager.getPubKey(); + console.log("HandleMessage exit:getPubKey", data); } else if (message.method === "deriveSharedSecret") { + console.log("HandleMessage entrance:deriveSharedSecret"); // @ts-ignore data = await this.keyManager.deriveSharedSecret(message.args[0]); + console.log("HandleMessage exit:deriveSharedSecret", data); } else if (message.method === "decryptMessage") { + console.log("HandleMessage entrance:decryptMessage"); // @ts-ignore data = await this.keyManager.decryptMessage(message.args[0]); + console.log("HandleMessage exit:decryptMessage", data); } return { data, @@ -143,12 +144,11 @@ export class RemoteKeyManager implements IKeyManager { } // @ts-ignore public async signWebToken(token: any) { - console.log("Boli"); - const temp = [token]; return new Promise(async (resolve, reject) => { const invocationId = await this.remoteKeyClient.invoke("signWebToken", [token]); + console.log("RemoteKeyManager::signWebToken::invokationId: ", invocationId); this.remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { - console.log("sign+++====", msg); + console.log("RemoteKeyManager::signWebToken::msg: ", msg); resolve(msg.result.data); }, (err) => { reject(err); @@ -157,23 +157,24 @@ export class RemoteKeyManager implements IKeyManager { } // @ts-ignore public async getPubKey() { - console.log("Holi"); return new Promise(async (resolve, reject) => { const invocationId = await this.remoteKeyClient.invoke("getPubKey", []); + console.log("RemoteKeyManager::getPubKey::invokationId: ", invocationId); this.remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { - console.log("pub+++====", msg); + console.log("RemoteKeyManager::getPubKey::msg: ", msg); resolve(msg.result.data); }, (err) => { reject(err); }); - console.log("getPubKey:Method"); }); } // @ts-ignore public async deriveSharedSecret(publicKey: string) { + const invocationId = await this.remoteKeyClient.invoke("deriveSharedSecret", [publicKey]); + console.log("RemoteKeyManager::deriveSharedSecret::invokationId: ", invocationId); return new Promise(async (resolve, reject) => { - this.remoteKeyClient.invokeResult((msg, senderId) => { - console.log("secret+++====", msg); + this.remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { + console.log("RemoteKeyManager::deriveSharedSecret::msg: ", msg); resolve(msg.result.data); }, (err) => { reject(err); @@ -182,9 +183,11 @@ export class RemoteKeyManager implements IKeyManager { } // @ts-ignore public async decryptMessage(encryptedMessage: string) { + const invocationId = await this.remoteKeyClient.invoke("decryptMessage", [encryptedMessage]); + console.log("RemoteKeyManager::decryptMessage::invokationId: ", invocationId); return new Promise(async (resolve, reject) => { - this.remoteKeyClient.invokeResult((msg, senderId) => { - console.log("decrypt+++====", msg); + this.remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { + console.log("RemoteKeyManager::decryptMessage::msg: ", msg); resolve(msg.result.data); }, (err) => { reject(err); diff --git a/src/core/entities/crux-user.ts b/src/core/entities/crux-user.ts index b3ea1b67..5a68f730 100644 --- a/src/core/entities/crux-user.ts +++ b/src/core/entities/crux-user.ts @@ -72,7 +72,6 @@ export class CruxUser { this.setCruxUserConfig(cruxUserData.configuration); this.setPublicKey(publicKey); this.setCruxUserPrivateAddresses(cruxUserData.privateAddresses); - console.log("CruxUser initialised"); log.debug("CruxUser initialised"); } get cruxID() { diff --git a/src/infrastructure/implementations/basic-key-manager.ts b/src/infrastructure/implementations/basic-key-manager.ts index 0d0f361b..27901749 100644 --- a/src/infrastructure/implementations/basic-key-manager.ts +++ b/src/infrastructure/implementations/basic-key-manager.ts @@ -20,13 +20,11 @@ export class BasicKeyManager implements IKeyManager { public signWebToken = async (payload: any): Promise => { await this.initPromise; let privateKey = await this.getDecryptedPrivateKey(); - console.log("privateKey: ", privateKey); const signedMsg = new TokenSigner("ES256K", privateKey).sign(payload); privateKey = "0".repeat(privateKey.length); return signedMsg; } public getPubKey = async (): Promise => { - console.log("*()"); await this.initPromise; return this.publicKey; } @@ -54,7 +52,6 @@ export class BasicKeyManager implements IKeyManager { encryptionConstant = getRandomHexString(); this.ephemeralEncryptionConstant = encryptionConstant; } - console.log("&&*&*&", privateKey); const keyPair = getKeyPairFromPrivKey(privateKey); this.publicKey = keyPair.pubKey; this.encryptedPrivateKey = JSON.stringify(await Encryption.encryptText(keyPair.privKey, encryptionConstant)); diff --git a/src/infrastructure/implementations/blockstack-crux-user-repository.ts b/src/infrastructure/implementations/blockstack-crux-user-repository.ts index 7be06363..36a4239e 100644 --- a/src/infrastructure/implementations/blockstack-crux-user-repository.ts +++ b/src/infrastructure/implementations/blockstack-crux-user-repository.ts @@ -73,12 +73,10 @@ export class BlockstackCruxUserRepository implements ICruxUserRepository { return this.blockstackService.isCruxIdAvailable(this.getCruxIdFromSubdomain(cruxIdSubdomain)); } public getByCruxId = async (cruxID: CruxId, tag?: string, onlyRegistered: boolean = false): Promise => { - console.log("inside getByCruxId::::::"); const cruxUserInformation = await this.blockstackService.getCruxIdInformation(cruxID, tag, onlyRegistered); if (cruxUserInformation.registrationStatus.status === SubdomainRegistrationStatus.NONE) { return; } - console.log("+++$$$$$", cruxUserInformation); let addressMap = {}; let cruxUserData: ICruxUserData = { configuration: { @@ -98,13 +96,10 @@ export class BlockstackCruxUserRepository implements ICruxUserRepository { cruxUserData = dereferencedCruxpayObject.cruxUserData; } } - console.log("$$$$#####$$", cruxUserInformation); return new CruxUser(cruxID.components.subdomain, await this.getUserCruxDomain(cruxID) as CruxDomain, addressMap, cruxUserInformation, cruxUserData, cruxpayPubKey); } public getWithKey = async (keyManager: IKeyManager): Promise => { - console.log("+++@@@@@@@", await keyManager.getPubKey()); const cruxID = await this.blockstackService.getCruxIdWithKeyManager(keyManager, this.getCruxDomain().id); - console.log("*()(*()(*()", cruxID); if (!cruxID) { return; } @@ -131,7 +126,6 @@ export class BlockstackCruxUserRepository implements ICruxUserRepository { cruxUserData = dereferencedCruxpayObject.cruxUserData; } } - console.log("holo"); return new CruxUser(cruxID.components.subdomain, this.getCruxDomain(), addressMap, cruxUserInformation, cruxUserData, cruxpayPubKey); } public save = async (cruxUser: CruxUser, keyManager: IKeyManager): Promise => { diff --git a/src/infrastructure/implementations/crux-messenger.ts b/src/infrastructure/implementations/crux-messenger.ts index f0bd0368..2d0eb9e5 100644 --- a/src/infrastructure/implementations/crux-messenger.ts +++ b/src/infrastructure/implementations/crux-messenger.ts @@ -41,12 +41,12 @@ export class StrongPubSubClient implements IPubSubClient { } public publish(topic: string, data: any): void { this.ensureClient(); - console.log("Message Published: ", topic, data); + console.log("StrongPubSubClient::publish::topic: ", topic); this.client.publish(topic, data); } public subscribe(topic: string, callback: any): void { this.ensureClient(); - console.log("SUBSCRIBED", topic); + console.log("StrongPubSubClient::subscribe::topic: ", topic); this.client.subscribe(topic, this.config.subscribeOptions); this.client.on("message", callback); } diff --git a/src/test/crux-messenger/test-crux-service-client-prod.ts b/src/test/crux-messenger/test-crux-service-client-prod.ts index 30db5da8..27e2d764 100644 --- a/src/test/crux-messenger/test-crux-service-client-prod.ts +++ b/src/test/crux-messenger/test-crux-service-client-prod.ts @@ -3,16 +3,12 @@ import * as blockstack from "blockstack"; import sinon from "sinon"; import chaiAsPromised from "chai-as-promised"; import 'mocha'; -import * as elliptic from "elliptic"; -import Client from "strong-pubsub"; -import MqttAdapter from "strong-pubsub-mqtt"; -import {SecureCruxIdMessenger, RemoteKeyClient, RemoteKeyHost, RemoteKeyManager} from "../../core/domain-services"; +import {SecureCruxIdMessenger} from "../../core/domain-services"; import {CruxServiceClient, getCruxUserRepository, CruxWalletClient} from "../../application/clients" import {BasicKeyManager, CruxNetPubSubClientFactory, StrongPubSubClient} from "../../infrastructure/implementations"; import {patchMissingDependencies, getCruxdevCruxDomain} from "../test-utils"; -import { CruxSpec } from "../../core/entities"; -import {IKeyManager} from "../../core/interfaces"; -import { CruxId } from "../../packages"; +import { CruxSpec, IAddress } from "../../core/entities"; +import { CruxId, InMemStorage } from "../../packages"; import { bip32 } from "bitcoinjs-lib"; import * as bip39 from "bip39"; @@ -22,11 +18,10 @@ chai.use(chaiAsPromised); chai.should(); const expect = require('chai').expect; +const btcAddress: IAddress = {addressHash: "1HX4KvtPdg9QUYwQE1kNqTAjmNaDG7w82V"}; const user1PvtKey = "cdf2d276caf0c9c34258ed6ebd0e60e0e8b3d9a7b8a9a717f2e19ed9b37f7c6f"; // mascot6699@cruxdex.crux -// const user2PvtKey = "KyBuSe1MMV6NjJgZfyWuvgmxUeAYswLC2HrfYLUri9aP3AS5FBfr"; // release020@cruxdev.crux +const user2PvtKey = "KyBuSe1MMV6NjJgZfyWuvgmxUeAYswLC2HrfYLUri9aP3AS5FBfr"; // release020@cruxdev.crux -var EC = elliptic.ec; -const curve = new EC("secp256k1"); const _generateMnemonic = (): string => { return blockstack.BlockstackWallet.generateMnemonic(); @@ -49,66 +44,35 @@ describe('Test CruxServiceClient', function() { const PORT = 1883; const newMnemonic = _generateMnemonic(); const identityKeyPair = await _generateIdentityKeyPair(newMnemonic); - console.log("+++++()()()", identityKeyPair); - // const keyPair = curve.genKeyPair(); - // console.log(keyPair.getPublic('hex')); this.user2CruxId = "release020@cruxdev.crux"; this.user1KeyManager = new BasicKeyManager(user1PvtKey); - console.log("!!!", this.user1KeyManager); - this.user2KeyManager = new BasicKeyManager(identityKeyPair.privKey); - console.log("===", this.user2KeyManager); + this.user2KeyManager = new BasicKeyManager(user2PvtKey); this.userRepo = getCruxUserRepository({ blockstackInfrastructure: CruxSpec.blockstack.infrastructure, cruxDomain: getCruxdevCruxDomain() }); this.user1Data = await this.userRepo.getWithKey(this.user1KeyManager); + this.user2Data = await this.userRepo.getWithKey(this.user2KeyManager); this.pubsubClientFactory = new CruxNetPubSubClientFactory({ defaultLinkServer: { host: HOST, port: PORT, } }); - this.subscriberUserName = "release020@cruxdev.crux"; - this.subscriberConfig = { - clientOptions: { - host: HOST, - port: PORT, - mqtt: { - clean: false, - clientId: this.subscriberUserName, - }, - }, - subscribeOptions: { - qos: 2, - } - }; - this.subscriber = new StrongPubSubClient(this.subscriberConfig); - this.client = new Client(this.subscriberConfig.clientOptions, MqttAdapter); }); it('Basic Key Manager Send Receive - CruxServiceClient', async function() { const cruxWalletClient = new CruxWalletClient({ privateKey: user1PvtKey, walletClientName: "cruxdev", isHost: true, + cacheStorage: new InMemStorage(), }); - // const user1Messenger = new SecureCruxIdMessenger(this.userRepo, this.pubsubClientFactory, { - // cruxId: this.user1Data.cruxID, - // keyManager: new BasicKeyManager(user1PvtKey) - // }); - // new Promise(async (resolve, reject) => { - // this.client.subscribe("topic_mascot6699@cruxdev.crux", this.subscriberConfig.subscribeOptions); - // this.client.on("message", (topic, msg) => { - // console.log("--------------", topic, msg) - // resolve(); - // }); - // }); const cruxServiceClient = new CruxServiceClient(); const serviceWalletClient = cruxServiceClient.getWalletClientForUser(new SecureCruxIdMessenger(this.userRepo, this.pubsubClientFactory, { cruxId: CruxId.fromString(this.user2CruxId), keyManager: this.user2KeyManager }), this.user1Data.cruxID); - console.log("++++++$$#####", serviceWalletClient); - console.log("=======++++++++", await serviceWalletClient.getAddressMap()); - console.log("@@@@@"); + const addressMap = await serviceWalletClient.putAddressMap({"btc" : btcAddress}); + console.log("TESTCASE::Address Map: ", addressMap); }); }); \ No newline at end of file diff --git a/src/test/crux-messenger/test-remote-key-client-prod.ts b/src/test/crux-messenger/test-remote-key-client-prod.ts index 97799a06..59428741 100644 --- a/src/test/crux-messenger/test-remote-key-client-prod.ts +++ b/src/test/crux-messenger/test-remote-key-client-prod.ts @@ -18,21 +18,6 @@ chai.use(chaiAsPromised); chai.should(); const expect = require('chai').expect; -const _generateMnemonic = (): string => { - return blockstack.BlockstackWallet.generateMnemonic(); -} - -const _generateIdentityKeyPair = async (mnemonic: string): Promise => { - const wallet = new blockstack.BlockstackWallet(bip32.fromSeed(bip39.mnemonicToSeedSync(mnemonic))); - const { address, key, keyID} = wallet.getIdentityKeyPair(0); - const identityKeyPair: any = { - address, - privKey: key, - pubKey: keyID, - }; - return identityKeyPair; -} - const user1PvtKey = "cdf2d276caf0c9c34258ed6ebd0e60e0e8b3d9a7b8a9a717f2e19ed9b37f7c6f"; // mascot6699@cruxdex.crux const user2PvtKey = "KyBuSe1MMV6NjJgZfyWuvgmxUeAYswLC2HrfYLUri9aP3AS5FBfr"; // release020@cruxdev.crux @@ -40,16 +25,9 @@ describe('Test RemoteKeyClient - PROD', function() { beforeEach(async function() { const HOST = "127.0.0.1"; const PORT = 1883; - const newMnemonic = _generateMnemonic(); - const identityKeyPair = await _generateIdentityKeyPair(newMnemonic); - console.log("+++++()()()", identityKeyPair, identityKeyPair.privKey); - // const keyPair = curve.genKeyPair(); - // console.log(keyPair.getPublic('hex')); this.user2CruxId = "release020@cruxdev.crux"; this.user1KeyManager = new BasicKeyManager(user1PvtKey); - console.log("!!!", this.user1KeyManager); this.user2KeyManager = new BasicKeyManager(user2PvtKey); - console.log("===", this.user2KeyManager); this.userRepo = getCruxUserRepository({ blockstackInfrastructure: CruxSpec.blockstack.infrastructure, cruxDomain: getCruxdevCruxDomain() @@ -65,7 +43,7 @@ describe('Test RemoteKeyClient - PROD', function() { }); it('Basic Key Manager Send Receive - RemoteKeyManager - Prod', async function() { - const testPubKey = "03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318"; + const testPubKey = "0362f171a40ab5e6ad22275ec166f15a232b83a571bab9c30622ed2963f1da4c08"; return new Promise(async (resolve, reject) => { const remoteKeyManager = new RemoteKeyManager(new SecureCruxIdMessenger(this.userRepo, this.pubsubClientFactory, { cruxId: this.user2Data.cruxID, @@ -77,28 +55,18 @@ describe('Test RemoteKeyClient - PROD', function() { keyManager: this.user1KeyManager }), this.user1KeyManager); - remoteKeyHost.invocationListener((msg, senderId) => { - new Promise(async (resolve, reject) => { - console.log("&^%$#%^&*&^%$", msg); - const data = await remoteKeyHost.handleMessage(msg); - console.log("+++^^^&^^", data); - remoteKeyHost.sendInvocationResult(data, senderId); - resolve(); - }); - },(err) => { - }); const signedWebToken = await remoteKeyManager.signWebToken("1234567") - console.log(signedWebToken); + console.log("TESTCASE::signWebToken:", signedWebToken); expect(signedWebToken).to.have.length(138); const publicKey = await remoteKeyManager.getPubKey(); - console.log(publicKey); - // expect(publicKey).to.equals(testPubKey); - const sharedSecret = await remoteKeyManager.deriveSharedSecret(testPubKey) - console.log(sharedSecret); - // expect(sharedSecret).to.equals("3380b4752c9cebf96bc55491ef0ee67ae1d564c0bb931a0c6e8875be6e3bee5"); + console.log("TESTCASE::publicKey", publicKey); + expect(publicKey).equals(testPubKey); + // const sharedSecret = await remoteKeyManager.deriveSharedSecret(testPubKey) + // console.log("TESTCASE::sharedSecret", sharedSecret); + // expect(sharedSecret).equals("d2744fdfa47538b816623e75cc783469cbe3d71da02965edd662ae3f45fbac3"); // const decryptedMessage = await remoteKeyManager.decryptMessage("4b4f34746f434c30354349312b41314b554f644542773d3d"); // console.log(decryptedMessage); - // expect(decryptedMessage).to.equals(""); + // expect(decryptedMessage).equals(""); resolve(); }); }); From 7b829d32fc46a554a14603c6f24a825bab72057b Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Thu, 28 May 2020 20:50:49 +0530 Subject: [PATCH 07/16] modified cruxServiceClient and updated testcases --- .../clients/crux-service-client.ts | 11 +++++- src/application/clients/crux-wallet-client.ts | 12 +++--- src/core/domain-services/crux-messenger.ts | 4 +- .../domain-services/remote-key-service.ts | 1 + .../implementations/basic-key-manager.ts | 2 + .../test-crux-service-client-prod.ts | 29 +++----------- .../test-remote-key-client-prod.ts | 22 +++++++---- .../crux-messenger/test-remote-key-client.ts | 39 ------------------- 8 files changed, 41 insertions(+), 79 deletions(-) diff --git a/src/application/clients/crux-service-client.ts b/src/application/clients/crux-service-client.ts index bcc2d733..3d28fcea 100644 --- a/src/application/clients/crux-service-client.ts +++ b/src/application/clients/crux-service-client.ts @@ -3,11 +3,18 @@ import { CruxId, InMemStorage } from "../../packages/"; import { CruxWalletClient } from "./crux-wallet-client"; export class CruxServiceClient { + private selfIdClaim: any; + private secureCruxIdMessenger: SecureCruxIdMessenger; - public getWalletClientForUser(secureCruxIdMessenger: SecureCruxIdMessenger, remoteUserId: CruxId) { + constructor(selfIdClaim: any, userRepo: any, pubsubClientFactory: any) { + this.selfIdClaim = selfIdClaim; + this.secureCruxIdMessenger = new SecureCruxIdMessenger(userRepo, pubsubClientFactory, selfIdClaim); + } + + public getWalletClientForUser(remoteUserId: CruxId) { return new CruxWalletClient({ cacheStorage: new InMemStorage(), - privateKey: new RemoteKeyManager(secureCruxIdMessenger, remoteUserId), + privateKey: new RemoteKeyManager(this.secureCruxIdMessenger, remoteUserId), walletClientName: remoteUserId.components.domain, }); } diff --git a/src/application/clients/crux-wallet-client.ts b/src/application/clients/crux-wallet-client.ts index 9bbc4165..6e1a4c8b 100644 --- a/src/application/clients/crux-wallet-client.ts +++ b/src/application/clients/crux-wallet-client.ts @@ -432,16 +432,16 @@ export class CruxWalletClient { if (!selfIdClaim) { throw Error("Self ID Claim is required to setup messenger"); } - const pubsubClientFactory = new CruxNetPubSubClientFactory({defaultLinkServer: { + if (options.isHost) { + const pubsubClientFactory = new CruxNetPubSubClientFactory({defaultLinkServer: { host: "127.0.0.1", port: 1883, - }}); - const secureCruxMessenger = new SecureCruxIdMessenger(this.cruxUserRepository, pubsubClientFactory, selfIdClaim); - this.paymentProtocolMessenger = new CruxConnectProtocolMessenger(secureCruxMessenger, cruxPaymentProtocol); - if (options.isHost) { + }}); + const secureCruxMessenger = new SecureCruxIdMessenger(this.cruxUserRepository, pubsubClientFactory, selfIdClaim); + this.paymentProtocolMessenger = new CruxConnectProtocolMessenger(secureCruxMessenger, cruxPaymentProtocol); const remoteKeyHost = new RemoteKeyHost(secureCruxMessenger, this.keyManager!); this.remoteKeyHost = remoteKeyHost; - console.log("setupCruxMessenger::remoteKeyHostSetup::hostCruxId", selfIdClaim.cruxId.toString()); + console.log("setupCruxMessenger::remoteKeyHostSetup::hostCruxId", selfIdClaim.cruxId.toString(), this.keyManager!); } } diff --git a/src/core/domain-services/crux-messenger.ts b/src/core/domain-services/crux-messenger.ts index df45b4ba..c5a4e1b4 100644 --- a/src/core/domain-services/crux-messenger.ts +++ b/src/core/domain-services/crux-messenger.ts @@ -48,6 +48,7 @@ export class EncryptionManager { } public static decrypt = async (encryptedContent: string, keyManager: IKeyManager): Promise => { try { + console.log("EncryptionManager::decrypt::keymanager, encryptionContent: ", keyManager, encryptedContent); const decryptedContent = await keyManager.decryptMessage!(encryptedContent); return decryptedContent; } catch (e) { @@ -167,7 +168,8 @@ export class SecureCruxIdMessenger { console.log("SecureCruxIdMessenger::listen::entry"); this.selfMessenger.on(EventBusEventNames.newMessage, async (encryptedString: string) => { try { - console.log("SecureCruxIdMessenger::listen::onblock::entry"); + console.log("SecureCruxIdMessenger::listen::onblock::entry: ", this.selfIdClaim!); + console.log("encryptedString::Detail::type and buffer",encryptedString, encryptedString); const serializedSecurePacket: string = await EncryptionManager.decrypt(encryptedString, this.selfIdClaim!.keyManager); const securePacket: ISecurePacket = JSON.parse(serializedSecurePacket); let senderUser: CruxUser | undefined; diff --git a/src/core/domain-services/remote-key-service.ts b/src/core/domain-services/remote-key-service.ts index 4a7c64b9..5ba8e18d 100644 --- a/src/core/domain-services/remote-key-service.ts +++ b/src/core/domain-services/remote-key-service.ts @@ -183,6 +183,7 @@ export class RemoteKeyManager implements IKeyManager { } // @ts-ignore public async decryptMessage(encryptedMessage: string) { + console.log("RemoteKeyManager::decryptMessage::entry: encryptedMessage: ", encryptedMessage); const invocationId = await this.remoteKeyClient.invoke("decryptMessage", [encryptedMessage]); console.log("RemoteKeyManager::decryptMessage::invokationId: ", invocationId); return new Promise(async (resolve, reject) => { diff --git a/src/infrastructure/implementations/basic-key-manager.ts b/src/infrastructure/implementations/basic-key-manager.ts index 27901749..75401dba 100644 --- a/src/infrastructure/implementations/basic-key-manager.ts +++ b/src/infrastructure/implementations/basic-key-manager.ts @@ -32,12 +32,14 @@ export class BasicKeyManager implements IKeyManager { let privateKey = await this.getDecryptedPrivateKey(); const curve = new ec("secp256k1"); const selfKey = curve.keyFromPrivate(privateKey, "hex"); + console.log("Inside DeriveSharedSecret: pubKey, pvtKey", publicKey, privateKey); const userKey = curve.keyFromPublic(publicKey, "hex"); privateKey = "0".repeat(privateKey.length); return selfKey.derive(userKey.getPublic()).toString(16); } public decryptMessage = async (encryptedMessage: string): Promise => { + console.log("Inside DecryptMessage: type, value", typeof encryptedMessage, encryptedMessage); const toDecrypt = BufferJSONSerializer.JSONStringToBufferObject(encryptedMessage); const privateKey = await this.getDecryptedPrivateKey(); const decrypted = await ECIESEncryption.decrypt(toDecrypt, privateKey); diff --git a/src/test/crux-messenger/test-crux-service-client-prod.ts b/src/test/crux-messenger/test-crux-service-client-prod.ts index 27e2d764..7e3f753d 100644 --- a/src/test/crux-messenger/test-crux-service-client-prod.ts +++ b/src/test/crux-messenger/test-crux-service-client-prod.ts @@ -22,34 +22,17 @@ const btcAddress: IAddress = {addressHash: "1HX4KvtPdg9QUYwQE1kNqTAjmNaDG7w82V"} const user1PvtKey = "cdf2d276caf0c9c34258ed6ebd0e60e0e8b3d9a7b8a9a717f2e19ed9b37f7c6f"; // mascot6699@cruxdex.crux const user2PvtKey = "KyBuSe1MMV6NjJgZfyWuvgmxUeAYswLC2HrfYLUri9aP3AS5FBfr"; // release020@cruxdev.crux - -const _generateMnemonic = (): string => { - return blockstack.BlockstackWallet.generateMnemonic(); -} - -const _generateIdentityKeyPair = async (mnemonic: string): Promise => { - const wallet = new blockstack.BlockstackWallet(bip32.fromSeed(bip39.mnemonicToSeedSync(mnemonic))); - const { address, key, keyID} = wallet.getIdentityKeyPair(0); - const identityKeyPair: any = { - address, - privKey: key, - pubKey: keyID, - }; - return identityKeyPair; -} - describe('Test CruxServiceClient', function() { beforeEach(async function() { const HOST = "127.0.0.1"; const PORT = 1883; - const newMnemonic = _generateMnemonic(); - const identityKeyPair = await _generateIdentityKeyPair(newMnemonic); this.user2CruxId = "release020@cruxdev.crux"; this.user1KeyManager = new BasicKeyManager(user1PvtKey); this.user2KeyManager = new BasicKeyManager(user2PvtKey); this.userRepo = getCruxUserRepository({ blockstackInfrastructure: CruxSpec.blockstack.infrastructure, - cruxDomain: getCruxdevCruxDomain() + cruxDomain: getCruxdevCruxDomain(), + cacheStorage: new InMemStorage(), }); this.user1Data = await this.userRepo.getWithKey(this.user1KeyManager); this.user2Data = await this.userRepo.getWithKey(this.user2KeyManager); @@ -67,12 +50,12 @@ describe('Test CruxServiceClient', function() { isHost: true, cacheStorage: new InMemStorage(), }); - const cruxServiceClient = new CruxServiceClient(); - const serviceWalletClient = cruxServiceClient.getWalletClientForUser(new SecureCruxIdMessenger(this.userRepo, this.pubsubClientFactory, { + const cruxServiceClient = new CruxServiceClient({ cruxId: CruxId.fromString(this.user2CruxId), keyManager: this.user2KeyManager - }), this.user1Data.cruxID); - const addressMap = await serviceWalletClient.putAddressMap({"btc" : btcAddress}); + }, this.userRepo, this.pubsubClientFactory); + const remoteWalletClient = cruxServiceClient.getWalletClientForUser(this.user1Data.cruxID); + const addressMap = await remoteWalletClient.getAddressMap(); console.log("TESTCASE::Address Map: ", addressMap); }); }); \ No newline at end of file diff --git a/src/test/crux-messenger/test-remote-key-client-prod.ts b/src/test/crux-messenger/test-remote-key-client-prod.ts index 59428741..b9a9017c 100644 --- a/src/test/crux-messenger/test-remote-key-client-prod.ts +++ b/src/test/crux-messenger/test-remote-key-client-prod.ts @@ -5,12 +5,13 @@ import 'mocha'; import * as blockstack from "blockstack"; import {SecureCruxIdMessenger, RemoteKeyClient, RemoteKeyHost, RemoteKeyManager} from "../../core/domain-services"; import {BasicKeyManager, CruxNetPubSubClientFactory} from "../../infrastructure/implementations"; -import {CruxId} from "../../packages"; +import {CruxId, InMemStorage, BufferJSONSerializer} from "../../packages"; import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies, getCruxdevCruxDomain} from "../test-utils"; import { bip32 } from "bitcoinjs-lib"; import * as bip39 from "bip39"; import { getCruxUserRepository } from "../../application/clients"; import { CruxSpec } from "../../core/entities"; +import { ECIESEncryption } from "../../packages/encryption"; patchMissingDependencies(); @@ -30,7 +31,8 @@ describe('Test RemoteKeyClient - PROD', function() { this.user2KeyManager = new BasicKeyManager(user2PvtKey); this.userRepo = getCruxUserRepository({ blockstackInfrastructure: CruxSpec.blockstack.infrastructure, - cruxDomain: getCruxdevCruxDomain() + cruxDomain: getCruxdevCruxDomain(), + cacheStorage: new InMemStorage(), }); this.user1Data = await this.userRepo.getWithKey(this.user1KeyManager); this.user2Data = await this.userRepo.getWithKey(this.user2KeyManager); @@ -40,6 +42,10 @@ describe('Test RemoteKeyClient - PROD', function() { port: PORT, } }); + const toEncrypt = Buffer.from("content", "utf8"); + const encrypted = await ECIESEncryption.encrypt(toEncrypt, "0362f171a40ab5e6ad22275ec166f15a232b83a571bab9c30622ed2963f1da4c08"); + this.testEncryptedData = BufferJSONSerializer.bufferObjectToJSONString(encrypted); + console.log("TEST testEncryptedData: ", this.testEncryptedData); }); it('Basic Key Manager Send Receive - RemoteKeyManager - Prod', async function() { @@ -61,12 +67,12 @@ describe('Test RemoteKeyClient - PROD', function() { const publicKey = await remoteKeyManager.getPubKey(); console.log("TESTCASE::publicKey", publicKey); expect(publicKey).equals(testPubKey); - // const sharedSecret = await remoteKeyManager.deriveSharedSecret(testPubKey) - // console.log("TESTCASE::sharedSecret", sharedSecret); - // expect(sharedSecret).equals("d2744fdfa47538b816623e75cc783469cbe3d71da02965edd662ae3f45fbac3"); - // const decryptedMessage = await remoteKeyManager.decryptMessage("4b4f34746f434c30354349312b41314b554f644542773d3d"); - // console.log(decryptedMessage); - // expect(decryptedMessage).equals(""); + const sharedSecret = await remoteKeyManager.deriveSharedSecret(testPubKey) + console.log("TESTCASE::sharedSecret", sharedSecret); + expect(sharedSecret).equals("d2744fdfa47538b816623e75cc783469cbe3d71da02965edd662ae3f45fbac3"); + const decryptedMessage = await remoteKeyManager.decryptMessage(this.testEncryptedData); + console.log("TESTCASE::decryptedMessage", decryptedMessage); + expect(decryptedMessage).equals("content"); resolve(); }); }); diff --git a/src/test/crux-messenger/test-remote-key-client.ts b/src/test/crux-messenger/test-remote-key-client.ts index 28accce7..1dc2e081 100644 --- a/src/test/crux-messenger/test-remote-key-client.ts +++ b/src/test/crux-messenger/test-remote-key-client.ts @@ -52,40 +52,10 @@ describe('Test RemoteKeyClient', function() { },(err) => { reject(err) }); - remoteKeyHost.invocationListener((msg, senderId) => { - new Promise(async (resolve, reject) => { - const data = await remoteKeyHost.handleMessage(msg); - remoteKeyHost.sendInvocationResult(data, senderId); - resolve(); - }); - },(err) => { - }); await remoteKeyClient.invoke("getPubKey", []); }); }); - it('Invalid Basic Key Manager Send Receive (wrong method)', async function() { - const testErrorMsg = 'Invalid key manager method'; - return new Promise(async (resolve, reject) => { - const remoteKeyClient = new RemoteKeyClient(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { - cruxId: this.user1Data.cruxUser.cruxID, - keyManager: this.user1KeyManager - }), this.user2Data.cruxUser.cruxID); - - const remoteKeyHost = new RemoteKeyHost(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { - cruxId: this.user2Data.cruxUser.cruxID, - keyManager: this.user2KeyManager - }), this.user2KeyManager); - - remoteKeyHost.invocationListener(async (msg, senderId) => { - await expect(remoteKeyHost.handleMessage(msg)).to.be.rejectedWith(Error); - resolve(); - },(err) => { - }); - await remoteKeyClient.invoke("getPublicKey", []); - }); - }); - it('Basic Key Manager Send Receive - RemoteKeyManager', async function() { const testPubKey = "03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318"; return new Promise(async (resolve, reject) => { @@ -99,15 +69,6 @@ describe('Test RemoteKeyClient', function() { keyManager: this.user2KeyManager }), this.user2KeyManager); - remoteKeyHost.invocationListener((msg, senderId) => { - new Promise(async (resolve, reject) => { - console.log(msg); - const data = await remoteKeyHost.handleMessage(msg); - remoteKeyHost.sendInvocationResult(data, senderId); - resolve(); - }); - },(err) => { - }); const signedWebToken = await remoteKeyManager.signWebToken("1234567") console.log(signedWebToken); expect(signedWebToken).to.have.length(138); From 6ac6520c4d5ddf30e94134fbaee288e9f21513dc Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Fri, 29 May 2020 16:02:09 +0530 Subject: [PATCH 08/16] added putAddressMap testcase in cruxServiceClient --- .../test-crux-service-client-prod.ts | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/test/crux-messenger/test-crux-service-client-prod.ts b/src/test/crux-messenger/test-crux-service-client-prod.ts index 7e3f753d..cc1000ee 100644 --- a/src/test/crux-messenger/test-crux-service-client-prod.ts +++ b/src/test/crux-messenger/test-crux-service-client-prod.ts @@ -43,7 +43,7 @@ describe('Test CruxServiceClient', function() { } }); }); - it('Basic Key Manager Send Receive - CruxServiceClient', async function() { + it('Basic Key Manager Send Receive - CruxServiceClient - getAddressMap', async function() { const cruxWalletClient = new CruxWalletClient({ privateKey: user1PvtKey, walletClientName: "cruxdev", @@ -56,6 +56,26 @@ describe('Test CruxServiceClient', function() { }, this.userRepo, this.pubsubClientFactory); const remoteWalletClient = cruxServiceClient.getWalletClientForUser(this.user1Data.cruxID); const addressMap = await remoteWalletClient.getAddressMap(); - console.log("TESTCASE::Address Map: ", addressMap); + console.log("TESTCASE::AddressMap: ", addressMap); + }); + + it('Basic Key Manager Send Receive - CruxServiceClient - putAddressMap', async function() { + const cruxWalletClient = new CruxWalletClient({ + privateKey: user1PvtKey, + walletClientName: "cruxdev", + isHost: true, + cacheStorage: new InMemStorage(), + }); + const cruxServiceClient = new CruxServiceClient({ + cruxId: CruxId.fromString(this.user2CruxId), + keyManager: this.user2KeyManager + }, this.userRepo, this.pubsubClientFactory); + const remoteWalletClient = cruxServiceClient.getWalletClientForUser(this.user1Data.cruxID); + const addressMapResult = await remoteWalletClient.putAddressMap({ + "ltc": { + addressHash: "1HX4KvtPdg9QUYwQE1kNqTAjmNaDG12345" + } + }); + console.log("TESTCASE::Address Map: ", addressMapResult); }); }); \ No newline at end of file From 4444029c2f369ccdb20f2f43ab9c6c5e569d1887 Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Tue, 2 Jun 2020 14:45:47 +0530 Subject: [PATCH 09/16] modified remoteKeyManager, remoteKeyHost, remoteKeyClient functionalities --- .vscode/launch.json | 4 +- .vscode/settings.json | 2 +- package.json | 2 +- .../clients/crux-gateway-bridge-config.json | 4 +- .../clients/crux-service-client.ts | 14 ++-- src/application/clients/crux-wallet-client.ts | 1 + src/core/domain-services/crux-messenger.ts | 4 +- .../domain-services/remote-key-service.ts | 83 +++++++++---------- .../implementations/crux-messenger.ts | 14 ++-- .../test-key-management-protocol.ts | 12 +-- .../crux-messenger/test-remote-key-client.ts | 56 +++++++------ .../test-crux-service-client-prod.ts | 30 +++---- .../test-remote-key-client-prod.ts | 63 +++++++++----- ...uxid-messenger-prod-pubsubClientFactory.ts | 16 ++-- 14 files changed, 169 insertions(+), 136 deletions(-) rename src/test/{ => integration-tests}/crux-messenger/test-crux-service-client-prod.ts (74%) rename src/test/{ => integration-tests}/crux-messenger/test-remote-key-client-prod.ts (56%) diff --git a/.vscode/launch.json b/.vscode/launch.json index 3b9fd80c..d1b97cde 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -22,7 +22,7 @@ "jsdom-global/register", "--allow-uncaught", "--colors", - "--timeout 50000", + "--timeout 100000", // "--reporter", // "mocha-reporter", "${workspaceFolder}/src/test/*.ts" @@ -35,7 +35,7 @@ "request": "attach", "port": 9229, "protocol": "inspector", - "timeout": 30000, + "timeout": 100000, "stopOnEntry": false } ] diff --git a/.vscode/settings.json b/.vscode/settings.json index 6ab3ef93..613cb16f 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -6,7 +6,7 @@ }, "mochaExplorer.files": ["src/test/*.ts", "src/test/crux-messenger/*.ts", "src/test/integration-tests/crux-messenger/*.ts"], "mochaExplorer.require": ["ts-node/register", "mock-local-storage", "jsdom-global/register"], - "mochaExplorer.timeout": 80000, + "mochaExplorer.timeout": 100000, "testExplorer.codeLens": true, "testExplorer.gutterDecoration": true, "testExplorer.onStart": "reset", diff --git a/package.json b/package.json index 5883bce7..176216c4 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "test": "TS_NODE_PROJECT='./src/test/tsconfig.commonjs.json' TS_NODE_TRANSPILE_ONLY=true ./node_modules/.bin/mocha --exit --require ts-node/register --require mock-local-storage --require jsdom-global/register --allow-uncaught --colors --reporter mocha-reporter --timeout 50000 src/test/*.ts src/test/crux-messenger/*.ts", "start-bridge-server": "node dist/crux-gateway-bridge-without-auth.js &", "stop-bridge-server": "pkill -- signal SIGINT crux-gateway-bridge-server-without-auth", - "integration-test": "TS_NODE_PROJECT='./src/test/tsconfig.commonjs.json' TS_NODE_TRANSPILE_ONLY=true ./node_modules/.bin/mocha --exit --require ts-node/register --require mock-local-storage --require jsdom-global/register --allow-uncaught --colors --reporter mocha-reporter --timeout 50000 src/test/integration-tests/crux-messenger/*.ts", + "integration-test": "TS_NODE_PROJECT='./src/test/tsconfig.commonjs.json' TS_NODE_TRANSPILE_ONLY=true ./node_modules/.bin/mocha --exit --require ts-node/register --require mock-local-storage --require jsdom-global/register --allow-uncaught --colors --reporter mocha-reporter --timeout 80000 src/test/integration-tests/crux-messenger/*.ts", "integration": "npm run build-crux-bridge-server-without-auth && npm run start-bridge-server && npm run integration-test && npm run stop-bridge-server", "copy-latest-docs": "cp -a docs/$npm_package_version/. docs/", "version-docs": "./node_modules/.bin/typedoc --out docs/$npm_package_version src/index.ts", diff --git a/src/application/clients/crux-gateway-bridge-config.json b/src/application/clients/crux-gateway-bridge-config.json index d4911c3c..e7732882 100644 --- a/src/application/clients/crux-gateway-bridge-config.json +++ b/src/application/clients/crux-gateway-bridge-config.json @@ -1,9 +1,9 @@ { "HOST_URL": { - "BROKER_HOST": "127.0.0.1" + "BROKER_HOST": "broker.hivemq.com" }, "PORTS": { - "BROKER_PORT": 1883, + "BROKER_PORT": 8000, "TCP_PORT": 4005 } } diff --git a/src/application/clients/crux-service-client.ts b/src/application/clients/crux-service-client.ts index 3d28fcea..9d950143 100644 --- a/src/application/clients/crux-service-client.ts +++ b/src/application/clients/crux-service-client.ts @@ -1,20 +1,24 @@ -import { RemoteKeyManager, SecureCruxIdMessenger } from "../../core/domain-services"; +import { RemoteKeyManager, SecureCruxNetwork } from "../../core/domain-services"; import { CruxId, InMemStorage } from "../../packages/"; import { CruxWalletClient } from "./crux-wallet-client"; export class CruxServiceClient { private selfIdClaim: any; - private secureCruxIdMessenger: SecureCruxIdMessenger; + private secureCruxNetwork: SecureCruxNetwork; constructor(selfIdClaim: any, userRepo: any, pubsubClientFactory: any) { this.selfIdClaim = selfIdClaim; - this.secureCruxIdMessenger = new SecureCruxIdMessenger(userRepo, pubsubClientFactory, selfIdClaim); + this.secureCruxNetwork = new SecureCruxNetwork(userRepo, pubsubClientFactory, selfIdClaim); } - public getWalletClientForUser(remoteUserId: CruxId) { + public async getWalletClientForUser(remoteUserId: CruxId) { + await this.secureCruxNetwork.initialize(); + const remoteKeyManager = new RemoteKeyManager(this.secureCruxNetwork, remoteUserId); + await remoteKeyManager.initialize(); return new CruxWalletClient({ cacheStorage: new InMemStorage(), - privateKey: new RemoteKeyManager(this.secureCruxIdMessenger, remoteUserId), + // @ts-ignore + privateKey: remoteKeyManager, walletClientName: remoteUserId.components.domain, }); } diff --git a/src/application/clients/crux-wallet-client.ts b/src/application/clients/crux-wallet-client.ts index 6266f864..983425f3 100644 --- a/src/application/clients/crux-wallet-client.ts +++ b/src/application/clients/crux-wallet-client.ts @@ -472,6 +472,7 @@ export class CruxWalletClient { this.paymentProtocolMessenger = new CruxProtocolMessenger(this.secureCruxNetwork, cruxPaymentProtocol); const remoteKeyHost = new RemoteKeyHost(this.secureCruxNetwork, this.keyManager!); this.remoteKeyHost = remoteKeyHost; + await this.remoteKeyHost.initialize(); } } diff --git a/src/core/domain-services/crux-messenger.ts b/src/core/domain-services/crux-messenger.ts index 39db8f78..4371e1cd 100644 --- a/src/core/domain-services/crux-messenger.ts +++ b/src/core/domain-services/crux-messenger.ts @@ -252,7 +252,9 @@ export class SecureContext { data, }; const serializedSecurePacket = JSON.stringify(securePacket); - + if (typeof recipientId === "string") { + recipientId = CruxId.fromString(recipientId); + } const recipientCruxUser: CruxUser | undefined = await this.cruxUserRepo.getByCruxId(recipientId); if (!recipientCruxUser) { throw Error("No Such CRUX User Found"); diff --git a/src/core/domain-services/remote-key-service.ts b/src/core/domain-services/remote-key-service.ts index 5ba8e18d..e2bb39f6 100644 --- a/src/core/domain-services/remote-key-service.ts +++ b/src/core/domain-services/remote-key-service.ts @@ -2,23 +2,28 @@ import {makeUUID4} from "blockstack/lib"; import { createNanoEvents, DefaultEvents, Emitter } from "nanoevents"; import { CruxId } from "src/packages"; import { IKeyManager } from "../interfaces"; -import { SecureCruxIdMessenger } from "./crux-messenger"; +import { SecureCruxNetwork } from "./crux-messenger"; const VALID_METHODS = ["signWebToken", "getPubKey", "deriveSharedSecret", "decryptMessage"]; export class RemoteKeyClient { - private secureCruxIdMessenger: SecureCruxIdMessenger; + private secureCruxNetwork: SecureCruxNetwork; private remoteUserId: CruxId; private emitter: Emitter; - constructor(secureCruxIdMessenger: SecureCruxIdMessenger, remoteUserId: CruxId) { - this.secureCruxIdMessenger = secureCruxIdMessenger; + constructor(secureCruxNetwork: SecureCruxNetwork, remoteUserId: CruxId) { + this.secureCruxNetwork = secureCruxNetwork; this.remoteUserId = remoteUserId; this.emitter = createNanoEvents(); - this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => { - console.log("Inside RemoteKeyClient Constructor:: ", msg, senderId); + } + + public async initialize() { + this.secureCruxNetwork.receive(async (msg: any, senderId: CruxId | undefined) => { + console.log("Inside RemoteKeyClient::initialize::Msg, senderId: ", msg, senderId); this.emitter.emit(msg.invocationId, msg, senderId); - }, (err: any) => { + }); + this.secureCruxNetwork.onError((err: any) => { + console.log("errorinvocationListener", err); this.emitter.emit("error", err); return; }); @@ -26,31 +31,18 @@ export class RemoteKeyClient { public async invoke(method: string, args: any[]) { console.log("RemoteKeyClient::Inside Invoke"); - if (!this.secureCruxIdMessenger) { - throw Error("RemoteKeyClient cannot send with no selfMessenger"); + if (!this.secureCruxNetwork) { + throw Error("RemoteKeyClient cannot send with no secureCruxNetwork"); } const methodData = this.generateMethodData(method, args); console.log("RemoteKeyClient::Inside Invoke, RemoteUserId, MethodData", this.remoteUserId, methodData); - await this.secureCruxIdMessenger.send(methodData, this.remoteUserId); + await this.secureCruxNetwork.send(this.remoteUserId, methodData); return methodData.invocationId; } - public invokeResult = (resultCallback: (msg: any, senderId: CruxId | undefined) => any, errorCallback: (err: any) => any): void => { - if (!this.secureCruxIdMessenger) { - throw Error("RemoteKeyClient cannot listen with no selfMessenger"); - } - this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => { - console.log("RemoteKeyClient::Inside invokeresult", msg, senderId); - resultCallback(msg, senderId); - }, (err: any) => { - errorCallback(err); - return; - }); - } - public listenToInvocation = (invocationId: string, resultCallback: (msg: any, senderId: CruxId | undefined) => any, errorCallback: (err: any) => any): void => { - if (!this.secureCruxIdMessenger) { - throw Error("RemoteKeyClient cannot listen with no selfMessenger"); + if (!this.secureCruxNetwork) { + throw Error("RemoteKeyClient cannot listen with no secureCruxNetwork"); } console.log("RemoteKeyClient::ListenToInvocation::invocationId", invocationId); this.emitter.on(invocationId, resultCallback); @@ -67,30 +59,33 @@ export class RemoteKeyClient { } export class RemoteKeyHost { - private secureCruxIdMessenger: SecureCruxIdMessenger; + private secureCruxNetwork: SecureCruxNetwork; private keyManager: IKeyManager; - constructor(secureCruxIdMessenger: SecureCruxIdMessenger, keyManager: IKeyManager) { + constructor(secureCruxNetwork: SecureCruxNetwork, keyManager: IKeyManager) { this.keyManager = keyManager; - this.secureCruxIdMessenger = secureCruxIdMessenger; - this.secureCruxIdMessenger.listen(async (msg: any, senderId: CruxId | undefined) => { - console.log("Inside RemoteKeyHost::Constructor::Msg, senderId: ", msg, senderId); + this.secureCruxNetwork = secureCruxNetwork; + } + + public async initialize() { + this.secureCruxNetwork.receive(async (msg: any, senderId: CruxId | undefined) => { + console.log("Inside RemoteKeyHost::in::Msg, senderId: ", msg, senderId); const data = await this.handleMessage(msg); - console.log("Inside RemoteKeyHost::Constructor::Data(handleMessage): ", data); - this.sendInvocationResult(data, senderId); - }, (err: any) => { + console.log("Inside RemoteKeyHost::initialize::Data(handleMessage): ", data); + this.sendInvocationResult(data, senderId!); + }); + this.secureCruxNetwork.onError((err: any) => { console.log("errorinvocationListener", err); return; }); } - private async sendInvocationResult(result: any, receiverId: CruxId) { - if (!this.secureCruxIdMessenger) { + if (!this.secureCruxNetwork) { throw Error("RemoteKeyClient cannot send with no selfMessenger"); } const resultData = this.generateInvocationResponse(result); console.log("RemoteKeyHost::Inside sendInvocationResult::resultData: ", resultData); - await this.secureCruxIdMessenger.send(resultData, receiverId); + await this.secureCruxNetwork.send(receiverId, resultData); } private async handleMessage(message: any) { @@ -138,12 +133,16 @@ export class RemoteKeyManager implements IKeyManager { private remoteKeyClient: RemoteKeyClient; private remoteUserId: CruxId; - constructor(secureCruxIdMessenger: SecureCruxIdMessenger, remoteUserId: CruxId) { - this.remoteKeyClient = new RemoteKeyClient(secureCruxIdMessenger, remoteUserId); + constructor(secureCruxNetwork: SecureCruxNetwork, remoteUserId: CruxId) { + this.remoteKeyClient = new RemoteKeyClient(secureCruxNetwork, remoteUserId); this.remoteUserId = remoteUserId; } + + public async initialize() { + await this.remoteKeyClient.initialize(); + } // @ts-ignore - public async signWebToken(token: any) { + public signWebToken = async (token: any) => { return new Promise(async (resolve, reject) => { const invocationId = await this.remoteKeyClient.invoke("signWebToken", [token]); console.log("RemoteKeyManager::signWebToken::invokationId: ", invocationId); @@ -156,7 +155,7 @@ export class RemoteKeyManager implements IKeyManager { }); } // @ts-ignore - public async getPubKey() { + public getPubKey = async () => { return new Promise(async (resolve, reject) => { const invocationId = await this.remoteKeyClient.invoke("getPubKey", []); console.log("RemoteKeyManager::getPubKey::invokationId: ", invocationId); @@ -169,7 +168,7 @@ export class RemoteKeyManager implements IKeyManager { }); } // @ts-ignore - public async deriveSharedSecret(publicKey: string) { + public deriveSharedSecret = async (publicKey: string) => { const invocationId = await this.remoteKeyClient.invoke("deriveSharedSecret", [publicKey]); console.log("RemoteKeyManager::deriveSharedSecret::invokationId: ", invocationId); return new Promise(async (resolve, reject) => { @@ -182,7 +181,7 @@ export class RemoteKeyManager implements IKeyManager { }); } // @ts-ignore - public async decryptMessage(encryptedMessage: string) { + public decryptMessage = async (encryptedMessage: string) => { console.log("RemoteKeyManager::decryptMessage::entry: encryptedMessage: ", encryptedMessage); const invocationId = await this.remoteKeyClient.invoke("decryptMessage", [encryptedMessage]); console.log("RemoteKeyManager::decryptMessage::invokationId: ", invocationId); diff --git a/src/infrastructure/implementations/crux-messenger.ts b/src/infrastructure/implementations/crux-messenger.ts index 8e9b7eae..c44ded55 100644 --- a/src/infrastructure/implementations/crux-messenger.ts +++ b/src/infrastructure/implementations/crux-messenger.ts @@ -124,7 +124,7 @@ export class PahoClient implements IPubSubClient { } public connect = () => { - console.log("PahoClient trying to connect"); + console.log("PahoClient trying to connect: ", this.config); if (this.client && this.client.isConnected()) { console.log("Already Connected, returning"); return; @@ -140,7 +140,7 @@ export class PahoClient implements IPubSubClient { console.log("PahoClient - trying to connect"); this.client.connect({ onSuccess: (onSuccessData: any) => { - console.log("PahoClient - connect success!"); + console.log("PahoClient - connect success!", this.config); this.emitter.emit("connectSuccess", onSuccessData); res(onSuccessData); }, @@ -162,7 +162,7 @@ export class PahoClient implements IPubSubClient { } } private onMessageArrived = (msg: any) => { - console.log("recd message from paho library: ", msg.uniqueId, msg); + console.log("recd message from paho library: ", msg.uniqueId, msg, msg.payloadString, msg.destinationName); this.emitter.emit(msg.destinationName, msg.destinationName, msg.payloadString); } private onMessageDelivered = (msg: any) => { @@ -175,7 +175,7 @@ export class CruxNetPubSubClientFactory implements IPubSubClientFactory { private options: ICruxNetClientFactoryOptions; private defaultSubscribeOptions: { qos: number }; private defaultClientMqttOptions: { clean: boolean }; - private bufferPahoClient?: PahoClient; + private bufferPahoClient: any = {}; constructor(options: ICruxNetClientFactoryOptions) { this.options = options; this.defaultSubscribeOptions = { @@ -186,9 +186,9 @@ export class CruxNetPubSubClientFactory implements IPubSubClientFactory { }; } public getClient = (from: CruxId, keyManager: IKeyManager, to?: CruxId): IPubSubClient => { - if (this.bufferPahoClient) { return this.bufferPahoClient; } + if (this.bufferPahoClient[from.toString()]) { return this.bufferPahoClient[from.toString()]; } const overrideOpts = this.getDomainLevelClientOptions(to ? to : from); - this.bufferPahoClient = new PahoClient({ + this.bufferPahoClient[from.toString()] = new PahoClient({ clientOptions: { clientId: from.toString(), host: overrideOpts ? overrideOpts.host : this.options.defaultLinkServer.host, @@ -198,7 +198,7 @@ export class CruxNetPubSubClientFactory implements IPubSubClientFactory { }, subscribeOptions: this.defaultSubscribeOptions, }); - return this.bufferPahoClient; + return this.bufferPahoClient[from.toString()]; } private getDomainLevelClientOptions = (cruxId: CruxId): {host: string, port: number, path: string} | undefined => { // TODO Implement diff --git a/src/test/crux-messenger/test-key-management-protocol.ts b/src/test/crux-messenger/test-key-management-protocol.ts index cc6da230..300729f6 100644 --- a/src/test/crux-messenger/test-key-management-protocol.ts +++ b/src/test/crux-messenger/test-key-management-protocol.ts @@ -2,7 +2,7 @@ import * as chai from "chai"; import sinon from "sinon"; import chaiAsPromised from "chai-as-promised"; import 'mocha'; -import {SecureCruxIdMessenger, CertificateManager, CruxConnectProtocolMessenger} from "../../core/domain-services"; +import {SecureCruxNetwork, CertificateManager, CruxProtocolMessenger} from "../../core/domain-services"; import {ICruxUserRepository, IProtocolMessage, IPubSubClientFactory} from "../../core/interfaces"; import {BasicKeyManager, cruxPaymentProtocol, keyManagementProtocol} from "../../infrastructure/implementations"; import {CruxId} from "../../packages"; @@ -31,16 +31,18 @@ describe('Test Key Management Protocol', function() { userStore.store(user2Data.cruxUser); const inmemUserRepo = new InMemoryCruxUserRepository(userStore); const pubsubClientFactory = new InMemoryPubSubClientFactory(); - const user1Messenger = new SecureCruxIdMessenger(inmemUserRepo, pubsubClientFactory, { + const user1Messenger = new SecureCruxNetwork(inmemUserRepo, pubsubClientFactory, { cruxId: this.user1Data.cruxUser.cruxID, keyManager: new BasicKeyManager(this.user1Data.pvtKey) }); - const user2Messenger = new SecureCruxIdMessenger(inmemUserRepo, pubsubClientFactory, { + const user2Messenger = new SecureCruxNetwork(inmemUserRepo, pubsubClientFactory, { cruxId: this.user2Data.cruxUser.cruxID, keyManager: new BasicKeyManager(this.user2Data.pvtKey) }); - this.user1KeyManagerProtocolMessenger = new CruxConnectProtocolMessenger(user1Messenger, keyManagementProtocol); - this.user2KeyManagerProtocolMessenger = new CruxConnectProtocolMessenger(user2Messenger, keyManagementProtocol); + await user1Messenger.initialize(); + await user2Messenger.initialize(); + this.user1KeyManagerProtocolMessenger = new CruxProtocolMessenger(user1Messenger, keyManagementProtocol); + this.user2KeyManagerProtocolMessenger = new CruxProtocolMessenger(user2Messenger, keyManagementProtocol); }); diff --git a/src/test/crux-messenger/test-remote-key-client.ts b/src/test/crux-messenger/test-remote-key-client.ts index 1dc2e081..0b02e265 100644 --- a/src/test/crux-messenger/test-remote-key-client.ts +++ b/src/test/crux-messenger/test-remote-key-client.ts @@ -2,12 +2,13 @@ import * as chai from "chai"; import sinon from "sinon"; import chaiAsPromised from "chai-as-promised"; import 'mocha'; -import {SecureCruxIdMessenger, RemoteKeyClient, RemoteKeyHost, RemoteKeyManager} from "../../core/domain-services"; +import {SecureCruxNetwork, RemoteKeyClient, RemoteKeyHost, RemoteKeyManager} from "../../core/domain-services"; import {BasicKeyManager} from "../../infrastructure/implementations"; -import {CruxId} from "../../packages"; +import {CruxId, BufferJSONSerializer} from "../../packages"; import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies} from "../test-utils"; import {InMemoryPubSubClientFactory, InMemoryMaliciousPubSubClientFactory} from "./inmemory-implementations"; import {getMockUserBar123CSTestWallet, getMockUserFoo123CSTestWallet, getMockUserFooBar123CSTestWallet} from "./utils"; +import { ECIESEncryption } from "../../packages/encryption"; patchMissingDependencies(); @@ -31,44 +32,45 @@ describe('Test RemoteKeyClient', function() { this.pubsubClientFactory = new InMemoryPubSubClientFactory(); this.user1KeyManager = new BasicKeyManager(this.user1Data.pvtKey); this.user2KeyManager = new BasicKeyManager(this.user2Data.pvtKey); + const toEncrypt = Buffer.from("content", "utf8"); + const encrypted = await ECIESEncryption.encrypt(toEncrypt, this.user2KeyManager.publicKey); + this.testEncryptedData = BufferJSONSerializer.bufferObjectToJSONString(encrypted); + this.secureCruxNetwork1 = new SecureCruxNetwork(this.inmemUserRepo, this.pubsubClientFactory, { + cruxId: this.user1Data.cruxUser.cruxID, + keyManager: this.user1KeyManager + }); + this.secureCruxNetwork2 = new SecureCruxNetwork(this.inmemUserRepo, this.pubsubClientFactory, { + cruxId: this.user2Data.cruxUser.cruxID, + keyManager: this.user2KeyManager + }); + this.secureCruxNetwork1.initialize(); + this.secureCruxNetwork2.initialize(); }); it('Basic Key Manager Send Receive', async function() { const testPublicKey = '03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318'; return new Promise(async (resolve, reject) => { - const remoteKeyClient = new RemoteKeyClient(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { - cruxId: this.user1Data.cruxUser.cruxID, - keyManager: this.user1KeyManager - }), this.user2Data.cruxUser.cruxID); - - const remoteKeyHost = new RemoteKeyHost(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { - cruxId: this.user2Data.cruxUser.cruxID, - keyManager: this.user2KeyManager - }), this.user2KeyManager); - - remoteKeyClient.invokeResult((msg, senderId) => { + const remoteKeyClient = new RemoteKeyClient(this.secureCruxNetwork1, this.user2Data.cruxUser.cruxID); + await remoteKeyClient.initialize(); + const remoteKeyHost = new RemoteKeyHost(this.secureCruxNetwork2, this.user2KeyManager); + await remoteKeyHost.initialize() + const invocationId = await remoteKeyClient.invoke("getPubKey", []); + remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { expect(msg.result.data).equals(testPublicKey); resolve(msg) },(err) => { reject(err) }); - await remoteKeyClient.invoke("getPubKey", []); }); }); it('Basic Key Manager Send Receive - RemoteKeyManager', async function() { const testPubKey = "03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318"; return new Promise(async (resolve, reject) => { - const remoteKeyManager = new RemoteKeyManager(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { - cruxId: this.user1Data.cruxUser.cruxID, - keyManager: this.user1KeyManager - }), this.user2Data.cruxUser.cruxID); - - const remoteKeyHost = new RemoteKeyHost(new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { - cruxId: this.user2Data.cruxUser.cruxID, - keyManager: this.user2KeyManager - }), this.user2KeyManager); - + const remoteKeyManager = new RemoteKeyManager(this.secureCruxNetwork1, this.user2Data.cruxUser.cruxID); + const remoteKeyHost = new RemoteKeyHost(this.secureCruxNetwork2, this.user2KeyManager); + await remoteKeyManager.initialize(); + await remoteKeyHost.initialize(); const signedWebToken = await remoteKeyManager.signWebToken("1234567") console.log(signedWebToken); expect(signedWebToken).to.have.length(138); @@ -78,9 +80,9 @@ describe('Test RemoteKeyClient', function() { const sharedSecret = await remoteKeyManager.deriveSharedSecret(testPubKey) console.log(sharedSecret); expect(sharedSecret).to.equals("3380b4752c9cebf96bc55491ef0ee67ae1d564c0bb931a0c6e8875be6e3bee5"); - // const decryptedMessage = await remoteKeyManager.decryptMessage("4b4f34746f434c30354349312b41314b554f644542773d3d"); - // console.log(decryptedMessage); - // expect(decryptedMessage).to.equals(""); + const decryptedMessage = await remoteKeyManager.decryptMessage(this.testEncryptedData); + console.log(decryptedMessage); + expect(decryptedMessage).to.equals("content"); resolve(); }); }); diff --git a/src/test/crux-messenger/test-crux-service-client-prod.ts b/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts similarity index 74% rename from src/test/crux-messenger/test-crux-service-client-prod.ts rename to src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts index cc1000ee..91b373a3 100644 --- a/src/test/crux-messenger/test-crux-service-client-prod.ts +++ b/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts @@ -3,12 +3,12 @@ import * as blockstack from "blockstack"; import sinon from "sinon"; import chaiAsPromised from "chai-as-promised"; import 'mocha'; -import {SecureCruxIdMessenger} from "../../core/domain-services"; -import {CruxServiceClient, getCruxUserRepository, CruxWalletClient} from "../../application/clients" -import {BasicKeyManager, CruxNetPubSubClientFactory, StrongPubSubClient} from "../../infrastructure/implementations"; -import {patchMissingDependencies, getCruxdevCruxDomain} from "../test-utils"; -import { CruxSpec, IAddress } from "../../core/entities"; -import { CruxId, InMemStorage } from "../../packages"; +import {SecureCruxNetwork} from "../../../core/domain-services"; +import {CruxServiceClient, getCruxUserRepository, CruxWalletClient} from "../../../application/clients" +import {BasicKeyManager, CruxNetPubSubClientFactory} from "../../../infrastructure/implementations"; +import {patchMissingDependencies, getCruxdevCruxDomain} from "../../test-utils"; +import { CruxSpec, IAddress } from "../../../core/entities"; +import { CruxId, InMemStorage } from "../../../packages"; import { bip32 } from "bitcoinjs-lib"; import * as bip39 from "bip39"; @@ -22,10 +22,10 @@ const btcAddress: IAddress = {addressHash: "1HX4KvtPdg9QUYwQE1kNqTAjmNaDG7w82V"} const user1PvtKey = "cdf2d276caf0c9c34258ed6ebd0e60e0e8b3d9a7b8a9a717f2e19ed9b37f7c6f"; // mascot6699@cruxdex.crux const user2PvtKey = "KyBuSe1MMV6NjJgZfyWuvgmxUeAYswLC2HrfYLUri9aP3AS5FBfr"; // release020@cruxdev.crux -describe('Test CruxServiceClient', function() { +describe('Test CruxServiceClient - Prod', function() { beforeEach(async function() { - const HOST = "127.0.0.1"; - const PORT = 1883; + const HOST = "broker.hivemq.com"; + const PORT = 8000; this.user2CruxId = "release020@cruxdev.crux"; this.user1KeyManager = new BasicKeyManager(user1PvtKey); this.user2KeyManager = new BasicKeyManager(user2PvtKey); @@ -40,10 +40,11 @@ describe('Test CruxServiceClient', function() { defaultLinkServer: { host: HOST, port: PORT, + path: "/mqtt" } }); }); - it('Basic Key Manager Send Receive - CruxServiceClient - getAddressMap', async function() { + it('Send Receive - CruxWalletClient<->CruxServiceClient - getAddressMap', async function() { const cruxWalletClient = new CruxWalletClient({ privateKey: user1PvtKey, walletClientName: "cruxdev", @@ -54,12 +55,13 @@ describe('Test CruxServiceClient', function() { cruxId: CruxId.fromString(this.user2CruxId), keyManager: this.user2KeyManager }, this.userRepo, this.pubsubClientFactory); - const remoteWalletClient = cruxServiceClient.getWalletClientForUser(this.user1Data.cruxID); + + const remoteWalletClient = await cruxServiceClient.getWalletClientForUser(this.user1Data.cruxID); const addressMap = await remoteWalletClient.getAddressMap(); console.log("TESTCASE::AddressMap: ", addressMap); }); - it('Basic Key Manager Send Receive - CruxServiceClient - putAddressMap', async function() { + it('Send Receive - CruxWalletClient<->CruxServiceClient - putAddressMap', async function() { const cruxWalletClient = new CruxWalletClient({ privateKey: user1PvtKey, walletClientName: "cruxdev", @@ -70,10 +72,10 @@ describe('Test CruxServiceClient', function() { cruxId: CruxId.fromString(this.user2CruxId), keyManager: this.user2KeyManager }, this.userRepo, this.pubsubClientFactory); - const remoteWalletClient = cruxServiceClient.getWalletClientForUser(this.user1Data.cruxID); + const remoteWalletClient = await cruxServiceClient.getWalletClientForUser(this.user1Data.cruxID); const addressMapResult = await remoteWalletClient.putAddressMap({ "ltc": { - addressHash: "1HX4KvtPdg9QUYwQE1kNqTAjmNaDG12345" + addressHash: "1HX4KvtPdg9QUYwQE1kNqTAjmNaDG12346" } }); console.log("TESTCASE::Address Map: ", addressMapResult); diff --git a/src/test/crux-messenger/test-remote-key-client-prod.ts b/src/test/integration-tests/crux-messenger/test-remote-key-client-prod.ts similarity index 56% rename from src/test/crux-messenger/test-remote-key-client-prod.ts rename to src/test/integration-tests/crux-messenger/test-remote-key-client-prod.ts index b9a9017c..4984f9a8 100644 --- a/src/test/crux-messenger/test-remote-key-client-prod.ts +++ b/src/test/integration-tests/crux-messenger/test-remote-key-client-prod.ts @@ -3,15 +3,15 @@ import sinon from "sinon"; import chaiAsPromised from "chai-as-promised"; import 'mocha'; import * as blockstack from "blockstack"; -import {SecureCruxIdMessenger, RemoteKeyClient, RemoteKeyHost, RemoteKeyManager} from "../../core/domain-services"; -import {BasicKeyManager, CruxNetPubSubClientFactory} from "../../infrastructure/implementations"; -import {CruxId, InMemStorage, BufferJSONSerializer} from "../../packages"; -import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies, getCruxdevCruxDomain} from "../test-utils"; +import {RemoteKeyClient, RemoteKeyHost, RemoteKeyManager, SecureCruxNetwork} from "../../../core/domain-services"; +import {BasicKeyManager, CruxNetPubSubClientFactory} from "../../../infrastructure/implementations"; +import {CruxId, InMemStorage, BufferJSONSerializer} from "../../../packages"; +import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies, getCruxdevCruxDomain} from "../../test-utils"; import { bip32 } from "bitcoinjs-lib"; import * as bip39 from "bip39"; -import { getCruxUserRepository } from "../../application/clients"; -import { CruxSpec } from "../../core/entities"; -import { ECIESEncryption } from "../../packages/encryption"; +import { getCruxUserRepository } from "../../../application/clients"; +import { CruxSpec } from "../../../core/entities"; +import { ECIESEncryption } from "../../../packages/encryption"; patchMissingDependencies(); @@ -24,8 +24,8 @@ const user2PvtKey = "KyBuSe1MMV6NjJgZfyWuvgmxUeAYswLC2HrfYLUri9aP3AS5FBfr"; // r describe('Test RemoteKeyClient - PROD', function() { beforeEach(async function() { - const HOST = "127.0.0.1"; - const PORT = 1883; + const HOST = "broker.hivemq.com"; + const PORT = 8000; this.user2CruxId = "release020@cruxdev.crux"; this.user1KeyManager = new BasicKeyManager(user1PvtKey); this.user2KeyManager = new BasicKeyManager(user2PvtKey); @@ -40,27 +40,48 @@ describe('Test RemoteKeyClient - PROD', function() { defaultLinkServer: { host: HOST, port: PORT, + path: "/mqtt" } }); const toEncrypt = Buffer.from("content", "utf8"); const encrypted = await ECIESEncryption.encrypt(toEncrypt, "0362f171a40ab5e6ad22275ec166f15a232b83a571bab9c30622ed2963f1da4c08"); this.testEncryptedData = BufferJSONSerializer.bufferObjectToJSONString(encrypted); - console.log("TEST testEncryptedData: ", this.testEncryptedData); + this.secureCruxNetwork1 = new SecureCruxNetwork(this.userRepo, this.pubsubClientFactory, { + cruxId: this.user1Data.cruxID, + keyManager: this.user1KeyManager + }); + this.secureCruxNetwork2 = new SecureCruxNetwork(this.userRepo, this.pubsubClientFactory, { + cruxId: this.user2Data.cruxID, + keyManager: this.user2KeyManager + }); + await this.secureCruxNetwork1.initialize(); + await this.secureCruxNetwork2.initialize(); }); - it('Basic Key Manager Send Receive - RemoteKeyManager - Prod', async function() { - const testPubKey = "0362f171a40ab5e6ad22275ec166f15a232b83a571bab9c30622ed2963f1da4c08"; + it('Send Receive RemoteKeyClient<->RemoteKeyHost - Prod', async function() { + const testPublicKey = '0239d9d97d5b8973fba462b1a014bcbb84d056061234fd375442a7ef0620ea88c3'; return new Promise(async (resolve, reject) => { - const remoteKeyManager = new RemoteKeyManager(new SecureCruxIdMessenger(this.userRepo, this.pubsubClientFactory, { - cruxId: this.user2Data.cruxID, - keyManager: this.user2KeyManager - }), this.user1Data.cruxID); - - const remoteKeyHost = new RemoteKeyHost(new SecureCruxIdMessenger(this.userRepo, this.pubsubClientFactory, { - cruxId: this.user1Data.cruxID, - keyManager: this.user1KeyManager - }), this.user1KeyManager); + const remoteKeyClient = new RemoteKeyClient(this.secureCruxNetwork1, this.user2Data.cruxID); + await remoteKeyClient.initialize(); + const remoteKeyHost = new RemoteKeyHost(this.secureCruxNetwork2, this.user2KeyManager); + await remoteKeyHost.initialize() + const invocationId = await remoteKeyClient.invoke("getPubKey", []); + remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { + expect(msg.result.data).equals(testPublicKey); + resolve(msg) + },(err) => { + reject(err) + }); + }); + }); + it('Send Receive RemoteKeyManager<->RemoteKeyHost - RemoteKeyManager - Prod', async function() { + const testPubKey = "0362f171a40ab5e6ad22275ec166f15a232b83a571bab9c30622ed2963f1da4c08"; + return new Promise(async (resolve, reject) => { + const remoteKeyManager = new RemoteKeyManager(this.secureCruxNetwork2, this.user1Data.cruxID); + await remoteKeyManager.initialize(); + const remoteKeyHost = new RemoteKeyHost(this.secureCruxNetwork1, this.user1KeyManager); + await remoteKeyHost.initialize(); const signedWebToken = await remoteKeyManager.signWebToken("1234567") console.log("TESTCASE::signWebToken:", signedWebToken); expect(signedWebToken).to.have.length(138); diff --git a/src/test/integration-tests/crux-messenger/test-secure-cruxid-messenger-prod-pubsubClientFactory.ts b/src/test/integration-tests/crux-messenger/test-secure-cruxid-messenger-prod-pubsubClientFactory.ts index 3d024bbd..2ea9db04 100644 --- a/src/test/integration-tests/crux-messenger/test-secure-cruxid-messenger-prod-pubsubClientFactory.ts +++ b/src/test/integration-tests/crux-messenger/test-secure-cruxid-messenger-prod-pubsubClientFactory.ts @@ -2,7 +2,7 @@ import * as chai from "chai"; import sinon from "sinon"; import chaiAsPromised from "chai-as-promised"; import 'mocha'; -import {SecureCruxIdMessenger, CertificateManager} from "../../../core/domain-services"; +import {SecureCruxNetwork, CertificateManager} from "../../../core/domain-services"; import {BasicKeyManager, CruxNetPubSubClientFactory} from "../../../infrastructure/implementations"; import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies} from "../../test-utils"; import {getMockUserBar123CSTestWallet, getMockUserFoo123CSTestWallet} from "../../crux-messenger/utils"; @@ -36,25 +36,25 @@ describe('Test Secure Crux Messenger - Prod pubsubClientFactory', function() { }); }); - it('Basic Send Receive Test - Prod pubsubClientFactory', function() { + it('Basic Send Receive Test - Prod PubsubClientFactory', function() { const testmsg = 'HelloWorld'; return new Promise(async (resolve, reject) => { - const user1Messenger = new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { + const user1Messenger = new SecureCruxNetwork(this.inmemUserRepo, this.pubsubClientFactory, { cruxId: this.user1Data.cruxUser.cruxID, keyManager: new BasicKeyManager(this.user1Data.pvtKey) }); - const user2Messenger = new SecureCruxIdMessenger(this.inmemUserRepo, this.pubsubClientFactory, { + const user2Messenger = new SecureCruxNetwork(this.inmemUserRepo, this.pubsubClientFactory, { cruxId: this.user2Data.cruxUser.cruxID, keyManager: new BasicKeyManager(this.user2Data.pvtKey) }); - user2Messenger.listen((msg) => { + await user1Messenger.initialize(); + await user2Messenger.initialize(); + user2Messenger.receive((msg) => { expect(msg).equals(testmsg) resolve(msg) - },(err) => { - reject(err) }); - await user1Messenger.send(testmsg, this.user2Data.cruxUser.cruxID); + await user1Messenger.send(this.user2Data.cruxUser.cruxID, testmsg); }); }); From 0fbe28be466c79122b3092a6e51d3db90ae95694 Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Tue, 2 Jun 2020 15:37:44 +0530 Subject: [PATCH 10/16] added testcase for CruxServiceClient for InMemory feature --- .../test-crux-service-client.ts | 87 +++++++++++++++++++ src/test/crux-messenger/utils.ts | 2 +- 2 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 src/test/crux-messenger/test-crux-service-client.ts diff --git a/src/test/crux-messenger/test-crux-service-client.ts b/src/test/crux-messenger/test-crux-service-client.ts new file mode 100644 index 00000000..7c605ce7 --- /dev/null +++ b/src/test/crux-messenger/test-crux-service-client.ts @@ -0,0 +1,87 @@ +import * as chai from "chai"; +import sinon from "sinon"; +import chaiAsPromised from "chai-as-promised"; +import 'mocha'; +import * as cwc from "../../application/clients/crux-wallet-client"; +import {SecureCruxNetwork, RemoteKeyClient, RemoteKeyHost, RemoteKeyManager} from "../../core/domain-services"; +import {BasicKeyManager} from "../../infrastructure/implementations"; +import {CruxId, BufferJSONSerializer, InMemStorage} from "../../packages"; +import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies, InMemoryCruxDomainRepository, getSomewalletDomain, addUserToRepo, addDomainToRepo} from "../test-utils"; +import {InMemoryPubSubClientFactory, InMemoryMaliciousPubSubClientFactory} from "./inmemory-implementations"; +import {getMockUserBar123CSTestWallet, getMockUserFoo123CSTestWallet, getCstestwalletCruxDomain} from "./utils"; +import { ECIESEncryption } from "../../packages/encryption"; +import { CruxWalletClient, CruxServiceClient } from "../../application/clients"; + +patchMissingDependencies(); + +chai.use(chaiAsPromised); +chai.should(); +const expect = require('chai').expect; + +describe('Test CruxServiceClient - InMemory', function() { + beforeEach(async function() { + const userStore = new MockUserStore(); + const user1Data = getMockUserFoo123CSTestWallet(); + const user2Data = getMockUserBar123CSTestWallet(); + const testCruxDomain = getCstestwalletCruxDomain(); + this.user1Data = user1Data; + this.user2Data = user2Data; + userStore.store(user1Data.cruxUser); + userStore.store(user2Data.cruxUser); + this.inmemUserRepo = new InMemoryCruxUserRepository(userStore, testCruxDomain); + this.inmemDomainRepo = new InMemoryCruxDomainRepository(); + this.inmemDomainRepo = await addDomainToRepo(testCruxDomain, this.inmemDomainRepo); + this.pubsubClientFactory = new InMemoryPubSubClientFactory(); + this.user1KeyManager = new BasicKeyManager(this.user1Data.pvtKey); + this.user2KeyManager = new BasicKeyManager(this.user2Data.pvtKey); + const toEncrypt = Buffer.from("content", "utf8"); + const encrypted = await ECIESEncryption.encrypt(toEncrypt, this.user2KeyManager.publicKey); + this.testEncryptedData = BufferJSONSerializer.bufferObjectToJSONString(encrypted); + this.stubGetCruxDomainRepository = sinon.stub(cwc, 'getCruxDomainRepository').callsFake(() => this.inmemDomainRepo as any); + this.stubGetCruxUserRepository = sinon.stub(cwc, 'getCruxUserRepository').callsFake(() => this.inmemUserRepo as any); + this.stubGetPubsubClientFactory = sinon.stub(cwc, 'getPubsubClientFactory').callsFake(() => this.pubsubClientFactory as any); + }); + + afterEach(function() { + this.stubGetCruxUserRepository.restore(); + this.stubGetCruxDomainRepository.restore(); + this.stubGetPubsubClientFactory.restore(); + }); + + it('Send Receive - CruxWalletClient<->CruxServiceClient - getAddressMap', async function() { + const cruxWalletClient = new CruxWalletClient({ + privateKey: this.user1Data.pvtKey, + walletClientName: "cstestwallet", + isHost: true, + cacheStorage: new InMemStorage(), + }); + const cruxServiceClient = new CruxServiceClient({ + cruxId: this.user2Data.cruxUser.cruxID, + keyManager: this.user2KeyManager + }, this.inmemUserRepo, this.pubsubClientFactory); + + const remoteWalletClient = await cruxServiceClient.getWalletClientForUser(this.user1Data.cruxUser.cruxID); + const addressMap = await remoteWalletClient.getAddressMap(); + console.log("TESTCASE::AddressMap: ", addressMap); + }); + + it('Send Receive - CruxWalletClient<->CruxServiceClient - putAddressMap', async function() { + const cruxWalletClient = new CruxWalletClient({ + privateKey: this.user1Data.pvtKey, + walletClientName: "cstestwallet", + isHost: true, + cacheStorage: new InMemStorage(), + }); + const cruxServiceClient = new CruxServiceClient({ + cruxId: this.user2Data.cruxUser.cruxID, + keyManager: this.user2KeyManager + }, this.inmemUserRepo, this.pubsubClientFactory); + const remoteWalletClient = await cruxServiceClient.getWalletClientForUser(this.user1Data.cruxUser.cruxID); + const addressMapResult = await remoteWalletClient.putAddressMap({ + "bitcoin": { + addressHash: "d78c26f8-7c13-4909-bf62-57d7623f8ee8" + } + }); + console.log("TESTCASE::Address Map: ", addressMapResult); + }); +}) \ No newline at end of file diff --git a/src/test/crux-messenger/utils.ts b/src/test/crux-messenger/utils.ts index 1adb0cc5..545bab1b 100644 --- a/src/test/crux-messenger/utils.ts +++ b/src/test/crux-messenger/utils.ts @@ -9,7 +9,7 @@ import { } from "../../core/entities"; import {CruxDomainId, CruxId, getKeyPairFromPrivKey} from "../../packages"; -const getCstestwalletCruxDomain = () => { +export const getCstestwalletCruxDomain = () => { const testCruxDomainId = CruxDomainId.fromString('cstestwallet.crux'); const domainStatus: DomainRegistrationStatus = DomainRegistrationStatus.REGISTERED; const testValidDomainAssetMapping = { From 7a8a5d09123682aa53dfd02342c9cc9df4735d52 Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Tue, 2 Jun 2020 21:24:18 +0530 Subject: [PATCH 11/16] added key managementProtocol in CruxWalletClient, CruxServiceClient, remoteKeyManager, RemoteKeyHost, RemoteKeyClient --- .../clients/crux-service-client.ts | 14 +++--- src/application/clients/crux-wallet-client.ts | 7 ++- .../domain-services/remote-key-service.ts | 49 +++++++++---------- .../implementations/crux-messenger.ts | 2 +- .../test-crux-service-client.ts | 10 ++-- .../test-key-management-protocol.ts | 8 +-- .../crux-messenger/test-remote-key-client.ts | 18 ++++--- .../test-crux-service-client-prod.ts | 14 ++++-- .../test-remote-key-client-prod.ts | 19 ++++--- 9 files changed, 79 insertions(+), 62 deletions(-) diff --git a/src/application/clients/crux-service-client.ts b/src/application/clients/crux-service-client.ts index 9d950143..814adb1b 100644 --- a/src/application/clients/crux-service-client.ts +++ b/src/application/clients/crux-service-client.ts @@ -1,19 +1,21 @@ -import { RemoteKeyManager, SecureCruxNetwork } from "../../core/domain-services"; +import { CruxProtocolMessenger, RemoteKeyManager} from "../../core/domain-services"; +import { keyManagementProtocol } from "../../infrastructure"; import { CruxId, InMemStorage } from "../../packages/"; import { CruxWalletClient } from "./crux-wallet-client"; export class CruxServiceClient { private selfIdClaim: any; - private secureCruxNetwork: SecureCruxNetwork; + private cruxProtocolMessenger: any; - constructor(selfIdClaim: any, userRepo: any, pubsubClientFactory: any) { + constructor(selfIdClaim: any, secureCruxNetwork: any, protocolSchema?: any) { this.selfIdClaim = selfIdClaim; - this.secureCruxNetwork = new SecureCruxNetwork(userRepo, pubsubClientFactory, selfIdClaim); + this.cruxProtocolMessenger = new CruxProtocolMessenger(secureCruxNetwork, protocolSchema ? protocolSchema : keyManagementProtocol); } public async getWalletClientForUser(remoteUserId: CruxId) { - await this.secureCruxNetwork.initialize(); - const remoteKeyManager = new RemoteKeyManager(this.secureCruxNetwork, remoteUserId); + await this.cruxProtocolMessenger.initialize(); + const remoteKeyManager = new RemoteKeyManager(this.cruxProtocolMessenger, remoteUserId); + await remoteKeyManager.initialize(); return new CruxWalletClient({ cacheStorage: new InMemStorage(), diff --git a/src/application/clients/crux-wallet-client.ts b/src/application/clients/crux-wallet-client.ts index 983425f3..77651403 100644 --- a/src/application/clients/crux-wallet-client.ts +++ b/src/application/clients/crux-wallet-client.ts @@ -26,6 +26,7 @@ import { CruxNetPubSubClientFactory, cruxPaymentProtocol, IBlockstackCruxDomainRepositoryOptions, IBlockstackCruxUserRepositoryOptions, + keyManagementProtocol, } from "../../infrastructure/implementations"; import {CruxDomainId, CruxId, getLogger, InMemStorage, StorageService} from "../../packages"; import {Encryption} from "../../packages/encryption"; @@ -108,6 +109,7 @@ export class CruxWalletClient { public walletClientName: string; // TODO: make private public paymentProtocolMessenger?: CruxProtocolMessenger; + public keyManagerProtocolMessenger?: CruxProtocolMessenger; public secureCruxNetwork?: SecureCruxNetwork; private cruxBlockstackInfrastructure: ICruxBlockstackInfrastructure; private initPromise: Promise; @@ -468,9 +470,10 @@ export class CruxWalletClient { if (options.isHost) { const pubsubClientFactory = getPubsubClientFactory(); this.secureCruxNetwork = new SecureCruxNetwork(this.cruxUserRepository, pubsubClientFactory, selfIdClaim); - await this.secureCruxNetwork.initialize(); this.paymentProtocolMessenger = new CruxProtocolMessenger(this.secureCruxNetwork, cruxPaymentProtocol); - const remoteKeyHost = new RemoteKeyHost(this.secureCruxNetwork, this.keyManager!); + this.keyManagerProtocolMessenger = new CruxProtocolMessenger(this.secureCruxNetwork, keyManagementProtocol); + await this.keyManagerProtocolMessenger.initialize(); + const remoteKeyHost = new RemoteKeyHost(this.keyManagerProtocolMessenger, this.keyManager!); this.remoteKeyHost = remoteKeyHost; await this.remoteKeyHost.initialize(); } diff --git a/src/core/domain-services/remote-key-service.ts b/src/core/domain-services/remote-key-service.ts index e2bb39f6..a94b5537 100644 --- a/src/core/domain-services/remote-key-service.ts +++ b/src/core/domain-services/remote-key-service.ts @@ -2,46 +2,45 @@ import {makeUUID4} from "blockstack/lib"; import { createNanoEvents, DefaultEvents, Emitter } from "nanoevents"; import { CruxId } from "src/packages"; import { IKeyManager } from "../interfaces"; -import { SecureCruxNetwork } from "./crux-messenger"; +import { CruxProtocolMessenger, SecureCruxNetwork } from "./crux-messenger"; const VALID_METHODS = ["signWebToken", "getPubKey", "deriveSharedSecret", "decryptMessage"]; export class RemoteKeyClient { - private secureCruxNetwork: SecureCruxNetwork; + private cruxProtocolMessenger: CruxProtocolMessenger; private remoteUserId: CruxId; private emitter: Emitter; - constructor(secureCruxNetwork: SecureCruxNetwork, remoteUserId: CruxId) { - this.secureCruxNetwork = secureCruxNetwork; + constructor(cruxProtocolMessenger: CruxProtocolMessenger, remoteUserId: CruxId) { + this.cruxProtocolMessenger = cruxProtocolMessenger; this.remoteUserId = remoteUserId; this.emitter = createNanoEvents(); } public async initialize() { - this.secureCruxNetwork.receive(async (msg: any, senderId: CruxId | undefined) => { + this.cruxProtocolMessenger.on("KEY_MANAGER_RESPONSE", async (msg: any, senderId: CruxId | undefined) => { console.log("Inside RemoteKeyClient::initialize::Msg, senderId: ", msg, senderId); this.emitter.emit(msg.invocationId, msg, senderId); }); - this.secureCruxNetwork.onError((err: any) => { - console.log("errorinvocationListener", err); - this.emitter.emit("error", err); - return; - }); } public async invoke(method: string, args: any[]) { console.log("RemoteKeyClient::Inside Invoke"); - if (!this.secureCruxNetwork) { + if (!this.cruxProtocolMessenger) { throw Error("RemoteKeyClient cannot send with no secureCruxNetwork"); } const methodData = this.generateMethodData(method, args); console.log("RemoteKeyClient::Inside Invoke, RemoteUserId, MethodData", this.remoteUserId, methodData); - await this.secureCruxNetwork.send(this.remoteUserId, methodData); + // @ts-ignore + await this.cruxProtocolMessenger.send({ + content: methodData, + type: "KEY_MANAGER_REQUEST", + }, this.remoteUserId); return methodData.invocationId; } public listenToInvocation = (invocationId: string, resultCallback: (msg: any, senderId: CruxId | undefined) => any, errorCallback: (err: any) => any): void => { - if (!this.secureCruxNetwork) { + if (!this.cruxProtocolMessenger) { throw Error("RemoteKeyClient cannot listen with no secureCruxNetwork"); } console.log("RemoteKeyClient::ListenToInvocation::invocationId", invocationId); @@ -59,33 +58,33 @@ export class RemoteKeyClient { } export class RemoteKeyHost { - private secureCruxNetwork: SecureCruxNetwork; + private cruxProtocolMessenger: CruxProtocolMessenger; private keyManager: IKeyManager; - constructor(secureCruxNetwork: SecureCruxNetwork, keyManager: IKeyManager) { + constructor(cruxProtocolMessenger: CruxProtocolMessenger, keyManager: IKeyManager) { this.keyManager = keyManager; - this.secureCruxNetwork = secureCruxNetwork; + this.cruxProtocolMessenger = cruxProtocolMessenger; } public async initialize() { - this.secureCruxNetwork.receive(async (msg: any, senderId: CruxId | undefined) => { + this.cruxProtocolMessenger.on("KEY_MANAGER_REQUEST", async (msg: any, senderId: CruxId | undefined) => { console.log("Inside RemoteKeyHost::in::Msg, senderId: ", msg, senderId); const data = await this.handleMessage(msg); console.log("Inside RemoteKeyHost::initialize::Data(handleMessage): ", data); this.sendInvocationResult(data, senderId!); }); - this.secureCruxNetwork.onError((err: any) => { - console.log("errorinvocationListener", err); - return; - }); } private async sendInvocationResult(result: any, receiverId: CruxId) { - if (!this.secureCruxNetwork) { + if (!this.cruxProtocolMessenger) { throw Error("RemoteKeyClient cannot send with no selfMessenger"); } const resultData = this.generateInvocationResponse(result); console.log("RemoteKeyHost::Inside sendInvocationResult::resultData: ", resultData); - await this.secureCruxNetwork.send(receiverId, resultData); + // @ts-ignore + await this.cruxProtocolMessenger.send({ + content: resultData, + type: "KEY_MANAGER_RESPONSE", + }, receiverId); } private async handleMessage(message: any) { @@ -133,8 +132,8 @@ export class RemoteKeyManager implements IKeyManager { private remoteKeyClient: RemoteKeyClient; private remoteUserId: CruxId; - constructor(secureCruxNetwork: SecureCruxNetwork, remoteUserId: CruxId) { - this.remoteKeyClient = new RemoteKeyClient(secureCruxNetwork, remoteUserId); + constructor(cruxProtocolMessenger: CruxProtocolMessenger, remoteUserId: CruxId) { + this.remoteKeyClient = new RemoteKeyClient(cruxProtocolMessenger, remoteUserId); this.remoteUserId = remoteUserId; } diff --git a/src/infrastructure/implementations/crux-messenger.ts b/src/infrastructure/implementations/crux-messenger.ts index c44ded55..4840fb91 100644 --- a/src/infrastructure/implementations/crux-messenger.ts +++ b/src/infrastructure/implementations/crux-messenger.ts @@ -239,7 +239,7 @@ export const keyManagementProtocol: IMessageSchema[] = [ { messageType: "KEY_MANAGER_RESPONSE", schema: Joi.object({ - data: Joi.any() + result: Joi.any() .required(), invocationId: Joi.string() diff --git a/src/test/crux-messenger/test-crux-service-client.ts b/src/test/crux-messenger/test-crux-service-client.ts index 7c605ce7..0b46c861 100644 --- a/src/test/crux-messenger/test-crux-service-client.ts +++ b/src/test/crux-messenger/test-crux-service-client.ts @@ -4,7 +4,7 @@ import chaiAsPromised from "chai-as-promised"; import 'mocha'; import * as cwc from "../../application/clients/crux-wallet-client"; import {SecureCruxNetwork, RemoteKeyClient, RemoteKeyHost, RemoteKeyManager} from "../../core/domain-services"; -import {BasicKeyManager} from "../../infrastructure/implementations"; +import {BasicKeyManager, keyManagementProtocol} from "../../infrastructure/implementations"; import {CruxId, BufferJSONSerializer, InMemStorage} from "../../packages"; import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies, InMemoryCruxDomainRepository, getSomewalletDomain, addUserToRepo, addDomainToRepo} from "../test-utils"; import {InMemoryPubSubClientFactory, InMemoryMaliciousPubSubClientFactory} from "./inmemory-implementations"; @@ -40,6 +40,10 @@ describe('Test CruxServiceClient - InMemory', function() { this.stubGetCruxDomainRepository = sinon.stub(cwc, 'getCruxDomainRepository').callsFake(() => this.inmemDomainRepo as any); this.stubGetCruxUserRepository = sinon.stub(cwc, 'getCruxUserRepository').callsFake(() => this.inmemUserRepo as any); this.stubGetPubsubClientFactory = sinon.stub(cwc, 'getPubsubClientFactory').callsFake(() => this.pubsubClientFactory as any); + this.secureCruxNetwork2 = new SecureCruxNetwork(this.inmemUserRepo, this.pubsubClientFactory, { + cruxId: this.user2Data.cruxUser.cruxID, + keyManager: new BasicKeyManager(this.user2Data.pvtKey) + }); }); afterEach(function() { @@ -58,7 +62,7 @@ describe('Test CruxServiceClient - InMemory', function() { const cruxServiceClient = new CruxServiceClient({ cruxId: this.user2Data.cruxUser.cruxID, keyManager: this.user2KeyManager - }, this.inmemUserRepo, this.pubsubClientFactory); + }, this.secureCruxNetwork2, keyManagementProtocol); const remoteWalletClient = await cruxServiceClient.getWalletClientForUser(this.user1Data.cruxUser.cruxID); const addressMap = await remoteWalletClient.getAddressMap(); @@ -75,7 +79,7 @@ describe('Test CruxServiceClient - InMemory', function() { const cruxServiceClient = new CruxServiceClient({ cruxId: this.user2Data.cruxUser.cruxID, keyManager: this.user2KeyManager - }, this.inmemUserRepo, this.pubsubClientFactory); + }, this.secureCruxNetwork2, keyManagementProtocol); const remoteWalletClient = await cruxServiceClient.getWalletClientForUser(this.user1Data.cruxUser.cruxID); const addressMapResult = await remoteWalletClient.putAddressMap({ "bitcoin": { diff --git a/src/test/crux-messenger/test-key-management-protocol.ts b/src/test/crux-messenger/test-key-management-protocol.ts index 300729f6..fe70e2e2 100644 --- a/src/test/crux-messenger/test-key-management-protocol.ts +++ b/src/test/crux-messenger/test-key-management-protocol.ts @@ -172,7 +172,7 @@ describe('Test Key Management Protocol', function() { it('Valid Key Manager Response - String output', async function() { return new Promise(async (res, rej) => { const validKeyManagerResponse = { - data: "03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318", + result: "03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318", invocationId: '7c3baa3c-f5e8-490a-88a1-e0a052b7caa4', } const testMessage: IProtocolMessage = { @@ -197,7 +197,7 @@ describe('Test Key Management Protocol', function() { it('Valid Key Manager Response - Object Output', async function() { return new Promise(async (res, rej) => { const validKeyManagerResponse = { - data: [{ + result: [{ 'webtoken': "hello" }], invocationId: '7c3baa3c-f5e8-490a-88a1-e0a052b7caa4' @@ -224,7 +224,7 @@ describe('Test Key Management Protocol', function() { it('Valid Key Manager Response - Array Output', async function() { return new Promise(async (res, rej) => { const validKeyManagerResponse = { - data: ['webtoken'], + result: ['webtoken'], invocationId: '7c3baa3c-f5e8-490a-88a1-e0a052b7caa4' } const testMessage: IProtocolMessage = { @@ -260,7 +260,7 @@ describe('Test Key Management Protocol', function() { }); it('Invalid Key Manager Response - invocationId wrong length', async function() { const validKeyManagerResponse = { - data: ['webtoken'], + result: ['webtoken'], invocationId: '7c3baa3c-f5e8-490a-88a1-e0a02b7caa4' } const testMessage: IProtocolMessage = { diff --git a/src/test/crux-messenger/test-remote-key-client.ts b/src/test/crux-messenger/test-remote-key-client.ts index 0b02e265..fe79f43c 100644 --- a/src/test/crux-messenger/test-remote-key-client.ts +++ b/src/test/crux-messenger/test-remote-key-client.ts @@ -2,8 +2,8 @@ import * as chai from "chai"; import sinon from "sinon"; import chaiAsPromised from "chai-as-promised"; import 'mocha'; -import {SecureCruxNetwork, RemoteKeyClient, RemoteKeyHost, RemoteKeyManager} from "../../core/domain-services"; -import {BasicKeyManager} from "../../infrastructure/implementations"; +import {SecureCruxNetwork, RemoteKeyClient, RemoteKeyHost, RemoteKeyManager, CruxProtocolMessenger} from "../../core/domain-services"; +import {BasicKeyManager, keyManagementProtocol} from "../../infrastructure/implementations"; import {CruxId, BufferJSONSerializer} from "../../packages"; import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies} from "../test-utils"; import {InMemoryPubSubClientFactory, InMemoryMaliciousPubSubClientFactory} from "./inmemory-implementations"; @@ -43,16 +43,18 @@ describe('Test RemoteKeyClient', function() { cruxId: this.user2Data.cruxUser.cruxID, keyManager: this.user2KeyManager }); - this.secureCruxNetwork1.initialize(); - this.secureCruxNetwork2.initialize(); + this.cruxProtocolMessenger1 = new CruxProtocolMessenger(this.secureCruxNetwork1, keyManagementProtocol); + this.cruxProtocolMessenger2 = new CruxProtocolMessenger(this.secureCruxNetwork2, keyManagementProtocol); + await this.cruxProtocolMessenger1.initialize(); + await this.cruxProtocolMessenger2.initialize(); }); it('Basic Key Manager Send Receive', async function() { const testPublicKey = '03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318'; return new Promise(async (resolve, reject) => { - const remoteKeyClient = new RemoteKeyClient(this.secureCruxNetwork1, this.user2Data.cruxUser.cruxID); + const remoteKeyClient = new RemoteKeyClient(this.cruxProtocolMessenger1, this.user2Data.cruxUser.cruxID); await remoteKeyClient.initialize(); - const remoteKeyHost = new RemoteKeyHost(this.secureCruxNetwork2, this.user2KeyManager); + const remoteKeyHost = new RemoteKeyHost(this.cruxProtocolMessenger2, this.user2KeyManager); await remoteKeyHost.initialize() const invocationId = await remoteKeyClient.invoke("getPubKey", []); remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { @@ -67,8 +69,8 @@ describe('Test RemoteKeyClient', function() { it('Basic Key Manager Send Receive - RemoteKeyManager', async function() { const testPubKey = "03e6bbc79879d37473836771441a79d3d9dddfabacdac22ed315e5636ff819a318"; return new Promise(async (resolve, reject) => { - const remoteKeyManager = new RemoteKeyManager(this.secureCruxNetwork1, this.user2Data.cruxUser.cruxID); - const remoteKeyHost = new RemoteKeyHost(this.secureCruxNetwork2, this.user2KeyManager); + const remoteKeyManager = new RemoteKeyManager(this.cruxProtocolMessenger1, this.user2Data.cruxUser.cruxID); + const remoteKeyHost = new RemoteKeyHost(this.cruxProtocolMessenger2, this.user2KeyManager); await remoteKeyManager.initialize(); await remoteKeyHost.initialize(); const signedWebToken = await remoteKeyManager.signWebToken("1234567") diff --git a/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts b/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts index 91b373a3..3a00c7e8 100644 --- a/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts +++ b/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts @@ -5,7 +5,7 @@ import chaiAsPromised from "chai-as-promised"; import 'mocha'; import {SecureCruxNetwork} from "../../../core/domain-services"; import {CruxServiceClient, getCruxUserRepository, CruxWalletClient} from "../../../application/clients" -import {BasicKeyManager, CruxNetPubSubClientFactory} from "../../../infrastructure/implementations"; +import {BasicKeyManager, CruxNetPubSubClientFactory, keyManagementProtocol} from "../../../infrastructure/implementations"; import {patchMissingDependencies, getCruxdevCruxDomain} from "../../test-utils"; import { CruxSpec, IAddress } from "../../../core/entities"; import { CruxId, InMemStorage } from "../../../packages"; @@ -43,6 +43,10 @@ describe('Test CruxServiceClient - Prod', function() { path: "/mqtt" } }); + this.secureCruxNetwork2 = new SecureCruxNetwork(this.userRepo, this.pubsubClientFactory, { + cruxId: this.user2Data.cruxID, + keyManager: new BasicKeyManager(user2PvtKey) + }); }); it('Send Receive - CruxWalletClient<->CruxServiceClient - getAddressMap', async function() { const cruxWalletClient = new CruxWalletClient({ @@ -54,11 +58,11 @@ describe('Test CruxServiceClient - Prod', function() { const cruxServiceClient = new CruxServiceClient({ cruxId: CruxId.fromString(this.user2CruxId), keyManager: this.user2KeyManager - }, this.userRepo, this.pubsubClientFactory); + }, this.secureCruxNetwork2, keyManagementProtocol); const remoteWalletClient = await cruxServiceClient.getWalletClientForUser(this.user1Data.cruxID); const addressMap = await remoteWalletClient.getAddressMap(); - console.log("TESTCASE::AddressMap: ", addressMap); + console.log("TESTCASE::Get Address Map: ", addressMap); }); it('Send Receive - CruxWalletClient<->CruxServiceClient - putAddressMap', async function() { @@ -71,13 +75,13 @@ describe('Test CruxServiceClient - Prod', function() { const cruxServiceClient = new CruxServiceClient({ cruxId: CruxId.fromString(this.user2CruxId), keyManager: this.user2KeyManager - }, this.userRepo, this.pubsubClientFactory); + }, this.secureCruxNetwork2, keyManagementProtocol); const remoteWalletClient = await cruxServiceClient.getWalletClientForUser(this.user1Data.cruxID); const addressMapResult = await remoteWalletClient.putAddressMap({ "ltc": { addressHash: "1HX4KvtPdg9QUYwQE1kNqTAjmNaDG12346" } }); - console.log("TESTCASE::Address Map: ", addressMapResult); + console.log("TESTCASE::Put Address Map: ", addressMapResult); }); }); \ No newline at end of file diff --git a/src/test/integration-tests/crux-messenger/test-remote-key-client-prod.ts b/src/test/integration-tests/crux-messenger/test-remote-key-client-prod.ts index 4984f9a8..b548b93a 100644 --- a/src/test/integration-tests/crux-messenger/test-remote-key-client-prod.ts +++ b/src/test/integration-tests/crux-messenger/test-remote-key-client-prod.ts @@ -3,8 +3,8 @@ import sinon from "sinon"; import chaiAsPromised from "chai-as-promised"; import 'mocha'; import * as blockstack from "blockstack"; -import {RemoteKeyClient, RemoteKeyHost, RemoteKeyManager, SecureCruxNetwork} from "../../../core/domain-services"; -import {BasicKeyManager, CruxNetPubSubClientFactory} from "../../../infrastructure/implementations"; +import {RemoteKeyClient, RemoteKeyHost, RemoteKeyManager, SecureCruxNetwork, CruxProtocolMessenger} from "../../../core/domain-services"; +import {BasicKeyManager, CruxNetPubSubClientFactory, keyManagementProtocol} from "../../../infrastructure/implementations"; import {CruxId, InMemStorage, BufferJSONSerializer} from "../../../packages"; import {InMemoryCruxUserRepository, MockUserStore, patchMissingDependencies, getCruxdevCruxDomain} from "../../test-utils"; import { bip32 } from "bitcoinjs-lib"; @@ -54,19 +54,22 @@ describe('Test RemoteKeyClient - PROD', function() { cruxId: this.user2Data.cruxID, keyManager: this.user2KeyManager }); - await this.secureCruxNetwork1.initialize(); - await this.secureCruxNetwork2.initialize(); + this.cruxProtocolMessenger1 = new CruxProtocolMessenger(this.secureCruxNetwork1, keyManagementProtocol); + this.cruxProtocolMessenger2 = new CruxProtocolMessenger(this.secureCruxNetwork2, keyManagementProtocol); + await this.cruxProtocolMessenger1.initialize(); + await this.cruxProtocolMessenger2.initialize(); }); it('Send Receive RemoteKeyClient<->RemoteKeyHost - Prod', async function() { const testPublicKey = '0239d9d97d5b8973fba462b1a014bcbb84d056061234fd375442a7ef0620ea88c3'; return new Promise(async (resolve, reject) => { - const remoteKeyClient = new RemoteKeyClient(this.secureCruxNetwork1, this.user2Data.cruxID); + const remoteKeyClient = new RemoteKeyClient(this.cruxProtocolMessenger1, this.user2Data.cruxID); await remoteKeyClient.initialize(); - const remoteKeyHost = new RemoteKeyHost(this.secureCruxNetwork2, this.user2KeyManager); + const remoteKeyHost = new RemoteKeyHost(this.cruxProtocolMessenger2, this.user2KeyManager); await remoteKeyHost.initialize() const invocationId = await remoteKeyClient.invoke("getPubKey", []); remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { + console.log("TESTCASE::msg.result.data", msg.result.data); expect(msg.result.data).equals(testPublicKey); resolve(msg) },(err) => { @@ -78,9 +81,9 @@ describe('Test RemoteKeyClient - PROD', function() { it('Send Receive RemoteKeyManager<->RemoteKeyHost - RemoteKeyManager - Prod', async function() { const testPubKey = "0362f171a40ab5e6ad22275ec166f15a232b83a571bab9c30622ed2963f1da4c08"; return new Promise(async (resolve, reject) => { - const remoteKeyManager = new RemoteKeyManager(this.secureCruxNetwork2, this.user1Data.cruxID); + const remoteKeyManager = new RemoteKeyManager(this.cruxProtocolMessenger2, this.user1Data.cruxID); await remoteKeyManager.initialize(); - const remoteKeyHost = new RemoteKeyHost(this.secureCruxNetwork1, this.user1KeyManager); + const remoteKeyHost = new RemoteKeyHost(this.cruxProtocolMessenger1, this.user1KeyManager); await remoteKeyHost.initialize(); const signedWebToken = await remoteKeyManager.signWebToken("1234567") console.log("TESTCASE::signWebToken:", signedWebToken); From 838d4bb1d2546fd80c118e6eb937e46336046cf2 Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Wed, 3 Jun 2020 13:28:27 +0530 Subject: [PATCH 12/16] updated CruxWalletClient setupmessenger functionality --- src/application/clients/crux-wallet-client.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/application/clients/crux-wallet-client.ts b/src/application/clients/crux-wallet-client.ts index 77651403..be4bd78e 100644 --- a/src/application/clients/crux-wallet-client.ts +++ b/src/application/clients/crux-wallet-client.ts @@ -467,10 +467,10 @@ export class CruxWalletClient { if (!selfIdClaim) { throw Error("Self ID Claim is required to setup messenger"); } + const pubsubClientFactory = getPubsubClientFactory(); + this.secureCruxNetwork = new SecureCruxNetwork(this.cruxUserRepository, pubsubClientFactory, selfIdClaim); + this.paymentProtocolMessenger = new CruxProtocolMessenger(this.secureCruxNetwork, cruxPaymentProtocol); if (options.isHost) { - const pubsubClientFactory = getPubsubClientFactory(); - this.secureCruxNetwork = new SecureCruxNetwork(this.cruxUserRepository, pubsubClientFactory, selfIdClaim); - this.paymentProtocolMessenger = new CruxProtocolMessenger(this.secureCruxNetwork, cruxPaymentProtocol); this.keyManagerProtocolMessenger = new CruxProtocolMessenger(this.secureCruxNetwork, keyManagementProtocol); await this.keyManagerProtocolMessenger.initialize(); const remoteKeyHost = new RemoteKeyHost(this.keyManagerProtocolMessenger, this.keyManager!); From 8155a26ceb25ac2fa7b812d002e3122d09483b95 Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Thu, 4 Jun 2020 11:55:25 +0530 Subject: [PATCH 13/16] added demo for remote-crux-settings --- package.json | 3 +- .../clients/crux-service-client.ts | 1 + src/application/clients/crux-wallet-client.ts | 27 ++- src/core/index.ts | 1 + src/samples/remote-crux-settings.html | 61 ++++++ src/samples/remote-crux-settings.ts | 178 ++++++++++++++++++ 6 files changed, 261 insertions(+), 10 deletions(-) create mode 100644 src/samples/remote-crux-settings.html create mode 100644 src/samples/remote-crux-settings.ts diff --git a/package.json b/package.json index 176216c4..cba1726f 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,8 @@ "version-docs": "./node_modules/.bin/typedoc --out docs/$npm_package_version src/index.ts", "coverage": "./node_modules/.bin/nyc npm run test", "wallet_demo_legacy": "./node_modules/.bin/parcel src/samples/wallet_demo_legacy.html --https --no-cache", - "wallet_demo": "./node_modules/.bin/parcel src/samples/wallet_demo.html --no-cache", + "wallet_demo": "./node_modules/.bin/parcel src/samples/wallet_demo.html --no-cache &", + "remote-crux-settings": "npm run wallet_demo && ./node_modules/.bin/parcel src/samples/remote-crux-settings.html --no-cache", "onboarding_demo": "./node_modules/.bin/parcel src/samples/onboarding_demo.html --https --no-cache", "typecheck": "./node_modules/.bin/tsc --noEmit", "validate_lockfile": "./node_modules/.bin/lockfile-lint --type npm --path package-lock.json --allowed-hosts npm github.com --allowed-schemes \"https:\" \"git+https:\"", diff --git a/src/application/clients/crux-service-client.ts b/src/application/clients/crux-service-client.ts index 814adb1b..486fd6bf 100644 --- a/src/application/clients/crux-service-client.ts +++ b/src/application/clients/crux-service-client.ts @@ -19,6 +19,7 @@ export class CruxServiceClient { await remoteKeyManager.initialize(); return new CruxWalletClient({ cacheStorage: new InMemStorage(), + disableCruxMessenger: true, // @ts-ignore privateKey: remoteKeyManager, walletClientName: remoteUserId.components.domain, diff --git a/src/application/clients/crux-wallet-client.ts b/src/application/clients/crux-wallet-client.ts index be4bd78e..fdd082a0 100644 --- a/src/application/clients/crux-wallet-client.ts +++ b/src/application/clients/crux-wallet-client.ts @@ -80,7 +80,7 @@ export interface ICruxWalletClientOptions { cacheStorage?: StorageService; walletClientName: string; debugLogging?: boolean; - isHost?: boolean; + disableCruxMessenger?: boolean; } export interface ICruxIDState { @@ -259,6 +259,7 @@ export class CruxWalletClient { @throwCruxClientError public putAddressMap = async (newAddressMap: IAddressMapping): Promise<{success: IPutAddressMapSuccess, failures: IPutAddressMapFailures}> => { + console.log("+++==", newAddressMap); await this.initPromise; const cruxUser = await this.getCruxUserByKey(); if (!cruxUser) { @@ -441,9 +442,16 @@ export class CruxWalletClient { throw ErrorHelper.getPackageError(null, PackageErrorCode.CouldNotFindBlockstackConfigurationServiceClientConfig); } this.cruxAssetTranslator = new CruxAssetTranslator(this.cruxDomain.config.assetMapping, this.cruxDomain.config.assetList); + if (options.disableCruxMessenger) { + return; + } const selfIdClaim = await this.getSelfClaim(); if (selfIdClaim) { - await this.setupCruxMessenger(selfIdClaim, options); + try { + await this.setupCruxMessenger(selfIdClaim, options); + } catch (err) { + console.log(err); + } } } @@ -467,16 +475,17 @@ export class CruxWalletClient { if (!selfIdClaim) { throw Error("Self ID Claim is required to setup messenger"); } + if (options && options.disableCruxMessenger) { + throw Error("Secure Crux Network hasn't been initiated for Wallet"); + } const pubsubClientFactory = getPubsubClientFactory(); this.secureCruxNetwork = new SecureCruxNetwork(this.cruxUserRepository, pubsubClientFactory, selfIdClaim); this.paymentProtocolMessenger = new CruxProtocolMessenger(this.secureCruxNetwork, cruxPaymentProtocol); - if (options.isHost) { - this.keyManagerProtocolMessenger = new CruxProtocolMessenger(this.secureCruxNetwork, keyManagementProtocol); - await this.keyManagerProtocolMessenger.initialize(); - const remoteKeyHost = new RemoteKeyHost(this.keyManagerProtocolMessenger, this.keyManager!); - this.remoteKeyHost = remoteKeyHost; - await this.remoteKeyHost.initialize(); - } + this.keyManagerProtocolMessenger = new CruxProtocolMessenger(this.secureCruxNetwork, keyManagementProtocol); + await this.keyManagerProtocolMessenger.initialize(); + const remoteKeyHost = new RemoteKeyHost(this.keyManagerProtocolMessenger, this.keyManager!); + this.remoteKeyHost = remoteKeyHost; + await this.remoteKeyHost.initialize(); } } diff --git a/src/core/index.ts b/src/core/index.ts index b2dd8083..8fa0d752 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -1,2 +1,3 @@ export * from "./entities"; export * from "./interfaces"; +export * from "./domain-services"; diff --git a/src/samples/remote-crux-settings.html b/src/samples/remote-crux-settings.html new file mode 100644 index 00000000..cae49ad6 --- /dev/null +++ b/src/samples/remote-crux-settings.html @@ -0,0 +1,61 @@ + + + + + + + Remote Crux Settings + + + + +

Demo CruxServiceClient

+ +
CruxPay Interface
+ +
+
Fetch RemoteWalletClient:
+ Remote User Id:
+ +

+    
+ +
+
Fetch address map:
+ +

+    
+ +
+
Publish address map:
+

+ +

+    
+ + ======================== + + + + diff --git a/src/samples/remote-crux-settings.ts b/src/samples/remote-crux-settings.ts new file mode 100644 index 00000000..1c466fd9 --- /dev/null +++ b/src/samples/remote-crux-settings.ts @@ -0,0 +1,178 @@ +import { + CruxWalletClient, + CruxServiceClient, + IAddressMapping, + CruxClientError, + CruxId, + keyManagementProtocol, + InMemStorage +} from "../index"; +import { SecureCruxNetwork, CruxSpec } from "../core"; +import { getCruxUserRepository, getPubsubClientFactory } from "../application"; +import { getCruxdevCruxDomain } from "../test/test-utils"; +import { BasicKeyManager } from "../infrastructure"; +// TODO: add optional import statement to use the build + +const doc = (document as { + getElementById: Function, + getElementsByName: Function, + getElementsByClassName: Function +}) + + + +// Demo wallet artifacts + +let walletClientName = "local" +const btcAddress = "1HX4KvtPdg9QUYwQE1kNqTAjmNaDG7w82V" +const ethAddress = "0x0a2311594059b468c9897338b027c8782398b481" +const trxAddress = "TG3iFaVvUs34SGpWq8RG9gnagDLTe1jdyz" +const xrpAddress = "rpfKAA2Ezqoq5wWo3XENdLYdZ8YGziz48h" +const xrpSecIdentifier = "12345" +const lifeAddress = "0xd26114cd6ee289accf82350c8d8487fedb8a0c07" +const zrxAddress = "0xd26114cd6ee289accf82350c8d8487fedb8a0c07" + +const sampleAddressMaps: {[walletClientName: string]: IAddressMapping} = { + "local,guarda": { + btc: { + addressHash: btcAddress + }, + eth: { + addressHash: ethAddress + }, + trx: { + addressHash: trxAddress + }, + xrp: { + addressHash: xrpAddress, + secIdentifier: xrpSecIdentifier + }, + life: { + addressHash: lifeAddress, + }, + }, + "zel_dev": { + bitcoin: { + addressHash: btcAddress + }, + ethereum: { + addressHash: ethAddress + }, + tron: { + addressHash: trxAddress + }, + ripple: { + addressHash: xrpAddress, + secIdentifier: xrpSecIdentifier + }, + zrx: { + addressHash: zrxAddress, + } + } +}; + +const sampleAddressMap = sampleAddressMaps[Object.keys(sampleAddressMaps).find((keyString) => keyString.split(',').includes(walletClientName))]; +console.log(sampleAddressMap, sampleAddressMaps); +doc.getElementById('publishAddresses').innerHTML = Object.keys(sampleAddressMap).map((currency) => { let address = sampleAddressMap[currency].addressHash; let secIdentifier = sampleAddressMap[currency].secIdentifier; return `${currency.toUpperCase()}` }).join('\n') + + +// --- @crux/js-sdk integration --- // +const userCruxId = CruxId.fromString("release020@cruxdev.crux"); +const userPvtKey = "KyBuSe1MMV6NjJgZfyWuvgmxUeAYswLC2HrfYLUri9aP3AS5FBfr"; +const userBasicKeyManager = new BasicKeyManager(userPvtKey); + +const selfIdClaim = { + cruxId: userCruxId, + keyManager: userBasicKeyManager +} + +const secureCruxNetwork = new SecureCruxNetwork(getCruxUserRepository({ + blockstackInfrastructure: CruxSpec.blockstack.infrastructure, + cruxDomain: getCruxdevCruxDomain(), + cacheStorage: new InMemStorage(), +}), getPubsubClientFactory(), selfIdClaim); + +const cruxServiceClient = new CruxServiceClient({ + cruxId: userCruxId, + keyManager: userBasicKeyManager +}, secureCruxNetwork, keyManagementProtocol); + +let remoteWalletClient: CruxWalletClient; + +const getRemoteWalletClient = async () => { + let UIResponse: string = "Fetching RemoteWalletClient..." + doc.getElementById('getRemoteWalletClientAcknowledgement').textContent = UIResponse; + let remoteUserId = CruxId.fromString(doc.getElementById('remoteUserId').value); + try{ + remoteWalletClient = await cruxServiceClient.getWalletClientForUser(remoteUserId); + UIResponse = `RemoteWalletClient has been initialized for: ${remoteUserId}` + } catch (e) { + console.log(e); + if (e instanceof CruxClientError) { + UIResponse = `${e.errorCode}: ${e}` + } else { + UIResponse = e + } + } finally { + doc.getElementById('getRemoteWalletClientAcknowledgement').textContent = UIResponse + } +} + +const getAddressMap = async () => { + let UIResponse: string = "fetching addressMap remotely..." + doc.getElementById('getAddressMapAcknowledgement').textContent = UIResponse; + try { + let addressMap = await remoteWalletClient.getAddressMap() + UIResponse = JSON.stringify(addressMap, undefined, 4) + } catch (e) { + if (e instanceof CruxClientError) { + UIResponse = `${e.errorCode}: ${e}` + } else { + UIResponse = e + } + } finally { + doc.getElementById('getAddressMapAcknowledgement').textContent = UIResponse + } +} + +const putAddressMap = async () => { + let UIResponse: string = "Publishing your selected addresses remotely..." + let addressMap: IAddressMapping = {}; + // @ts-ignore + [].forEach.call(doc.getElementsByName('publishAddressOption'), (el: HTMLInputElement) => { + if (el.checked) { + addressMap[el.attributes['currency'].nodeValue] = { + addressHash: el.attributes['addressHash'].nodeValue, + secIdentifier: el.attributes['secIdentifier'].nodeValue === "undefined" ? undefined : el.attributes['secIdentifier'].nodeValue + } + } + }); + doc.getElementById('putAddressMapAcknowledgement').textContent = UIResponse + try { + let {success, failures} = await remoteWalletClient.putAddressMap(addressMap) + UIResponse = `successfully published: ${JSON.stringify(success)}, \nFailed publishing: ${JSON.stringify(failures, undefined, 4)}` + } catch (e) { + if (e instanceof CruxClientError) { + UIResponse = `${e.errorCode}: ${e}` + } else { + UIResponse = e + } + } finally { + doc.getElementById('putAddressMapAcknowledgement').textContent = UIResponse + } +} + +// Declaring global variables to be accessible for (button clicks or debugging purposes) +declare global { + interface Window { + remoteWalletClient: CruxWalletClient; + getRemoteWalletClient: Function; + getAddressMap: Function; + putAddressMap: Function; + } +} + +window.remoteWalletClient = remoteWalletClient; +window.getRemoteWalletClient = getRemoteWalletClient; +window.getAddressMap = getAddressMap; +window.putAddressMap = putAddressMap; From 65fea2060c80acf844575f9098b210e80ba672a2 Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Thu, 4 Jun 2020 17:09:07 +0530 Subject: [PATCH 14/16] fixed PR comments --- package.json | 2 +- .../clients/crux-service-client.ts | 4 +- src/application/clients/crux-wallet-client.ts | 12 +-- src/core/domain-services/crux-messenger.ts | 3 - .../domain-services/remote-key-service.ts | 80 +++++-------------- .../blockstack-crux-user-repository.ts | 2 +- .../implementations/crux-messenger.ts | 9 ++- .../test-crux-service-client-prod.ts | 2 - 8 files changed, 29 insertions(+), 85 deletions(-) diff --git a/package.json b/package.json index cba1726f..6f310b29 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "main": "lib/index.js", "types": "lib/index.d.ts", "scripts": { - "test": "TS_NODE_PROJECT='./src/test/tsconfig.commonjs.json' TS_NODE_TRANSPILE_ONLY=true ./node_modules/.bin/mocha --exit --require ts-node/register --require mock-local-storage --require jsdom-global/register --allow-uncaught --colors --reporter mocha-reporter --timeout 50000 src/test/*.ts src/test/crux-messenger/*.ts", + "test": "TS_NODE_PROJECT='./src/test/tsconfig.commonjs.json' TS_NODE_TRANSPILE_ONLY=true ./node_modules/.bin/mocha --exit --require ts-node/register --require mock-local-storage --require jsdom-global/register --allow-uncaught --colors --reporter mocha-reporter --timeout 5000 src/test/*.ts src/test/crux-messenger/*.ts", "start-bridge-server": "node dist/crux-gateway-bridge-without-auth.js &", "stop-bridge-server": "pkill -- signal SIGINT crux-gateway-bridge-server-without-auth", "integration-test": "TS_NODE_PROJECT='./src/test/tsconfig.commonjs.json' TS_NODE_TRANSPILE_ONLY=true ./node_modules/.bin/mocha --exit --require ts-node/register --require mock-local-storage --require jsdom-global/register --allow-uncaught --colors --reporter mocha-reporter --timeout 80000 src/test/integration-tests/crux-messenger/*.ts", diff --git a/src/application/clients/crux-service-client.ts b/src/application/clients/crux-service-client.ts index 486fd6bf..e35b2b6e 100644 --- a/src/application/clients/crux-service-client.ts +++ b/src/application/clients/crux-service-client.ts @@ -7,9 +7,9 @@ export class CruxServiceClient { private selfIdClaim: any; private cruxProtocolMessenger: any; - constructor(selfIdClaim: any, secureCruxNetwork: any, protocolSchema?: any) { + constructor(selfIdClaim: any, secureCruxNetwork: any, protocolSchema: any) { this.selfIdClaim = selfIdClaim; - this.cruxProtocolMessenger = new CruxProtocolMessenger(secureCruxNetwork, protocolSchema ? protocolSchema : keyManagementProtocol); + this.cruxProtocolMessenger = new CruxProtocolMessenger(secureCruxNetwork, protocolSchema); } public async getWalletClientForUser(remoteUserId: CruxId) { diff --git a/src/application/clients/crux-wallet-client.ts b/src/application/clients/crux-wallet-client.ts index fdd082a0..52b1d119 100644 --- a/src/application/clients/crux-wallet-client.ts +++ b/src/application/clients/crux-wallet-client.ts @@ -206,14 +206,10 @@ export class CruxWalletClient { @throwCruxClientError public getAddressMap = async (): Promise => { - console.log("CruxWalletClient::getAddressMap::keyManager: ", this.getKeyManager()); await this.initPromise; - console.log("CruxWalletClient::getAddressMap::publickKey: ", await this.getKeyManager().getPubKey()); const cruxUser = await this.cruxUserRepository.getWithKey(this.getKeyManager()); - console.log("CruxWalletClient::getAddressMap::cruxUser: ", cruxUser); if (cruxUser) { const assetIdAddressMap = cruxUser.getAddressMap(); - console.log("CruxWalletClient::getAddressMap::assetIdAddressMap"); return this.cruxAssetTranslator.assetIdAddressMapToSymbolAddressMap(assetIdAddressMap); } return {}; @@ -259,7 +255,6 @@ export class CruxWalletClient { @throwCruxClientError public putAddressMap = async (newAddressMap: IAddressMapping): Promise<{success: IPutAddressMapSuccess, failures: IPutAddressMapFailures}> => { - console.log("+++==", newAddressMap); await this.initPromise; const cruxUser = await this.getCruxUserByKey(); if (!cruxUser) { @@ -448,7 +443,7 @@ export class CruxWalletClient { const selfIdClaim = await this.getSelfClaim(); if (selfIdClaim) { try { - await this.setupCruxMessenger(selfIdClaim, options); + await this.setupCruxMessenger(selfIdClaim); } catch (err) { console.log(err); } @@ -471,13 +466,10 @@ export class CruxWalletClient { } return selfClaim; } - private setupCruxMessenger = async (selfIdClaim: ICruxIdClaim | undefined, options: ICruxWalletClientOptions) => { + private setupCruxMessenger = async (selfIdClaim: ICruxIdClaim | undefined) => { if (!selfIdClaim) { throw Error("Self ID Claim is required to setup messenger"); } - if (options && options.disableCruxMessenger) { - throw Error("Secure Crux Network hasn't been initiated for Wallet"); - } const pubsubClientFactory = getPubsubClientFactory(); this.secureCruxNetwork = new SecureCruxNetwork(this.cruxUserRepository, pubsubClientFactory, selfIdClaim); this.paymentProtocolMessenger = new CruxProtocolMessenger(this.secureCruxNetwork, cruxPaymentProtocol); diff --git a/src/core/domain-services/crux-messenger.ts b/src/core/domain-services/crux-messenger.ts index 4371e1cd..794be387 100644 --- a/src/core/domain-services/crux-messenger.ts +++ b/src/core/domain-services/crux-messenger.ts @@ -252,9 +252,6 @@ export class SecureContext { data, }; const serializedSecurePacket = JSON.stringify(securePacket); - if (typeof recipientId === "string") { - recipientId = CruxId.fromString(recipientId); - } const recipientCruxUser: CruxUser | undefined = await this.cruxUserRepo.getByCruxId(recipientId); if (!recipientCruxUser) { throw Error("No Such CRUX User Found"); diff --git a/src/core/domain-services/remote-key-service.ts b/src/core/domain-services/remote-key-service.ts index a94b5537..9bbea04d 100644 --- a/src/core/domain-services/remote-key-service.ts +++ b/src/core/domain-services/remote-key-service.ts @@ -1,6 +1,6 @@ import {makeUUID4} from "blockstack/lib"; import { createNanoEvents, DefaultEvents, Emitter } from "nanoevents"; -import { CruxId } from "src/packages"; +import { CruxId } from "../../packages"; import { IKeyManager } from "../interfaces"; import { CruxProtocolMessenger, SecureCruxNetwork } from "./crux-messenger"; @@ -71,7 +71,7 @@ export class RemoteKeyHost { console.log("Inside RemoteKeyHost::in::Msg, senderId: ", msg, senderId); const data = await this.handleMessage(msg); console.log("Inside RemoteKeyHost::initialize::Data(handleMessage): ", data); - this.sendInvocationResult(data, senderId!); + await this.sendInvocationResult(data, CruxId.fromString(senderId!)); }); } private async sendInvocationResult(result: any, receiverId: CruxId) { @@ -80,7 +80,6 @@ export class RemoteKeyHost { } const resultData = this.generateInvocationResponse(result); console.log("RemoteKeyHost::Inside sendInvocationResult::resultData: ", resultData); - // @ts-ignore await this.cruxProtocolMessenger.send({ content: resultData, type: "KEY_MANAGER_RESPONSE", @@ -88,32 +87,12 @@ export class RemoteKeyHost { } private async handleMessage(message: any) { - if (!VALID_METHODS.includes(message.method)) { - throw new Error("Invalid key manager method"); - } if (!this.keyManager) { throw new Error("Key Manager not available"); } let data; - if (message.method === "signWebToken") { - console.log("HandleMessage entrance:signWebToken"); - data = await this.keyManager.signWebToken(message.args[0]); - console.log("HandleMessage exit:signWebToken", data); - } else if (message.method === "getPubKey") { - console.log("HandleMessage entrance:getPubKey"); - data = await this.keyManager.getPubKey(); - console.log("HandleMessage exit:getPubKey", data); - } else if (message.method === "deriveSharedSecret") { - console.log("HandleMessage entrance:deriveSharedSecret"); - // @ts-ignore - data = await this.keyManager.deriveSharedSecret(message.args[0]); - console.log("HandleMessage exit:deriveSharedSecret", data); - } else if (message.method === "decryptMessage") { - console.log("HandleMessage entrance:decryptMessage"); - // @ts-ignore - data = await this.keyManager.decryptMessage(message.args[0]); - console.log("HandleMessage exit:decryptMessage", data); - } + // @ts-ignore + data = await this.keyManager[message.method](message.args[0]); return { data, invocationId: message.invocationId, @@ -141,52 +120,29 @@ export class RemoteKeyManager implements IKeyManager { await this.remoteKeyClient.initialize(); } // @ts-ignore - public signWebToken = async (token: any) => { - return new Promise(async (resolve, reject) => { - const invocationId = await this.remoteKeyClient.invoke("signWebToken", [token]); - console.log("RemoteKeyManager::signWebToken::invokationId: ", invocationId); - this.remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { - console.log("RemoteKeyManager::signWebToken::msg: ", msg); - resolve(msg.result.data); - }, (err) => { - reject(err); - }); - }); + public signWebToken = async (args: any) => { + return this.makeRemoteMessageCall("signWebToken", [args]); } // @ts-ignore public getPubKey = async () => { - return new Promise(async (resolve, reject) => { - const invocationId = await this.remoteKeyClient.invoke("getPubKey", []); - console.log("RemoteKeyManager::getPubKey::invokationId: ", invocationId); - this.remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { - console.log("RemoteKeyManager::getPubKey::msg: ", msg); - resolve(msg.result.data); - }, (err) => { - reject(err); - }); - }); + return this.makeRemoteMessageCall("getPubKey"); } // @ts-ignore - public deriveSharedSecret = async (publicKey: string) => { - const invocationId = await this.remoteKeyClient.invoke("deriveSharedSecret", [publicKey]); - console.log("RemoteKeyManager::deriveSharedSecret::invokationId: ", invocationId); - return new Promise(async (resolve, reject) => { - this.remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { - console.log("RemoteKeyManager::deriveSharedSecret::msg: ", msg); - resolve(msg.result.data); - }, (err) => { - reject(err); - }); - }); + public deriveSharedSecret = async (args: string) => { + return this.makeRemoteMessageCall("deriveSharedSecret", [args]); } // @ts-ignore - public decryptMessage = async (encryptedMessage: string) => { - console.log("RemoteKeyManager::decryptMessage::entry: encryptedMessage: ", encryptedMessage); - const invocationId = await this.remoteKeyClient.invoke("decryptMessage", [encryptedMessage]); - console.log("RemoteKeyManager::decryptMessage::invokationId: ", invocationId); + public decryptMessage = async (args: string) => { + return this.makeRemoteMessageCall("decryptMessage", [args]); + } + + private makeRemoteMessageCall = async (method: string, args: any = []) => { + console.log("makeRemoteMessageCall::", method, args); + const invocationId = await this.remoteKeyClient.invoke(method, args); + console.log("RemoteKeyManager::makeRemoteMessageCall::invokationId: ", invocationId); return new Promise(async (resolve, reject) => { this.remoteKeyClient.listenToInvocation(invocationId, (msg, senderId) => { - console.log("RemoteKeyManager::decryptMessage::msg: ", msg); + console.log("RemoteKeyManager::deriveSharedSecret::msg: ", msg); resolve(msg.result.data); }, (err) => { reject(err); diff --git a/src/infrastructure/implementations/blockstack-crux-user-repository.ts b/src/infrastructure/implementations/blockstack-crux-user-repository.ts index 36a4239e..8bea59e0 100644 --- a/src/infrastructure/implementations/blockstack-crux-user-repository.ts +++ b/src/infrastructure/implementations/blockstack-crux-user-repository.ts @@ -98,7 +98,7 @@ export class BlockstackCruxUserRepository implements ICruxUserRepository { } return new CruxUser(cruxID.components.subdomain, await this.getUserCruxDomain(cruxID) as CruxDomain, addressMap, cruxUserInformation, cruxUserData, cruxpayPubKey); } - public getWithKey = async (keyManager: IKeyManager): Promise => { + public getWithKey = async (keyManager: IKeyManager): Promise => { const cruxID = await this.blockstackService.getCruxIdWithKeyManager(keyManager, this.getCruxDomain().id); if (!cruxID) { return; diff --git a/src/infrastructure/implementations/crux-messenger.ts b/src/infrastructure/implementations/crux-messenger.ts index 4840fb91..faecd6cc 100644 --- a/src/infrastructure/implementations/crux-messenger.ts +++ b/src/infrastructure/implementations/crux-messenger.ts @@ -186,11 +186,12 @@ export class CruxNetPubSubClientFactory implements IPubSubClientFactory { }; } public getClient = (from: CruxId, keyManager: IKeyManager, to?: CruxId): IPubSubClient => { - if (this.bufferPahoClient[from.toString()]) { return this.bufferPahoClient[from.toString()]; } + const fromCruxIdString = from.toString(); + if (this.bufferPahoClient[fromCruxIdString]) { return this.bufferPahoClient[fromCruxIdString]; } const overrideOpts = this.getDomainLevelClientOptions(to ? to : from); - this.bufferPahoClient[from.toString()] = new PahoClient({ + this.bufferPahoClient[fromCruxIdString] = new PahoClient({ clientOptions: { - clientId: from.toString(), + clientId: fromCruxIdString, host: overrideOpts ? overrideOpts.host : this.options.defaultLinkServer.host, path: overrideOpts ? overrideOpts.path : this.options.defaultLinkServer.path, port: overrideOpts ? overrideOpts.port : this.options.defaultLinkServer.port, @@ -198,7 +199,7 @@ export class CruxNetPubSubClientFactory implements IPubSubClientFactory { }, subscribeOptions: this.defaultSubscribeOptions, }); - return this.bufferPahoClient[from.toString()]; + return this.bufferPahoClient[fromCruxIdString]; } private getDomainLevelClientOptions = (cruxId: CruxId): {host: string, port: number, path: string} | undefined => { // TODO Implement diff --git a/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts b/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts index 3a00c7e8..af9831c4 100644 --- a/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts +++ b/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts @@ -52,7 +52,6 @@ describe('Test CruxServiceClient - Prod', function() { const cruxWalletClient = new CruxWalletClient({ privateKey: user1PvtKey, walletClientName: "cruxdev", - isHost: true, cacheStorage: new InMemStorage(), }); const cruxServiceClient = new CruxServiceClient({ @@ -69,7 +68,6 @@ describe('Test CruxServiceClient - Prod', function() { const cruxWalletClient = new CruxWalletClient({ privateKey: user1PvtKey, walletClientName: "cruxdev", - isHost: true, cacheStorage: new InMemStorage(), }); const cruxServiceClient = new CruxServiceClient({ From 06165701e3298e8ecd0287dd2d8f3d386695cdbb Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Thu, 4 Jun 2020 17:13:25 +0530 Subject: [PATCH 15/16] typecheck fixed --- src/core/domain-services/remote-key-service.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/domain-services/remote-key-service.ts b/src/core/domain-services/remote-key-service.ts index 9bbea04d..a0f891b1 100644 --- a/src/core/domain-services/remote-key-service.ts +++ b/src/core/domain-services/remote-key-service.ts @@ -71,7 +71,8 @@ export class RemoteKeyHost { console.log("Inside RemoteKeyHost::in::Msg, senderId: ", msg, senderId); const data = await this.handleMessage(msg); console.log("Inside RemoteKeyHost::initialize::Data(handleMessage): ", data); - await this.sendInvocationResult(data, CruxId.fromString(senderId!)); + // @ts-ignore + await this.sendInvocationResult(data, CruxId.fromString(senderId!)); // getting senderId as string }); } private async sendInvocationResult(result: any, receiverId: CruxId) { From f85b7e3e8e0c9a3e81e0f68ce9764f9dc65ef983 Mon Sep 17 00:00:00 2001 From: malavindra5 Date: Thu, 4 Jun 2020 20:31:03 +0530 Subject: [PATCH 16/16] setup local HiveMQ broker and IP change --- src/application/clients/crux-gateway-bridge-config.json | 2 +- src/application/clients/crux-wallet-client.ts | 2 +- src/test/crux-messenger/test-crux-service-client.ts | 2 -- .../crux-messenger/paho-pubsub-client-runner.ts | 2 +- .../crux-messenger/secure-cruxid-messenger-prod-test.ts | 2 +- .../crux-messenger/test-crux-service-client-prod.ts | 2 +- .../crux-messenger/test-remote-key-client-prod.ts | 2 +- .../test-secure-cruxid-messenger-prod-pubsubClientFactory.ts | 2 +- 8 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/application/clients/crux-gateway-bridge-config.json b/src/application/clients/crux-gateway-bridge-config.json index e7732882..831c9617 100644 --- a/src/application/clients/crux-gateway-bridge-config.json +++ b/src/application/clients/crux-gateway-bridge-config.json @@ -1,6 +1,6 @@ { "HOST_URL": { - "BROKER_HOST": "broker.hivemq.com" + "BROKER_HOST": "127.0.0.1" }, "PORTS": { "BROKER_PORT": 8000, diff --git a/src/application/clients/crux-wallet-client.ts b/src/application/clients/crux-wallet-client.ts index 52b1d119..a74f6d87 100644 --- a/src/application/clients/crux-wallet-client.ts +++ b/src/application/clients/crux-wallet-client.ts @@ -98,7 +98,7 @@ export const getCruxUserRepository = (options: IBlockstackCruxUserRepositoryOpti export const getPubsubClientFactory = (): IPubSubClientFactory => { return new CruxNetPubSubClientFactory({defaultLinkServer: { - host: "broker.hivemq.com", + host: "127.0.0.1", path: "/mqtt", port: 8000, }}); diff --git a/src/test/crux-messenger/test-crux-service-client.ts b/src/test/crux-messenger/test-crux-service-client.ts index 0b46c861..6fba21db 100644 --- a/src/test/crux-messenger/test-crux-service-client.ts +++ b/src/test/crux-messenger/test-crux-service-client.ts @@ -56,7 +56,6 @@ describe('Test CruxServiceClient - InMemory', function() { const cruxWalletClient = new CruxWalletClient({ privateKey: this.user1Data.pvtKey, walletClientName: "cstestwallet", - isHost: true, cacheStorage: new InMemStorage(), }); const cruxServiceClient = new CruxServiceClient({ @@ -73,7 +72,6 @@ describe('Test CruxServiceClient - InMemory', function() { const cruxWalletClient = new CruxWalletClient({ privateKey: this.user1Data.pvtKey, walletClientName: "cstestwallet", - isHost: true, cacheStorage: new InMemStorage(), }); const cruxServiceClient = new CruxServiceClient({ diff --git a/src/test/integration-tests/crux-messenger/paho-pubsub-client-runner.ts b/src/test/integration-tests/crux-messenger/paho-pubsub-client-runner.ts index 8dea9c82..8eb983ed 100644 --- a/src/test/integration-tests/crux-messenger/paho-pubsub-client-runner.ts +++ b/src/test/integration-tests/crux-messenger/paho-pubsub-client-runner.ts @@ -11,7 +11,7 @@ patchMissingDependencies() chai.use(chaiAsPromised); chai.should(); const expect = require('chai').expect; -const BROKER_HOST = "broker.hivemq.com"; +const BROKER_HOST = "127.0.0.1"; const BROKER_PORT = 8000; const path = '/mqtt' diff --git a/src/test/integration-tests/crux-messenger/secure-cruxid-messenger-prod-test.ts b/src/test/integration-tests/crux-messenger/secure-cruxid-messenger-prod-test.ts index 8168a644..4406653e 100644 --- a/src/test/integration-tests/crux-messenger/secure-cruxid-messenger-prod-test.ts +++ b/src/test/integration-tests/crux-messenger/secure-cruxid-messenger-prod-test.ts @@ -21,7 +21,7 @@ const user2PvtKey = "cdf2d276caf0c9c34258ed6ebd0e60e0e8b3d9a7b8a9a717f2e19ed9b37 describe('Test Secure Crux Messenger - PROD', function() { beforeEach(async function() { - const HOST = "broker.hivemq.com"; + const HOST = "127.0.0.1"; const PORT = 8000; const path = '/mqtt'; this.user1KeyManager = new BasicKeyManager(user1PvtKey); diff --git a/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts b/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts index af9831c4..8e6e41e4 100644 --- a/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts +++ b/src/test/integration-tests/crux-messenger/test-crux-service-client-prod.ts @@ -24,7 +24,7 @@ const user2PvtKey = "KyBuSe1MMV6NjJgZfyWuvgmxUeAYswLC2HrfYLUri9aP3AS5FBfr"; // r describe('Test CruxServiceClient - Prod', function() { beforeEach(async function() { - const HOST = "broker.hivemq.com"; + const HOST = "127.0.0.1"; const PORT = 8000; this.user2CruxId = "release020@cruxdev.crux"; this.user1KeyManager = new BasicKeyManager(user1PvtKey); diff --git a/src/test/integration-tests/crux-messenger/test-remote-key-client-prod.ts b/src/test/integration-tests/crux-messenger/test-remote-key-client-prod.ts index b548b93a..78ffc5ff 100644 --- a/src/test/integration-tests/crux-messenger/test-remote-key-client-prod.ts +++ b/src/test/integration-tests/crux-messenger/test-remote-key-client-prod.ts @@ -24,7 +24,7 @@ const user2PvtKey = "KyBuSe1MMV6NjJgZfyWuvgmxUeAYswLC2HrfYLUri9aP3AS5FBfr"; // r describe('Test RemoteKeyClient - PROD', function() { beforeEach(async function() { - const HOST = "broker.hivemq.com"; + const HOST = "127.0.0.1"; const PORT = 8000; this.user2CruxId = "release020@cruxdev.crux"; this.user1KeyManager = new BasicKeyManager(user1PvtKey); diff --git a/src/test/integration-tests/crux-messenger/test-secure-cruxid-messenger-prod-pubsubClientFactory.ts b/src/test/integration-tests/crux-messenger/test-secure-cruxid-messenger-prod-pubsubClientFactory.ts index 2ea9db04..95fb501f 100644 --- a/src/test/integration-tests/crux-messenger/test-secure-cruxid-messenger-prod-pubsubClientFactory.ts +++ b/src/test/integration-tests/crux-messenger/test-secure-cruxid-messenger-prod-pubsubClientFactory.ts @@ -16,7 +16,7 @@ const expect = require('chai').expect; describe('Test Secure Crux Messenger - Prod pubsubClientFactory', function() { beforeEach(async function() { - const HOST = "broker.hivemq.com"; + const HOST = "127.0.0.1"; const PORT = 8000; const path = '/mqtt'; const userStore = new MockUserStore();