Skip to content

Commit

Permalink
apply pr suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
vzotova committed Jul 30, 2024
1 parent fd1278c commit ef8dda6
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 57 deletions.
45 changes: 21 additions & 24 deletions packages/shared/src/porter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import { fromBase64, fromHexString, toBase64, toHexString } from './utils';
const defaultPorterUri: Record<string, string> = {
mainnet: 'https://porter.nucypher.community',
tapir: 'https://porter-tapir.nucypher.community',
oryx: 'https://porter-oryx.nucypher.community',
lynx: 'https://porter-lynx.nucypher.community',
};

Expand All @@ -35,21 +34,17 @@ export const getPorterUri = (domain: Domain): string => {
return getPorterUris(domain)[0];
};

export const getPorterUris = (domain: Domain, porterUri?: string | string[]): string[] => {
const porterUris: string[] = [];
if (porterUri) {
if (porterUri instanceof Array) {
porterUris.push(...porterUri);
} else {
porterUris.push(porterUri);
}
}
export const getPorterUris = (
domain: Domain,
porterUris: string[] = [],
): string[] => {
const fullList = [...porterUris];
const uri = defaultPorterUri[domain];
if (!uri) {
throw new Error(`No default Porter URI found for domain: ${domain}`);
}
porterUris.push(uri);
return porterUris;
fullList.push(uri);
return fullList;
};

// /get_ursulas
Expand Down Expand Up @@ -147,11 +142,13 @@ export class PorterClient {
}
}

protected async tryAndCall<T, D>(config: AxiosRequestConfig<D>): Promise<AxiosResponse<T>> {
protected async tryAndCall<T, D>(
config: AxiosRequestConfig<D>,
): Promise<AxiosResponse<T>> {
let resp!: AxiosResponse<T>;
let lastError = undefined;
for (const porterUrl of this.porterUrls) {
const localConfig = { ...config, baseURL: porterUrl.toString() }
const localConfig = { ...config, baseURL: porterUrl.toString() };
try {
resp = await axios.request(localConfig);
} catch (e) {
Expand All @@ -165,7 +162,9 @@ export class PorterClient {
if (lastError !== undefined) {
throw lastError;
}
throw new Error("Porter returns bad response");
throw new Error(
'Porter returns bad response: ${resp.status} - ${resp.data}',
);
}

public async getUrsulas(
Expand All @@ -185,8 +184,7 @@ export class PorterClient {
paramsSerializer: (params) => {
return qs.stringify(params, { arrayFormat: 'comma' });
},
},
);
});
return resp.data.result.ursulas.map((u: UrsulaResponse) => ({
checksumAddress: u.checksum_address,
uri: u.uri,
Expand Down Expand Up @@ -216,7 +214,7 @@ export class PorterClient {
await this.tryAndCall({
url: '/retrieve_cfrags',
method: 'post',
data: data
data: data,
});

return resp.data.result.retrieval_results.map(({ cfrags, errors }) => {
Expand All @@ -242,12 +240,11 @@ export class PorterClient {
),
threshold,
};
const resp: AxiosResponse<PostTacoDecryptResponse> =
await this.tryAndCall({
url: '/decrypt',
method: 'post',
data: data
});
const resp: AxiosResponse<PostTacoDecryptResponse> = await this.tryAndCall({
url: '/decrypt',
method: 'post',
data: data,
});

const { encrypted_decryption_responses, errors } =
resp.data.result.decryption_results;
Expand Down
62 changes: 34 additions & 28 deletions packages/shared/test/porter.test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { fakeUrsulas } from '@nucypher/test-utils';
import axios, { HttpStatusCode } from 'axios';
import { SpyInstance, beforeAll, describe, expect, it, vi } from 'vitest';
import {
initialize,
GetUrsulasResult,
PorterClient,
toHexString,
Ursula,
initialize,
toHexString,
} from '../src';
import { fakeUrsulas } from '@nucypher/test-utils';
import { beforeAll, describe, expect, SpyInstance, it, vi } from 'vitest';
import axios, { HttpStatusCode } from 'axios';

const fakePorterUris = ['https://_this_should_crash.com/', 'https://2_this_should_crash.com/', 'https://_this_should_work.com/'];
const fakePorterUris = [
'https://_this_should_crash.com/',
'https://2_this_should_crash.com/',
'https://_this_should_work.com/',
];

const mockGetUrsulas = (
ursulas: Ursula[] = fakeUrsulas(),
): SpyInstance => {
const mockGetUrsulas = (ursulas: Ursula[] = fakeUrsulas()): SpyInstance => {
const fakePorterUrsulas = (
mockUrsulas: readonly Ursula[],
): GetUrsulasResult => {
Expand All @@ -32,7 +34,10 @@ const mockGetUrsulas = (
return vi.spyOn(axios, 'request').mockImplementation(async (config) => {
switch (config.baseURL) {
case fakePorterUris[2]:
return Promise.resolve({ status: HttpStatusCode.Ok, data: fakePorterUrsulas(ursulas) });
return Promise.resolve({
status: HttpStatusCode.Ok,
data: fakePorterUrsulas(ursulas),
});
case fakePorterUris[0]:
throw new Error();
default:
Expand All @@ -46,37 +51,39 @@ describe('PorterClient', () => {
await initialize();
});

it('Get Ursulas', async () => {
it('should work when at least one ursula URI is valid', async () => {
const ursulas = fakeUrsulas();
const getUrsulasSpy = mockGetUrsulas(ursulas);
const porterClient = new PorterClient(fakePorterUris);
const result = await porterClient.getUrsulas(ursulas.length);

expect(result.every((u: Ursula, index: number) => {
const expectedUrsula = ursulas[index];
return u.checksumAddress === expectedUrsula.checksumAddress &&
u.uri === expectedUrsula.uri &&
u.encryptingKey.equals(expectedUrsula.encryptingKey);
})).toBeTruthy();
expect(
result.every((u: Ursula, index: number) => {
const expectedUrsula = ursulas[index];
return (
u.checksumAddress === expectedUrsula.checksumAddress &&
u.uri === expectedUrsula.uri &&
u.encryptingKey.equals(expectedUrsula.encryptingKey)
);
}),
).toBeTruthy();
const params = {
method: 'get',
url: "/get_ursulas",
url: '/get_ursulas',
params: {
exclude_ursulas: [],
include_ursulas: [],
quantity: ursulas.length,
}
},
};

expect(getUrsulasSpy).toBeCalledTimes(fakePorterUris.length);
expect(getUrsulasSpy).toHaveBeenNthCalledWith(1, expect.objectContaining(
{ ...params, baseURL: fakePorterUris[0] })
);
expect(getUrsulasSpy).toHaveBeenNthCalledWith(2, expect.objectContaining(
{ ...params, baseURL: fakePorterUris[1] })
);
expect(getUrsulasSpy).toHaveBeenNthCalledWith(3, expect.objectContaining(
{ ...params, baseURL: fakePorterUris[2] }));
fakePorterUris.forEach((value, index) => {
expect(getUrsulasSpy).toHaveBeenNthCalledWith(
index + 1,
expect.objectContaining({ ...params, baseURL: value }),
);
});
});

it('returns error in case all porters fail', async () => {
Expand All @@ -87,5 +94,4 @@ describe('PorterClient', () => {
porterClient = new PorterClient([fakePorterUris[1], fakePorterUris[0]]);
expect(porterClient.getUrsulas(ursulas.length)).rejects.toThrowError();
});

});
8 changes: 4 additions & 4 deletions packages/taco/src/taco.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export const encryptWithPublicKey = async (
* @param {Domain} domain - Represents the logical network in which the decryption will be performed.
* Must match the `ritualId`.
* @param {ThresholdMessageKit} messageKit - The kit containing the message to be decrypted
* @param {string} [porterUri] - The URI for the Porter service. If not provided, a value will be obtained
* @param {string} [porterUri] - The URI(s) for the Porter service. If not provided, a value will be obtained
* from the Domain
* @param {ethers.Signer} [signer] - An optional signer for the decryption
* @param {Record<string, CustomContextParam>} [customParameters] - Optional custom parameters that may be required
Expand All @@ -139,11 +139,11 @@ export const decrypt = async (
provider: ethers.providers.Provider,
domain: Domain,
messageKit: ThresholdMessageKit,
porterUri?: string | string[],
porterUris: string[] = [],
signer?: ethers.Signer,
customParameters?: Record<string, CustomContextParam>,
): Promise<Uint8Array> => {
const porterUris: string[] = getPorterUris(domain, porterUri);
const porterUrisFull: string[] = getPorterUris(domain, porterUris);

const ritualId = await DkgCoordinatorAgent.getRitualIdFromPublicKey(
provider,
Expand All @@ -154,7 +154,7 @@ export const decrypt = async (
return retrieveAndDecrypt(
provider,
domain,
porterUris,
porterUrisFull,
messageKit,
ritualId,
ritual.sharesNum,
Expand Down
2 changes: 1 addition & 1 deletion packages/taco/test/taco.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ describe('taco', () => {
provider,
domains.DEVNET,
messageKit,
fakePorterUri,
[fakePorterUri],
signer,
);
expect(getParticipantsSpy).toHaveBeenCalled();
Expand Down

0 comments on commit ef8dda6

Please sign in to comment.