Skip to content

Commit

Permalink
Merge branch '27-refator-encryptor' into 'dev'
Browse files Browse the repository at this point in the history
Resolve "Refactor the packages to retrieve the message encryptor from external sources"

Closes #27

See merge request ergo/rosen-bridge/sign-protocols!37
  • Loading branch information
vorujack committed Nov 8, 2024
2 parents 790bba0 + 96ea1c3 commit aeec351
Show file tree
Hide file tree
Showing 19 changed files with 124 additions and 108 deletions.
8 changes: 8 additions & 0 deletions .changeset/nine-colts-kneel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@rosen-bridge/ergo-multi-sig': major
'@rosen-bridge/communication': major
'@rosen-bridge/detection': major
'@rosen-bridge/tss': major
---

Refactor constructor interfaces, add messageEnc and remove unnecessary secrets
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Rosen Bridge Sign Protocols

A monorepo containing all the packages related to Rosen Bridge Signing process. It contains the following packages:

1. [keygen-service](./services/keygen-service/README.md): Keygen service is a tool top of [tss-api](./services/tss-api/README.md) for setup keygen ceremony for new guards.
2. [tss-api](./services/tss-api/README.md): A service for keygen, sign and regroup operations on eddsa and ecdsa protocols in threshold signature.
3. [communication](./packages/communication/README.md): A package that abstractly manages communication between endpoints.
4. [encryption](./packages/encryption/README.md): unify encryption interface.
5. [detection](./packages/detection/README.md): A package that finds available endpoints in private network.
6. [tss](./packages/tss/README.md): A package for building and validating TSS signatures.
7. [ergo-multi-sig](./packages/ergo-multi-sig/README.md): A package that manage multi signature protocol for ergo network.

For more info on how each of the packages works, refer to their specific page.
16 changes: 8 additions & 8 deletions packages/communication/lib/Communicator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { guardMessageValidTimeoutDefault } from './const/const';

export abstract class Communicator {
protected logger: AbstractLogger;
protected signer: EncryptionHandler;
protected messageEnc: EncryptionHandler;
private readonly submitMessage: (
msg: string,
peers: Array<string>,
Expand All @@ -21,13 +21,13 @@ export abstract class Communicator {

protected constructor(
logger: AbstractLogger,
signer: EncryptionHandler,
messageEnc: EncryptionHandler,
submitMessage: (msg: string, peers: Array<string>) => unknown,
guardPks: Array<string>,
messageValidDurationSeconds?: number,
) {
this.logger = logger;
this.signer = signer;
this.messageEnc = messageEnc;
this.guardPks = guardPks;
this.submitMessage = submitMessage;
this.messageValidDuration = messageValidDurationSeconds
Expand All @@ -40,7 +40,7 @@ export abstract class Communicator {
*/
protected getIndex = async () => {
if (this.index === -1) {
const pk = await this.signer.getPk();
const pk = await this.messageEnc.getPk();
this.index = this.guardPks.indexOf(pk);
}
return this.index;
Expand All @@ -66,8 +66,8 @@ export abstract class Communicator {
* @param timestamp
*/
signPayload = async (payload: any, timestamp: number) => {
const publicKey = await this.signer.getPk();
return await this.signer.sign(
const publicKey = await this.messageEnc.getPk();
return await this.messageEnc.sign(
Communicator.generatePayloadToSign(payload, timestamp, publicKey),
);
};
Expand All @@ -92,7 +92,7 @@ export abstract class Communicator {
)} to ${JSON.stringify(peers)}`,
);
timestamp = timestamp ? timestamp : this.getDate();
const publicKey = await this.signer.getPk();
const publicKey = await this.messageEnc.getPk();
const payloadSign = await this.signPayload(payload, timestamp);
const message: CommunicationMessage = {
type: messageType,
Expand Down Expand Up @@ -142,7 +142,7 @@ export abstract class Communicator {
return;
}
if (
!(await this.signer.verify(
!(await this.messageEnc.verify(
Communicator.generatePayloadToSign(
msg.payload,
msg.timestamp,
Expand Down
34 changes: 19 additions & 15 deletions packages/communication/tests/Comunicator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,23 @@ import { describe, expect, it, vi, beforeEach } from 'vitest';
describe('Communicator', () => {
let communicator: TestCommunicator;
let mockSubmit = vi.fn();
let guardSigners: Array<EdDSA>;
let guardMessageEncs: Array<EdDSA>;
const payload = { foo: 'bar' };

beforeEach(async () => {
guardSigners = [];
guardMessageEncs = [];
const guardPks: Array<string> = [];
for (let index = 0; index < 10; index++) {
const sk = new EdDSA(await EdDSA.randomKey());
guardSigners.push(sk);
guardMessageEncs.push(sk);
guardPks.push(await sk.getPk());
}
mockSubmit = vi.fn();
communicator = new TestCommunicator(guardSigners[1], mockSubmit, guardPks);
communicator = new TestCommunicator(
guardMessageEncs[1],
mockSubmit,
guardPks,
);
});

describe('getDate', () => {
Expand Down Expand Up @@ -51,8 +55,8 @@ describe('Communicator', () => {
*/
it('should call submit message', async () => {
const currentTime = 1685683141;
const publicKey = await guardSigners[1].getPk();
const sign = await guardSigners[1].sign(
const publicKey = await guardMessageEncs[1].getPk();
const sign = await guardMessageEncs[1].sign(
`${JSON.stringify(payload)}${currentTime}${publicKey}`,
);
vi.spyOn(Date, 'now').mockReturnValue(currentTime * 1000);
Expand Down Expand Up @@ -84,8 +88,8 @@ describe('Communicator', () => {
*/
it('should pass arguments to process message function when sign is valid', async () => {
const currentTime = 1685683142;
const publicKey = await guardSigners[2].getPk();
const sign = await guardSigners[2].sign(
const publicKey = await guardMessageEncs[2].getPk();
const sign = await guardMessageEncs[2].sign(
`${JSON.stringify(payload)}${currentTime}${publicKey}`,
);
vi.spyOn(Date, 'now').mockReturnValue(currentTime * 1000);
Expand Down Expand Up @@ -120,15 +124,15 @@ describe('Communicator', () => {
*/
it('should not call processMessage when signature is not valid', async () => {
const currentTime = 1685683143;
const publicKey = await guardSigners[2].getPk();
const sign = await guardSigners[2].sign(
const publicKey = await guardMessageEncs[2].getPk();
const sign = await guardMessageEncs[2].sign(
`${JSON.stringify(payload)}${currentTime}${publicKey}`,
);
vi.spyOn(Date, 'now').mockReturnValue(currentTime * 1000);
const message = {
type: 'message',
payload: payload,
publicKey: await guardSigners[3].getPk(),
publicKey: await guardMessageEncs[3].getPk(),
timestamp: currentTime,
sign: sign,
index: 3,
Expand All @@ -148,8 +152,8 @@ describe('Communicator', () => {
*/
it('should not call processMessage when signer public key differ from index', async () => {
const currentTime = 1685683144;
const publicKey = await guardSigners[2].getPk();
const sign = await guardSigners[2].sign(
const publicKey = await guardMessageEncs[2].getPk();
const sign = await guardMessageEncs[2].sign(
`${JSON.stringify(payload)}${currentTime}${publicKey}`,
);
vi.spyOn(Date, 'now').mockReturnValue(currentTime * 1000);
Expand Down Expand Up @@ -177,8 +181,8 @@ describe('Communicator', () => {
*/
it('should not call processMessage when message timed out', async () => {
const currentTime = 1685683145;
const publicKey = await guardSigners[2].getPk();
const sign = await guardSigners[2].sign(
const publicKey = await guardMessageEncs[2].getPk();
const sign = await guardMessageEncs[2].sign(
`${JSON.stringify(payload)}${currentTime - 60001}${publicKey}`,
);
vi.spyOn(Date, 'now').mockReturnValue(currentTime * 1000);
Expand Down
4 changes: 2 additions & 2 deletions packages/detection/lib/GuardDetection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export class GuardDetection extends Communicator {
constructor(config: GuardDetectionConfig) {
super(
config.logger ? config.logger : new DummyLogger(),
config.signer,
config.messageEnc,
config.submit,
config.guardsPublicKey,
config.messageValidDurationSeconds,
Expand Down Expand Up @@ -322,7 +322,7 @@ export class GuardDetection extends Communicator {
*/
activeGuards = async (): Promise<Array<ActiveGuard>> => {
const myActiveGuard: ActiveGuard = {
publicKey: await this.signer.getPk(),
publicKey: await this.messageEnc.getPk(),
peerId: await this.getPeerId(),
};
return [
Expand Down
2 changes: 1 addition & 1 deletion packages/detection/lib/interfaces/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export interface ActiveGuard {
export interface GuardDetectionConfig {
logger?: AbstractLogger;
guardsPublicKey: string[];
signer: EncryptionHandler;
messageEnc: EncryptionHandler;
submit: (msg: string, peers: Array<string>) => unknown;
activeTimeoutSeconds?: number;
heartbeatTimeoutSeconds?: number;
Expand Down
18 changes: 9 additions & 9 deletions packages/detection/tests/GuardDetection.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,16 @@ import { describe, expect, it, vi, beforeEach } from 'vitest';
describe('GuardDetection', () => {
let detection: TestGuardDetection;
let mockSubmit = vi.fn();
let guardSigners: Array<EdDSA>;
let guardMessageEncs: Array<EdDSA>;

beforeEach(async () => {
const signers = await generateSigners();
guardSigners = signers.guardSigners;
guardMessageEncs = signers.guardSigners;
vi.resetAllMocks();
mockSubmit = vi.fn();
detection = new TestGuardDetection({
submit: mockSubmit,
signer: guardSigners[0],
messageEnc: guardMessageEncs[0],
guardsPublicKey: signers.guardPks,
getPeerId: () => Promise.resolve('myPeerId'),
});
Expand Down Expand Up @@ -241,7 +241,7 @@ describe('GuardDetection', () => {
const info = detection.getInfo();
const currentTime = 1685683141;
vi.setSystemTime(new Date(currentTime * 1000));
const myPk = await guardSigners[0].getPk();
const myPk = await guardMessageEncs[0].getPk();
info.forEach((item, index) => {
if (item.publicKey !== myPk) {
item.lastUpdate = currentTime;
Expand Down Expand Up @@ -294,7 +294,7 @@ describe('GuardDetection', () => {
const callback = vi.fn();
await detection.register(
'peerId-1',
await guardSigners[1].getPk(),
await guardMessageEncs[1].getPk(),
callback,
);
await expect(callback).toHaveBeenCalledTimes(1);
Expand All @@ -320,7 +320,7 @@ describe('GuardDetection', () => {
const callback = vi.fn();
await detection.register(
'peerId-1',
await guardSigners[1].getPk(),
await guardMessageEncs[1].getPk(),
callback,
);
await expect(callback).toHaveBeenCalledTimes(1);
Expand All @@ -340,7 +340,7 @@ describe('GuardDetection', () => {
it('should call send message if guard is not in active state', async () => {
await detection.register(
'peerId-1',
await guardSigners[1].getPk(),
await guardMessageEncs[1].getPk(),
vi.fn(),
);
expect(mockSubmit).toHaveBeenCalledTimes(1);
Expand Down Expand Up @@ -368,12 +368,12 @@ describe('GuardDetection', () => {
vi.spyOn(detection as any, 'addNonce').mockReturnValue('new nonce');
await detection.mockedHandleRegister(
{ nonce: 'random nonce' },
await guardSigners[1].getPk(),
await guardMessageEncs[1].getPk(),
1,
);
expect(mockSubmit).toHaveBeenCalledTimes(1);
expect(mockSubmit).toHaveBeenCalledWith(expect.any(String), [
await guardSigners[1].getPk(),
await guardMessageEncs[1].getPk(),
]);
const msg = JSON.parse(mockSubmit.mock.calls[0][0]);
expect(msg.type).toEqual(approveMessage);
Expand Down
3 changes: 1 addition & 2 deletions packages/ergo-multi-sig/lib/MultiSigHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
} from './types';
import { turnTime } from './const';
import { Semaphore } from 'await-semaphore';
import { ECDSA } from '@rosen-bridge/encryption';
import { MultiSigUtils } from './MultiSigUtils';
import { AbstractLogger, DummyLogger } from '@rosen-bridge/abstract-logger';
import { ActiveGuard, GuardDetection } from '@rosen-bridge/detection';
Expand All @@ -33,7 +32,7 @@ export class MultiSigHandler extends Communicator {
constructor(config: ErgoMultiSigConfig) {
super(
config.logger ? config.logger : new DummyLogger(),
new ECDSA(config.secretHex),
config.messageEnc,
config.submit,
config.guardsPk,
);
Expand Down
2 changes: 2 additions & 0 deletions packages/ergo-multi-sig/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as wasm from 'ergo-lib-wasm-nodejs';
import { AbstractLogger } from '@rosen-bridge/abstract-logger';
import { MultiSigUtils } from './MultiSigUtils';
import { GuardDetection } from '@rosen-bridge/detection';
import { EncryptionHandler } from '@rosen-bridge/encryption';

interface Signer {
id?: string;
Expand Down Expand Up @@ -107,6 +108,7 @@ export enum MessageType {
interface ErgoMultiSigConfig {
logger?: AbstractLogger;
multiSigUtilsInstance: MultiSigUtils;
messageEnc: EncryptionHandler;
secretHex: string;
txSignTimeout: number;
multiSigFirstSignDelay?: number;
Expand Down
7 changes: 0 additions & 7 deletions packages/ergo-multi-sig/tests/MultiSigUtils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
import { MultiSigUtils } from '../lib';
import { describe, expect, it } from 'vitest';
import { boxJs } from './testData';
import {
getChangeBoxJs,
getOutBoxJs,
jsToReducedTx,
} from './testUtils/txUtils';
import * as wasm from 'ergo-lib-wasm-nodejs';
import { ErgoBox } from 'ergo-lib-wasm-nodejs';
import fs from 'fs';
import path from 'path';
import { mockedErgoStateContext } from '@rosen-bridge/ergo-multi-sig/tests/testData';
Expand Down
5 changes: 3 additions & 2 deletions packages/ergo-multi-sig/tests/testUtils/TestUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ class TestUtils {
});
const pubKeys = pks ? pks : testPubs;
const secretInd = testSecrets.indexOf(secret);
const ecdsaSigner = new ECDSA(testSecrets[secretInd]);
const ecdsaMessageEnc = new ECDSA(testSecrets[secretInd]);
const guardDetection = new GuardDetection({
guardsPublicKey: pubKeys,
signer: ecdsaSigner,
messageEnc: ecdsaMessageEnc,
submit: submit,
getPeerId: () => Promise.resolve(testPubs[secretInd]),
});
Expand All @@ -43,6 +43,7 @@ class TestUtils {

return new MultiSigHandler({
multiSigUtilsInstance: multiSigUtilsInstance,
messageEnc: ecdsaMessageEnc,
secretHex: secret,
txSignTimeout: TestConfigs.txSignTimeout,
multiSigFirstSignDelay: TestConfigs.multiSigFirstSignDelay,
Expand Down
8 changes: 4 additions & 4 deletions packages/tss/lib/tss/EcdsaSigner.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { ECDSA } from '@rosen-bridge/encryption';
import { EcdsaConfig, Sign, SignResult } from '../types/signer';
import { Sign, SignerConfig, SignResult } from '../types/signer';
import { TssSigner } from './TssSigner';

export class EcdsaSigner extends TssSigner {
constructor(config: EcdsaConfig) {
constructor(config: SignerConfig) {
super({
logger: config.logger,
guardsPk: config.guardsPk,
signingCrypto: 'ecdsa',
messageEnc: config.messageEnc,
submitMsg: config.submitMsg,
messageValidDuration: config.messageValidDuration,
timeoutSeconds: config.timeoutSeconds,
Expand All @@ -20,7 +21,6 @@ export class EcdsaSigner extends TssSigner {
thresholdTTL: config.thresholdTTL,
responseDelay: config.responseDelay,
signPerRoundLimit: config.signPerRoundLimit,
signer: new ECDSA(config.secret),
});
}

Expand Down
8 changes: 4 additions & 4 deletions packages/tss/lib/tss/EddsaSigner.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { EdDSA } from '@rosen-bridge/encryption';
import { EddsaConfig, Sign, SignResult } from '../types/signer';
import { Sign, SignerConfig, SignResult } from '../types/signer';
import { TssSigner } from './TssSigner';

export class EddsaSigner extends TssSigner {
constructor(config: EddsaConfig) {
constructor(config: SignerConfig) {
super({
logger: config.logger,
guardsPk: config.guardsPk,
signingCrypto: 'eddsa',
messageEnc: config.messageEnc,
submitMsg: config.submitMsg,
messageValidDuration: config.messageValidDuration,
timeoutSeconds: config.timeoutSeconds,
Expand All @@ -20,7 +21,6 @@ export class EddsaSigner extends TssSigner {
thresholdTTL: config.thresholdTTL,
responseDelay: config.responseDelay,
signPerRoundLimit: config.signPerRoundLimit,
signer: new EdDSA(config.secret),
});
}

Expand Down
Loading

0 comments on commit aeec351

Please sign in to comment.