Skip to content

Commit 590015b

Browse files
committed
feat: it works! - add respond handling strategy
1 parent d141b0d commit 590015b

File tree

8 files changed

+295
-96
lines changed

8 files changed

+295
-96
lines changed

packages/lit-node-client-nodejs/src/lib/helpers/parseCustomResources.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,25 @@ export function parseCustomResources(nodeResponses: any) {
33
return {
44
signedMessage: item.siweMessage
55
};
6-
}).map((v: any) => {
6+
}).map((v: any, i: number) => {
77
const signedMessage = v.signedMessage;
88
const urnLine = signedMessage.match(/urn:recap:[\w\d]+/)![0];
99

1010
const authContext = JSON.parse(atob(urnLine.split(':')[2])).att['lit-resolvedauthcontext://*']['Auth/Auth'][0]['auth_context'];
1111

1212
const extractedCustomAuthResource = (authContext['customAuthResource']).slice(8, -2);
13-
const formattedCustomAuthResource = extractedCustomAuthResource.replace(/\\"/g, '"');
13+
const customAuthResources = extractedCustomAuthResource.replace(/\\"/g, '"');
1414
let result;
1515

1616
try {
17-
result = JSON.parse(formattedCustomAuthResource);
17+
result = JSON.parse(customAuthResources);
1818
} catch (e) {
1919
result = extractedCustomAuthResource
2020
}
2121

2222
return {
23-
authContext,
24-
formattedCustomAuthResource: result,
23+
customAuthResources: result,
24+
// authContext,
2525
};
26-
}).find((item: any) => item.formattedCustomAuthResource !== 'undefined')))?.formattedCustomAuthResource
26+
}).find((item: any) => item.customAuthResources !== 'undefined'))).customAuthResources;
2727
}

packages/lit-node-client-nodejs/src/lib/lit-node-client-nodejs.ts

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import {
4343
findMostCommonResponse,
4444
formatSessionSigs,
4545
hexPrefixed,
46+
leastCommonString,
4647
log,
4748
logError,
4849
logErrorWithRequestId,
@@ -1881,8 +1882,8 @@ export class LitNodeClientNodeJs
18811882

18821883
// -- resolve promises
18831884
const numberToResolve = params?.handleAllResponses ? this.connectedNodes.size : this.config.minNodeCount;
1885+
log(`[signSessionKey] number of node promises to resolve:`, numberToResolve);
18841886

1885-
console.log("numberToResolve:", numberToResolve);
18861887
let res;
18871888
try {
18881889
res = await this.handleNodePromises(
@@ -1896,19 +1897,14 @@ export class LitNodeClientNodeJs
18961897
}
18971898

18981899
// -- handle all responses
1899-
let customResources;
1900-
1901-
1902-
console.log("res:", res);
1900+
let customAuthResources;
19031901

19041902
try {
1905-
customResources = parseCustomResources(res);
1903+
customAuthResources = parseCustomResources(res);
19061904
} catch (e) {
19071905
log(`Failed to parse custom resources, not a problem.`)
19081906
}
19091907

1910-
console.log("customResources:", customResources);
1911-
19121908
logWithRequestId(requestId, 'handleNodePromises res:', res);
19131909

19141910
// -- case: promises rejected
@@ -2010,10 +2006,12 @@ export class LitNodeClientNodeJs
20102006
);
20112007
}
20122008

2009+
const commonStringStrategy = params?.strategy === 'mostCommon' ? mostCommonString : leastCommonString;
2010+
20132011
const blsSignedData: BlsResponseData[] =
20142012
validatedSignedDataList as BlsResponseData[];
20152013

2016-
const sigType = mostCommonString(blsSignedData.map((s) => s.curveType));
2014+
const sigType = commonStringStrategy(blsSignedData.map((s) => s.curveType));
20172015
log(`[signSessionKey] sigType:`, sigType);
20182016

20192017
const signatureShares = getBlsSignatures(blsSignedData);
@@ -2030,10 +2028,10 @@ export class LitNodeClientNodeJs
20302028
const publicKey = removeHexPrefix(params.pkpPublicKey);
20312029
log(`[signSessionKey] publicKey:`, publicKey);
20322030

2033-
const dataSigned = mostCommonString(blsSignedData.map((s) => s.dataSigned));
2031+
const dataSigned = commonStringStrategy(blsSignedData.map((s) => s.dataSigned));
20342032
log(`[signSessionKey] dataSigned:`, dataSigned);
20352033

2036-
const mostCommonSiweMessage = mostCommonString(
2034+
const mostCommonSiweMessage = commonStringStrategy(
20372035
blsSignedData.map((s) => s.siweMessage)
20382036
);
20392037

@@ -2052,7 +2050,7 @@ export class LitNodeClientNodeJs
20522050
derivedVia: 'lit.bls',
20532051
signedMessage,
20542052
address: computeAddress(hexPrefixed(publicKey)),
2055-
...(customResources && { customResources: customResources })
2053+
...(customAuthResources && { customAuthResources: customAuthResources })
20562054
},
20572055
pkpPublicKey: publicKey,
20582056
};
@@ -2140,6 +2138,7 @@ export class LitNodeClientNodeJs
21402138
...(params.jsParams && { jsParams: params.jsParams }),
21412139
});
21422140

2141+
21432142
const needToResignSessionKey = await this.checkNeedToResignSessionKey({
21442143
authSig,
21452144
sessionKeyUri,

packages/misc/src/lib/misc.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,23 @@ export const mostCommonString = (arr: Array<any>): any => {
6565
.pop();
6666
};
6767

68+
/**
69+
*
70+
* Find the element that occurs the least in an array
71+
*
72+
* @param { Array<any> } arr
73+
* @returns { any } the element that appeared the least
74+
*/
75+
export const leastCommonString = (arr: Array<any>): any => {
76+
return arr
77+
.sort(
78+
(a: any, b: any) =>
79+
arr.filter((v: any) => v === b).length -
80+
arr.filter((v: any) => v === a).length
81+
)
82+
.pop();
83+
};
84+
6885
export const findMostCommonResponse = (responses: Array<object>): object => {
6986
const result: { [key: string]: any } = {};
7087

packages/types/src/lib/interfaces.ts

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1047,7 +1047,7 @@ export interface CreateCustomAuthMethodRequest {
10471047
// pub auth_sig: Option<AuthSigItem>,
10481048
// pub siwe_message: String,
10491049
// }
1050-
export interface SignSessionKeyProp extends LitActionSdkParams {
1050+
export interface SignSessionKeyProp extends LitActionSdkParams, RespondHandling {
10511051
/**
10521052
* The serialized session key pair to sign. If not provided, a session key pair will be fetched from localStorge or generated.
10531053
*/
@@ -1091,11 +1091,6 @@ export interface SignSessionKeyProp extends LitActionSdkParams {
10911091
* A LIT resource ability is a combination of a LIT resource and a LIT ability.
10921092
*/
10931093
resourceAbilityRequests?: LitResourceAbilityRequest[];
1094-
1095-
/**
1096-
* By default, it handles minNodeCount of responses
1097-
*/
1098-
handleAllResponses?: boolean;
10991094
}
11001095

11011096
export interface SignSessionKeyResponse {
@@ -1915,7 +1910,7 @@ export interface SignerLike {
19151910

19161911
export interface GetPkpSessionSigs
19171912
extends CommonGetSessionSigsProps,
1918-
LitActionSdkParams {
1913+
LitActionSdkParams, RespondHandling {
19191914
pkpPublicKey: string;
19201915

19211916
/**
@@ -1929,8 +1924,6 @@ export interface GetPkpSessionSigs
19291924
authMethods?: AuthMethod[];
19301925

19311926
ipfsOptions?: IpfsOptions;
1932-
1933-
handleAllResponses?: boolean;
19341927
}
19351928

19361929
/**
@@ -1950,12 +1943,19 @@ export type GetLitActionSessionSigs = CommonGetSessionSigsProps &
19501943
})
19511944
) & {
19521945
ipfsOptions?: IpfsOptions;
1946+
} & RespondHandling;
19531947

1954-
/**
1955-
* Special property to return all node responses
1956-
*/
1957-
handleAllResponses?: boolean;
1958-
};
1948+
export interface RespondHandling {
1949+
/**
1950+
* Weather to handle all responses or threshold/minNodeCount responses
1951+
*/
1952+
handleAllResponses?: boolean;
1953+
1954+
/**
1955+
* Strategy to handle responses
1956+
*/
1957+
strategy?: ResponseStrategy;
1958+
}
19591959

19601960
export interface SessionKeyCache {
19611961
value: SessionKeyPair;

packages/wrapped-keys/src/lib/api/tria-batch-generate-private-keys.ts

Lines changed: 48 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -67,19 +67,9 @@ export async function triaBatchGeneratePrivateKeys(
6767
accessControlConditions: [allowPkpAddressToDecrypt],
6868
};
6969

70-
// const { pkpSessionSigs, litNodeClient } = params;
71-
72-
// const sessionSig = getFirstSessionSig(pkpSessionSigs);
73-
// const pkpAddress = getPkpAddressFromSessionSig(sessionSig);
74-
75-
// const allowPkpAddressToDecrypt = getPkpAccessControlCondition(pkpAddress);
76-
77-
// const { litActionCode, litActionIpfsCid } = getLitActionCodeOrCidCommon(
78-
// 'batchGenerateEncryptedKeys'
79-
// );
80-
8170
try {
8271
litActionSessionSigs = await params.litNodeClient.getLitActionSessionSigs({
72+
expiration: new Date(Date.now() + 1000 * 60 * 10).toISOString(),
8373
pkpPublicKey: params.pkpPublicKey,
8474
resourceAbilityRequests: [
8575
{
@@ -94,52 +84,56 @@ export async function triaBatchGeneratePrivateKeys(
9484
litActionIpfsId: params.ipfsId,
9585
jsParams: _jsParams,
9686
handleAllResponses: true,
87+
strategy: 'leastCommon',
9788
});
9889
} catch (e) {
9990
throw new Error(`Error getting Lit Action Session Sigs: ${e}`);
10091
}
10192

102-
console.log("litActionSessionSigs:", litActionSessionSigs);
103-
104-
process.exit();
105-
106-
return { pkpAddress: pkpEthAddress, results: [] };
107-
108-
// TODO: Uncomment below
109-
// const keyParamsBatch = actionResults.map((keyData) => {
110-
// const { generateEncryptedPrivateKey, network } = keyData;
111-
// return {
112-
// ...generateEncryptedPrivateKey,
113-
// keyType: getKeyTypeFromNetwork(network),
114-
// };
115-
// });
116-
117-
// const { ids } = await storePrivateKeyBatch({
118-
// sessionSig,
119-
// storedKeyMetadataBatch: keyParamsBatch,
120-
// litNetwork: litNodeClient.config.litNetwork,
121-
// });
122-
123-
// const results = actionResults.map(
124-
// (actionResult, ndx): BatchGeneratePrivateKeysActionResult => {
125-
// const {
126-
// generateEncryptedPrivateKey: { memo, publicKey },
127-
// } = actionResult;
128-
// const id = ids[ndx]; // Result of writes is in same order as provided
129-
130-
// const signature = actionResult.signMessage?.signature;
131-
132-
// return {
133-
// ...(signature ? { signMessage: { signature } } : {}),
134-
// generateEncryptedPrivateKey: {
135-
// memo: memo,
136-
// id,
137-
// generatedPublicKey: publicKey,
138-
// pkpAddress,
139-
// },
140-
// };
141-
// }
142-
// );
143-
144-
// return { pkpAddress, results };
93+
const firstSessionSig = Object.entries(litActionSessionSigs)[0][1];
94+
95+
const firstSignedMessage = JSON.parse(firstSessionSig.signedMessage);
96+
97+
const firstCapabilities = firstSignedMessage.capabilities[0];
98+
99+
const theCustomAuthResources = firstCapabilities.customAuthResources;
100+
101+
const pkpAddress = getPkpAddressFromSessionSig(firstSessionSig);
102+
103+
const keyParamsBatch = theCustomAuthResources.map((keyData: any) => {
104+
const { generateEncryptedPrivateKey, network } = keyData;
105+
return {
106+
...generateEncryptedPrivateKey,
107+
keyType: getKeyTypeFromNetwork(network),
108+
};
109+
});
110+
111+
const { ids } = await storePrivateKeyBatch({
112+
sessionSig: firstSessionSig,
113+
storedKeyMetadataBatch: keyParamsBatch,
114+
litNetwork: params.litNodeClient.config.litNetwork,
115+
});
116+
117+
const results = theCustomAuthResources.map(
118+
(actionResult: any, ndx: any): BatchGeneratePrivateKeysActionResult => {
119+
const {
120+
generateEncryptedPrivateKey: { memo, publicKey },
121+
} = actionResult;
122+
const id = ids[ndx]; // Result of writes is in same order as provided
123+
124+
const signature = actionResult.signMessage?.signature;
125+
126+
return {
127+
...(signature ? { signMessage: { signature } } : {}),
128+
generateEncryptedPrivateKey: {
129+
memo: memo,
130+
id,
131+
generatedPublicKey: publicKey,
132+
pkpAddress,
133+
},
134+
};
135+
}
136+
);
137+
138+
return { pkpAddress, results };
145139
}

packages/wrapped-keys/src/lib/service-client/utils.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,8 @@ export async function makeRequest<T>({
135135
return result;
136136
} catch (e: unknown) {
137137
throw new Error(
138-
`Request(${requestId}) for wrapped key failed. Error: ${
139-
(e as Error).message
140-
// @ts-expect-error Unknown, but `cause` is on `TypeError: fetch failed` errors
138+
`Request(${requestId}) for wrapped key failed. Error: ${(e as Error).message
139+
// @ts-expect-error Unknown, but `cause` is on `TypeError: fetch failed` errors
141140
}${e.cause ? ' - ' + e.cause : ''}`
142141
);
143142
}

tsconfig.json

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,24 @@
1010
"importHelpers": true,
1111
"target": "ES2020",
1212
"module": "ES2020",
13-
"lib": ["ES2020", "dom", "ES2021.String"],
13+
"lib": [
14+
"ES2020",
15+
"dom",
16+
"ES2021.String"
17+
],
1418
"skipLibCheck": true,
1519
"skipDefaultLibCheck": true,
1620
"baseUrl": ".",
1721
"allowSyntheticDefaultImports": true,
1822
"resolveJsonModule": true,
1923
"paths": {
20-
"@lit-protocol/*": ["packages/*/src"]
24+
"@lit-protocol/*": [
25+
"packages/*/src"
26+
]
2127
}
2228
},
23-
"exclude": ["node_modules", "tmp"]
24-
}
29+
"exclude": [
30+
"node_modules",
31+
"tmp"
32+
]
33+
}

0 commit comments

Comments
 (0)