Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement the TACo API module #263

Merged
merged 9 commits into from
Sep 12, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
905 changes: 854 additions & 51 deletions abi/Coordinator.json

Large diffs are not rendered by default.

45 changes: 33 additions & 12 deletions src/agents/coordinator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SessionStaticKey } from '@nucypher/nucypher-core';
import { ethers } from 'ethers';
import { DkgPublicKey, SessionStaticKey } from '@nucypher/nucypher-core';
import { BigNumberish, ethers } from 'ethers';

import {
Coordinator,
Expand All @@ -13,12 +13,16 @@ import { DEFAULT_WAIT_N_CONFIRMATIONS, getContract } from './contracts';

export interface CoordinatorRitual {
initiator: string;
dkgSize: number;
initTimestamp: number;
endTimestamp: number;
totalTranscripts: number;
totalAggregations: number;
publicKey: BLS12381.G1PointStructOutput;
authority: string;
dkgSize: number;
threshold: number;
aggregationMismatch: boolean;
accessController: string;
publicKey: BLS12381.G1PointStructOutput;
aggregatedTranscript: string;
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are participants not stored in this struct? I guess maybe not needed...?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The contents of this struct are taken from types generated from contracts by typechain. I can trim them down to a size.

Expand Down Expand Up @@ -59,10 +63,18 @@ export class DkgCoordinatorAgent {
public static async initializeRitual(
provider: ethers.providers.Provider,
signer: ethers.Signer,
providers: ChecksumAddress[]
providers: ChecksumAddress[],
authority: string,
duration: BigNumberish,
accessController: string
): Promise<number> {
const Coordinator = await this.connectReadWrite(provider, signer);
const tx = await Coordinator.initiateRitual(providers);
const tx = await Coordinator.initiateRitual(
providers,
authority,
duration,
accessController
);
const txReceipt = await tx.wait(DEFAULT_WAIT_N_CONFIRMATIONS);
const [ritualStartEvent] = txReceipt.events ?? [];
if (!ritualStartEvent) {
Expand Down Expand Up @@ -95,16 +107,25 @@ export class DkgCoordinatorAgent {
const Coordinator = await this.connectReadOnly(provider);
// We leave `initiator` undefined because we don't care who the initiator is
// We leave `successful` undefined because we don't care if the ritual was successful
const eventFilter = Coordinator.filters.EndRitual(
ritualId,
undefined,
undefined
);
Coordinator.once(eventFilter, (_ritualId, _initiator, successful) => {
const eventFilter = Coordinator.filters.EndRitual(ritualId, undefined);
Coordinator.once(eventFilter, (_ritualId, successful) => {
callback(successful);
});
}

public static async getRitualIdFromPublicKey(
provider: ethers.providers.Provider,
dkgPublicKey: DkgPublicKey
): Promise<number> {
const Coordinator = await this.connectReadOnly(provider);
const dkgPublicKeyBytes = dkgPublicKey.toBytes();
const pointStruct: BLS12381.G1PointStruct = {
word0: dkgPublicKeyBytes.slice(0, 32),
word1: dkgPublicKeyBytes.slice(32, 48),
};
return await Coordinator.getRitualIdFromPublicKey(pointStruct);
}

private static async connectReadOnly(provider: ethers.providers.Provider) {
return await this.connect(provider);
}
Expand Down
11 changes: 5 additions & 6 deletions src/characters/cbd-recipient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { ethers } from 'ethers';

import { DkgCoordinatorAgent, DkgParticipant } from '../agents/coordinator';
import { ConditionContext } from '../conditions';
import { DkgRitual } from '../dkg';
import { PorterClient } from '../porter';
import { fromJSON, objectEquals, toJSON } from '../utils';

Expand All @@ -31,22 +30,22 @@ export class ThresholdDecrypter {
private readonly threshold: number
) {}

public static create(porterUri: string, dkgRitual: DkgRitual) {
public static create(porterUri: string, ritualId: number, threshold: number) {
return new ThresholdDecrypter(
new PorterClient(porterUri),
dkgRitual.id,
dkgRitual.dkgParams.threshold
ritualId,
threshold
);
}

// Retrieve and decrypt ciphertext using provider and condition expression
public async retrieveAndDecrypt(
provider: ethers.providers.Provider,
web3Provider: ethers.providers.Provider,
thresholdMessageKit: ThresholdMessageKit,
signer?: ethers.Signer
): Promise<Uint8Array> {
const decryptionShares = await this.retrieve(
provider,
web3Provider,
thresholdMessageKit,
signer
);
Expand Down
2 changes: 1 addition & 1 deletion src/conditions/context/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export class ConditionContext {
);
if (conditionRequiresSigner && !this.signer) {
throw new Error(
`Condition contains ${USER_ADDRESS_PARAM} context variable and requires a signer to populate`
`Signer required to satisfy ${USER_ADDRESS_PARAM} context variable in condition`
);
}

Expand Down
32 changes: 23 additions & 9 deletions src/dkg.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { DkgPublicKey } from '@nucypher/nucypher-core';
import { ethers } from 'ethers';
import { BigNumberish, ethers } from 'ethers';

import { DkgCoordinatorAgent, DkgRitualState } from './agents/coordinator';
import { ChecksumAddress } from './types';
Expand Down Expand Up @@ -58,22 +58,23 @@ export class DkgRitual {
}
}

// TODO: Currently, we're assuming that the threshold is always `floor(sharesNum / 2) + 1`.
// https://github.com/nucypher/nucypher/issues/3095
const assumedThreshold = (sharesNum: number): number =>
Math.floor(sharesNum / 2) + 1;

export class DkgClient {
public static async initializeRitual(
provider: ethers.providers.Provider,
signer: ethers.Signer,
ursulas: ChecksumAddress[],
authority: string,
duration: BigNumberish,
accessController: string,
waitUntilEnd = false
): Promise<number | undefined> {
const ritualId = await DkgCoordinatorAgent.initializeRitual(
provider,
signer,
ursulas.sort()
ursulas.sort(),
authority,
duration,
accessController
);

if (waitUntilEnd) {
Expand Down Expand Up @@ -111,7 +112,7 @@ export class DkgClient {
});
};

public static async getExistingRitual(
public static async getRitual(
provider: ethers.providers.Provider,
ritualId: number
): Promise<DkgRitual> {
Expand All @@ -129,12 +130,25 @@ export class DkgClient {
DkgPublicKey.fromBytes(dkgPkBytes),
{
sharesNum: ritual.dkgSize,
threshold: assumedThreshold(ritual.dkgSize),
threshold: ritual.threshold,
},
ritualState
);
}

public static async getFinalizedRitual(
provider: ethers.providers.Provider,
ritualId: number
): Promise<DkgRitual> {
const ritual = await DkgClient.getRitual(provider, ritualId);
if (ritual.state !== DkgRitualState.FINALIZED) {
throw new Error(
`Ritual ${ritualId} is not finalized. State: ${ritual.state}`
);
}
return ritual;
}

// TODO: Without Validator public key in Coordinator, we cannot verify the
// transcript. We need to add it to the Coordinator (nucypher-contracts #77).
// public async verifyRitual(ritualId: number): Promise<boolean> {
Expand Down
10 changes: 7 additions & 3 deletions src/sdk/strategy/cbd-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class CbdStrategy {
// // Given that we just initialized the ritual, this should never happen
// throw new Error('Ritual ID is undefined');
// }
const dkgRitual = await DkgClient.getExistingRitual(provider, ritualId);
const dkgRitual = await DkgClient.getRitual(provider, ritualId);
return DeployedCbdStrategy.create(dkgRitual, this.cohort.porterUri);
}

Expand Down Expand Up @@ -78,7 +78,11 @@ export class DeployedCbdStrategy {
) {}

public static create(dkgRitual: DkgRitual, porterUri: string) {
const decrypter = ThresholdDecrypter.create(porterUri, dkgRitual);
const decrypter = ThresholdDecrypter.create(
porterUri,
dkgRitual.id,
dkgRitual.dkgParams.threshold
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is threshold still needed, even though it is now part of the ritual struct?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The client needs to know how many shares to fetch from the nodes (/cbd_decrypt responses)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but now if you have the ritual id, you can get the value of the threshold from the Coordinator agent when doing the retrieve, or am I misunderstanding.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right 👍 . I mixed up my layers.

Side question: any reason we need the DkgRitualParameters object? This line could look nice as:

    const decrypter = ThresholdDecrypter.create(
      porterUri,
      dkgRitual.id,
      dkgRitual.threshold

? Anyways, just something to think about.

);
return new DeployedCbdStrategy(decrypter, dkgRitual.dkgPublicKey);
}

Expand All @@ -88,7 +92,7 @@ export class DeployedCbdStrategy {
porterUri: string,
ritualId: number
): Promise<DeployedCbdStrategy> {
const dkgRitual = await DkgClient.getExistingRitual(provider, ritualId);
const dkgRitual = await DkgClient.getRitual(provider, ritualId);
return DeployedCbdStrategy.create(dkgRitual, porterUri);
}

Expand Down
55 changes: 55 additions & 0 deletions src/taco.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { DkgPublicKey, ThresholdMessageKit } from '@nucypher/nucypher-core';
import { ethers } from 'ethers';

import { DkgCoordinatorAgent } from './agents/coordinator';
import { ThresholdDecrypter } from './characters/cbd-recipient';
import { Enrico } from './characters/enrico';
import { Condition, ConditionExpression } from './conditions';
import { DkgClient } from './dkg';
import { getPorterUri } from './porter';
import { toBytes } from './utils';

export const encrypt = async (
provider: ethers.providers.Provider,
message: string,
condition: Condition,
ritualId: number
): Promise<ThresholdMessageKit> => {
const dkgRitual = await DkgClient.getFinalizedRitual(provider, ritualId);
return await encryptLight(message, condition, dkgRitual.dkgPublicKey);
};

export const encryptLight = async (
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how I feel about Light as the term 😅 . Can this just be an overloaded function with the same name?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no support function overloading in JS/TS. I didn't have better ideas for an appropriate name, maybe we could use the blockchainy naming from the original TACo API issue.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

^ cc @cygnusv , @KPrasch, @jMyles (naming things).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have a good name for it, but I would prefer something like

export const encryptWithDKG = async (

than the original one

message: string,
condition: Condition,
dkgPublicKey: DkgPublicKey
): Promise<ThresholdMessageKit> => {
const encrypter = new Enrico(dkgPublicKey);
const conditionExpr = new ConditionExpression(condition);
return encrypter.encryptMessageCbd(toBytes(message), conditionExpr);
};

export const decrypt = async (
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This simplicity is great!

provider: ethers.providers.Provider,
messageKit: ThresholdMessageKit,
signer?: ethers.Signer,
porterUri = getPorterUri('tapir')
): Promise<Uint8Array> => {
const ritualId = await DkgCoordinatorAgent.getRitualIdFromPublicKey(
provider,
messageKit.acp.publicKey
);
const ritual = await DkgClient.getFinalizedRitual(provider, ritualId);
const decrypter = ThresholdDecrypter.create(
porterUri,
ritualId,
ritual.dkgParams.threshold
);
return decrypter.retrieveAndDecrypt(provider, messageKit, signer);
};

export const taco = {
encrypt,
encryptLight,
decrypt,
};
22 changes: 11 additions & 11 deletions test/unit/cbd-strategy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import {
fakeUrsulas,
makeCohort,
mockCbdDecrypt,
mockGetExistingRitual,
mockGetParticipants,
mockGetRitual,
mockGetUrsulas,
mockRandomSessionStaticSecret,
} from '../utils';
Expand All @@ -29,9 +29,9 @@ const {
} = conditions;

// Shared test variables
const aliceSecretKey = SecretKey.fromBEBytes(aliceSecretKeyBytes);
const aliceProvider = fakeProvider(aliceSecretKey.toBEBytes());
const aliceSigner = fakeSigner(aliceSecretKey.toBEBytes());
const secretKey = SecretKey.fromBEBytes(aliceSecretKeyBytes);
const provider = fakeProvider(secretKey.toBEBytes());
const signer = fakeSigner(secretKey.toBEBytes());
const ownsNFT = new ERC721Ownership({
contractAddress: '0x1e988ba4692e52Bc50b375bcC8585b95c48AaD77',
parameters: [3591],
Expand All @@ -51,12 +51,12 @@ const makeCbdStrategy = async () => {

async function makeDeployedCbdStrategy() {
const strategy = await makeCbdStrategy();

const mockedDkg = fakeDkgFlow(variant, 0, 4, 4);
const mockedDkgRitual = fakeDkgRitual(mockedDkg);
const getUrsulasSpy = mockGetUrsulas(ursulas);
const getExistingRitualSpy = mockGetExistingRitual(mockedDkgRitual);
const deployedStrategy = await strategy.deploy(aliceProvider, ritualId);
const getExistingRitualSpy = mockGetRitual(mockedDkgRitual);

const deployedStrategy = await strategy.deploy(provider, ritualId);

expect(getUrsulasSpy).toHaveBeenCalled();
expect(getExistingRitualSpy).toHaveBeenCalled();
Expand Down Expand Up @@ -108,13 +108,13 @@ describe('CbdDeployedStrategy', () => {
.encryptMessageCbd(message);

// Setup mocks for `retrieveAndDecrypt`
const { decryptionShares } = await fakeTDecFlow({
const { decryptionShares } = fakeTDecFlow({
...mockedDkg,
message: toBytes(message),
dkgPublicKey: mockedDkg.dkg.publicKey(),
thresholdMessageKit,
});
const { participantSecrets, participants } = await fakeDkgParticipants(
const { participantSecrets, participants } = fakeDkgParticipants(
mockedDkg.ritualId
);
const requesterSessionKey = SessionStaticSecret.random();
Expand All @@ -130,9 +130,9 @@ describe('CbdDeployedStrategy', () => {

const decryptedMessage =
await deployedStrategy.decrypter.retrieveAndDecrypt(
aliceProvider,
provider,
thresholdMessageKit,
aliceSigner
signer
);
expect(getUrsulasSpy).toHaveBeenCalled();
expect(getParticipantsSpy).toHaveBeenCalled();
Expand Down
8 changes: 7 additions & 1 deletion test/unit/conditions/condition-expr.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
TimeCondition,
TimeConditionProps,
} from '../../../src/conditions/base';
import { RpcConditionType } from '../../../src/conditions/base/rpc';
import { RpcConditionType } from '../../../src/conditions/base';
import { USER_ADDRESS_PARAM } from '../../../src/conditions/const';
import { ERC721Balance } from '../../../src/conditions/predefined';
import { objectEquals, toJSON } from '../../../src/utils';
Expand Down Expand Up @@ -187,6 +187,12 @@ describe('condition set', () => {
ConditionExpression.fromJSON(conditionExprJson);
expect(conditionExprFromJson).toBeDefined();
expect(conditionExprFromJson.equals(conditionExprFromJson)).toBeTruthy();

const asWasmConditions = conditionExprFromJson.toWASMConditions();
const fromWasmConditions =
ConditionExpression.fromWASMConditions(asWasmConditions);
expect(fromWasmConditions).toBeDefined();
expect(fromWasmConditions.equals(conditionExprFromJson)).toBeTruthy();
});

it('serializes to and from WASM conditions', () => {
Expand Down
Loading
Loading