Skip to content

Commit

Permalink
feat(sdk-lib-mpc): support DKLS DKG primitives
Browse files Browse the repository at this point in the history
Ticket: HSM-267
  • Loading branch information
islamaminBitGo committed Feb 14, 2024
1 parent cabaec4 commit 4f42bbb
Show file tree
Hide file tree
Showing 9 changed files with 541 additions and 70 deletions.
69 changes: 0 additions & 69 deletions modules/sdk-core/src/bitgo/utils/opengpgUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,75 +309,6 @@ export async function encryptText(text: string, key: Key): Promise<string> {
});
}

/**
* Encrypts and detach signs a string
* @param text string to encrypt and sign
* @param publicArmor public key to encrypt with
* @param privateArmor private key to sign with
*/
export async function encryptAndDetachSignText(
text: string,
publicArmor: string,
privateArmor: string
): Promise<AuthEncMessage> {
const publicKey = await readKey({ armoredKey: publicArmor });
const privateKey = await readPrivateKey({ armoredKey: privateArmor });
const message = await createMessage({ text });
const encryptedMessage = await encrypt({
message,
encryptionKeys: publicKey,
format: 'armored',
config: {
rejectCurves: new Set(),
showVersion: false,
showComment: false,
},
});
const signature = await sign({
message,
signingKeys: privateKey,
format: 'armored',
detached: true,
config: {
rejectCurves: new Set(),
showVersion: false,
showComment: false,
},
});
return {
encryptedMessage: encryptedMessage,
signature: signature,
};
}

/**
* Encrypts and detach signs a string
* @param text string to encrypt and sign
* @param publicArmor public key to verify signature with
* @param privateArmor private key to decrypt with
*/
export async function decryptAndVerifySignedText(
encryptedAndSignedMessage: AuthEncMessage,
publicArmor: string,
privateArmor: string
): Promise<string> {
const publicKey = await readKey({ armoredKey: publicArmor });
const privateKey = await readPrivateKey({ armoredKey: privateArmor });
const decryptedMessage = await decrypt({
message: await readMessage({ armoredMessage: encryptedAndSignedMessage.encryptedMessage }),
decryptionKeys: privateKey,
signature: await readSignature({ armoredSignature: encryptedAndSignedMessage.signature }),
verificationKeys: publicKey,
expectSigned: true,
config: {
rejectCurves: new Set(),
showVersion: false,
showComment: false,
},
});
return decryptedMessage.data;
}

/**
* Encrypts and signs a string
* @param text string to encrypt and sign
Expand Down
5 changes: 4 additions & 1 deletion modules/sdk-lib-mpc/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,14 @@
"dependencies": {
"@noble/secp256k1": "1.6.3",
"@types/superagent": "4.1.15",
"@silencelaboratories/dkls-wasm-ll-node": "0.1.0-pre.2",
"@wasmer/wasi": "^1.2.2",
"bigint-crypto-utils": "3.1.4",
"bigint-mod-arith": "3.1.2",
"libsodium-wrappers-sumo": "^0.7.9",
"paillier-bigint": "3.3.0"
"paillier-bigint": "3.3.0",
"cbor": "^9.0.1",
"openpgp": "5.10.1"
},
"devDependencies": {
"@types/lodash": "^4.14.151",
Expand Down
131 changes: 131 additions & 0 deletions modules/sdk-lib-mpc/src/tss/ecdsa-dkls/commsLayer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { SerializedMessages, AuthEncMessage, AuthEncMessages } from './types';
import * as pgp from 'openpgp';

/**
* Detach signs a binary and encodes it in base64
* @param data binary to encode in base64 and sign
* @param privateArmor private key to sign with
*/
export async function detachSignData(data: Buffer, privateArmor: string): Promise<AuthEncMessage> {
const message = await pgp.createMessage({ binary: data });
const privateKey = await pgp.readPrivateKey({ armoredKey: privateArmor });
const signature = await pgp.sign({
message,
signingKeys: privateKey,
format: 'armored',
detached: true,
config: {
rejectCurves: new Set(),
showVersion: false,
showComment: false,
},
});
return {
encryptedMessage: data.toString('base64'),
signature: signature,
};
}

/**
* Encrypts and detach signs a binary
* @param data binary to encrypt and sign
* @param publicArmor public key to encrypt with
* @param privateArmor private key to sign with
*/
export async function encryptAndDetachSignData(
data: Buffer,
publicArmor: string,
privateArmor: string
): Promise<AuthEncMessage> {
const message = await pgp.createMessage({ binary: data });
const publicKey = await pgp.readKey({ armoredKey: publicArmor });
const privateKey = await pgp.readPrivateKey({ armoredKey: privateArmor });
const encryptedMessage = await pgp.encrypt({
message,
encryptionKeys: publicKey,
format: 'armored',
config: {
rejectCurves: new Set(),
showVersion: false,
showComment: false,
},
});
const signature = await pgp.sign({
message,
signingKeys: privateKey,
format: 'armored',
detached: true,
config: {
rejectCurves: new Set(),
showVersion: false,
showComment: false,
},
});
return {
encryptedMessage: encryptedMessage,
signature: signature,
};
}

/**
* Decrypts and verifies signature on a binary
* @param encryptedAndSignedMessage message to decrypt and verify
* @param publicArmor public key to verify signature with
* @param privateArmor private key to decrypt with
*/
export async function decryptAndVerifySignedData(
encryptedAndSignedMessage: AuthEncMessage,
publicArmor: string,
privateArmor: string
): Promise<string> {
const publicKey = await pgp.readKey({ armoredKey: publicArmor });
const privateKey = await pgp.readPrivateKey({ armoredKey: privateArmor });
const decryptedMessage = await pgp.decrypt({
message: await pgp.readMessage({ armoredMessage: encryptedAndSignedMessage.encryptedMessage }),
decryptionKeys: [privateKey],
config: {
rejectCurves: new Set(),
showVersion: false,
showComment: false,
},
format: 'binary',
});
const verificationResult = await pgp.verify({
message: await pgp.createMessage({ binary: decryptedMessage.data }),
signature: await pgp.readSignature({ armoredSignature: encryptedAndSignedMessage.signature }),
verificationKeys: publicKey,
});
await verificationResult.signatures[0].verified;
return Buffer.from(decryptedMessage.data).toString('base64');
}

export async function encryptAndAuthOutgoingMessages(
messages: SerializedMessages,
pubEncryptionGpgKey: string,
prvAuthenticationGpgKey: string
): Promise<AuthEncMessages> {
return {
p2pMessages: await Promise.all(
messages.p2pMessages.map(async (m) => {
return {
to: m.to,
from: m.from,
payload: await encryptAndDetachSignData(
Buffer.from(m.payload, 'base64'),
pubEncryptionGpgKey,
prvAuthenticationGpgKey
),
commitment: m.commitment,
};
})
),
broadcastMessages: await Promise.all(
messages.broadcastMessages.map(async (m) => {
return {
from: m.from,
payload: await detachSignData(Buffer.from(m.payload, 'base64'), prvAuthenticationGpgKey),
};
})
),
};
}
138 changes: 138 additions & 0 deletions modules/sdk-lib-mpc/src/tss/ecdsa-dkls/dkg.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { KeygenSession, Keyshare, Message } from '@silencelaboratories/dkls-wasm-ll-node';
import { DeserializedBroadcastMessage, DeserializedMessages, DkgState } from './types';
import { decode } from 'cbor';

export class Dkg {
protected dkgSession: KeygenSession;
protected dkgKeyShare: Keyshare;
protected n: number;
protected t: number;
protected chainCodeCommitment: Uint8Array | undefined;
protected partyIdx: number;
protected dkgState: DkgState = DkgState.Uninitialized;

constructor(n: number, t: number, partyIdx: number) {
this.n = n;
this.t = t;
this.partyIdx = partyIdx;
this.chainCodeCommitment = undefined;
}

private _deserializeState() {
const round = decode(this.dkgSession.toBytes()).round;
switch (round) {
case 'WaitMsg1':
this.dkgState = DkgState.Round1;
break;
case 'WaitMsg2':
this.dkgState = DkgState.Round2;
break;
case 'WaitMsg3':
this.dkgState = DkgState.Round3;
break;
case 'WaitMsg4':
this.dkgState = DkgState.Round4;
break;
case 'Ended':
this.dkgState = DkgState.Complete;
break;
default:
this.dkgState = DkgState.InvalidState;
throw `Invalid State: ${round}`;
}
}

async initDkg(): Promise<DeserializedBroadcastMessage> {
if (this.t > this.n || this.partyIdx >= this.n) {
throw 'Invalid parameters for DKG';
}
if (this.dkgState != DkgState.Uninitialized) {
throw 'DKG session already initialized';
}
this.dkgSession = new KeygenSession(this.n, this.t, this.partyIdx);
try {
const payload = this.dkgSession.createFirstMessage().payload;
this._deserializeState();
return {
payload: payload,
from: this.partyIdx,
};
} catch (e) {
throw `Error while creating the first message from party ${this.partyIdx}: ${e}`;
}
}

getKeyShare(): Buffer {
const keyShareBuff = Buffer.from(this.dkgKeyShare.toBytes());
this.dkgKeyShare.free();
return keyShareBuff;
}

handleIncomingMessages(messagesForIthRound: DeserializedMessages): DeserializedMessages {
try {
let nextRoundMessages: Message[];
if (this.dkgState == DkgState.Round3) {
const commitmentsUnsorted = messagesForIthRound.p2pMessages
.map((m) => {
return { from: m.from, commitment: m.commitment };
})
.concat([{ from: this.partyIdx, commitment: this.chainCodeCommitment }]);
const commitmentsSorted = commitmentsUnsorted
.sort((a, b) => {
return a.from - b.from;
})
.map((c) => c.commitment);
nextRoundMessages = this.dkgSession.handleMessages(
messagesForIthRound.broadcastMessages
.map((m) => new Message(m.payload, m.from, undefined))
.concat(messagesForIthRound.p2pMessages.map((m) => new Message(m.payload, m.from, m.to))),
commitmentsSorted
);
} else {
nextRoundMessages = this.dkgSession.handleMessages(
messagesForIthRound.broadcastMessages
.map((m) => new Message(m.payload, m.from, undefined))
.concat(messagesForIthRound.p2pMessages.map((m) => new Message(m.payload, m.from, m.to))),
undefined
);
}
if (this.dkgState == DkgState.Round4) {
this.dkgKeyShare = this.dkgSession.keyshare();
this.dkgState = DkgState.Complete;
return { broadcastMessages: [], p2pMessages: [] };
} else {
// Update ronud data.
this._deserializeState();
}
if (this.dkgState == DkgState.Round3) {
this.chainCodeCommitment = this.dkgSession.calculateChainCodeCommitment();
}
const nextRoundSerializedMessages = {
p2pMessages: nextRoundMessages
.filter((m) => m.to_id !== undefined)
.map((m) => {
const p2pReturn = {
payload: m.payload,
from: m.from_id,
to: m.to_id!,
commitment: this.chainCodeCommitment,
};
return p2pReturn;
}),
broadcastMessages: nextRoundMessages
.filter((m) => m.to_id === undefined)
.map((m) => {
const broadcastReturn = {
payload: m.payload,
from: m.from_id,
};
return broadcastReturn;
}),
};
nextRoundMessages.forEach((m) => m.free());
return nextRoundSerializedMessages;
} catch (e) {
throw `Error while creating messages from party ${this.partyIdx}, round ${this.dkgState}: ${e}`;
}
}
}
2 changes: 2 additions & 0 deletions modules/sdk-lib-mpc/src/tss/ecdsa-dkls/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * as DklsDkg from './dkg';
export * as DklsTypes from './types';
Loading

0 comments on commit 4f42bbb

Please sign in to comment.