Skip to content

Commit c99d1f0

Browse files
committed
feat: changes in lit node client to remove misc, missed in previous commit
1 parent cfc3c34 commit c99d1f0

File tree

1 file changed

+58
-108
lines changed

1 file changed

+58
-108
lines changed

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

Lines changed: 58 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import { SiweMessage } from 'siwe';
66
import {
77
getFormattedAccessControlConditions,
88
getHashedAccessControlConditions,
9-
validateAccessControlConditions,
109
} from '@lit-protocol/access-control-conditions';
1110
import {
1211
createSiweMessage,
@@ -16,7 +15,6 @@ import {
1615
generateAuthSig,
1716
generateSessionCapabilityObjectWithWildcards,
1817
LitAccessControlConditionResource,
19-
LitResourceAbilityRequest,
2018
} from '@lit-protocol/auth-helpers';
2119
import {
2220
AUTH_METHOD_TYPE,
@@ -41,31 +39,26 @@ import {
4139
WalletSignatureNotFoundError,
4240
} from '@lit-protocol/constants';
4341
import { getNodePrices } from '@lit-protocol/contracts-sdk';
44-
import { composeLitUrl, LitCore } from '@lit-protocol/core';
42+
import { composeLitUrl, mostCommonValue, LitCore } from '@lit-protocol/core';
4543
import {
4644
combineSignatureShares,
4745
encrypt,
4846
generateSessionKeyPair,
4947
verifyAndDecryptWithSignatureShares,
5048
verifySignature,
5149
} from '@lit-protocol/crypto';
52-
import {
53-
defaultMintClaimCallback,
54-
findMostCommonResponse,
55-
formatSessionSigs,
56-
hexPrefixed,
57-
mostCommonString,
58-
normalizeAndStringify,
59-
removeHexPrefix,
60-
safeParams,
61-
validateSessionSigs,
62-
} from '@lit-protocol/misc';
6350
import {
6451
getStorageItem,
6552
removeStorageItem,
6653
setStorageItem,
6754
} from '@lit-protocol/misc-browser';
6855
import { nacl } from '@lit-protocol/nacl';
56+
import {
57+
applySchemaWithValidation,
58+
DecryptRequestSchema,
59+
EncryptRequestSchema,
60+
JsonExecutionSdkParamsBaseSchema,
61+
} from '@lit-protocol/schemas';
6962
import {
7063
AuthCallback,
7164
AuthCallbackParams,
@@ -96,6 +89,7 @@ import {
9689
JsonSignSessionKeyRequestV1,
9790
JsonSignSessionKeyRequestV2,
9891
LitNodeClientConfig,
92+
LitResourceAbilityRequest,
9993
NodeBlsSigningShare,
10094
NodeCommandResponse,
10195
NodeSet,
@@ -117,19 +111,25 @@ import {
117111
uint8arrayToString,
118112
} from '@lit-protocol/uint8arrays';
119113

114+
import { assembleMostCommonResponse } from './helpers/assemble-most-common-response';
120115
import { encodeCode } from './helpers/encode-code';
121116
import { getBlsSignatures } from './helpers/get-bls-signatures';
122117
import { getClaims } from './helpers/get-claims';
123118
import { getClaimsList } from './helpers/get-claims-list';
124119
import { getExpiration } from './helpers/get-expiration';
125120
import { getMaxPricesForNodeProduct } from './helpers/get-max-prices-for-node-product';
126121
import { getSignatures } from './helpers/get-signatures';
122+
import { hexPrefixed, removeHexPrefix } from './helpers/hex';
123+
import { defaultMintClaimCallback } from './helpers/mint-claim-callback';
124+
import { normalizeAndStringify } from './helpers/normalize-and-stringify';
127125
import { normalizeArray } from './helpers/normalize-array';
128126
import { normalizeJsParams } from './helpers/normalize-params';
129127
import { parseAsJsonOrString } from './helpers/parse-as-json-or-string';
130128
import { parsePkpSignResponse } from './helpers/parse-pkp-sign-response';
131129
import { processLitActionResponseStrategy } from './helpers/process-lit-action-response-strategy';
132130
import { removeDoubleQuotes } from './helpers/remove-double-quotes';
131+
import { formatSessionSigs } from './helpers/session-sigs-reader';
132+
import { validateSessionSigs } from './helpers/session-sigs-validator';
133133
import { blsSessionSigVerify } from './helpers/validate-bls-session-sig';
134134

135135
export class LitNodeClient extends LitCore implements ILitNodeClient {
@@ -622,6 +622,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
622622

623623
return this.generatePromise(urlWithPath, reqBody, requestId);
624624
}
625+
625626
/**
626627
*
627628
* Execute JS on the nodes and combine and return any resulting signatures
@@ -635,51 +636,43 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
635636
params: JsonExecutionSdkParams
636637
): Promise<ExecuteJsResponse> => {
637638
// ========== Validate Params ==========
639+
const _params = applySchemaWithValidation(
640+
'executeJs',
641+
params,
642+
JsonExecutionSdkParamsBaseSchema
643+
);
644+
638645
if (!this.ready) {
639646
const message =
640647
'[executeJs] LitNodeClient is not ready. Please call await litNodeClient.connect() first.';
641648

642649
throw new LitNodeClientNotReadyError({}, message);
643650
}
644651

645-
const paramsIsSafe = safeParams({
646-
functionName: 'executeJs',
647-
params: params,
648-
});
649-
650-
if (!paramsIsSafe) {
651-
throw new InvalidParamType(
652-
{
653-
info: {
654-
params,
655-
},
656-
},
657-
'executeJs params are not valid'
658-
);
659-
}
660-
661652
// Format the params
662653
let formattedParams: JsonExecutionSdkParams = {
663-
...params,
664-
...(params.jsParams && { jsParams: normalizeJsParams(params.jsParams) }),
665-
...(params.code && { code: encodeCode(params.code) }),
654+
..._params,
655+
...(_params.jsParams && {
656+
jsParams: normalizeJsParams(_params.jsParams),
657+
}),
658+
...(_params.code && { code: encodeCode(_params.code) }),
666659
};
667660

668661
// Check if IPFS options are provided and if the code should be fetched from IPFS and overwrite the current code.
669662
// This will fetch the code from the specified IPFS gateway using the provided ipfsId,
670663
// and update the params with the fetched code, removing the ipfsId afterward.
671664
const overwriteCode =
672-
params.ipfsOptions?.overwriteCode ||
665+
_params.ipfsOptions?.overwriteCode ||
673666
GLOBAL_OVERWRITE_IPFS_CODE_BY_NETWORK[this.config.litNetwork];
674667

675-
if (overwriteCode && params.ipfsId) {
668+
if (overwriteCode && _params.ipfsId) {
676669
const code = await this._getFallbackIpfsCode(
677-
params.ipfsOptions?.gatewayUrl,
678-
params.ipfsId
670+
_params.ipfsOptions?.gatewayUrl,
671+
_params.ipfsId
679672
);
680673

681674
formattedParams = {
682-
...params,
675+
..._params,
683676
code: code,
684677
ipfsId: undefined,
685678
};
@@ -689,15 +682,15 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
689682

690683
const userMaxPrices = await this.getMaxPricesForNodeProduct({
691684
product: 'LIT_ACTION',
692-
userMaxPrice: params.userMaxPrice,
685+
userMaxPrice: _params.userMaxPrice,
693686
});
694687

695-
const targetNodePrices = params.useSingleNode
688+
const targetNodePrices = _params.useSingleNode
696689
? userMaxPrices.slice(0, 1)
697690
: userMaxPrices;
698691

699692
const sessionSigs = await this._getSessionSigs({
700-
...params.authContext,
693+
..._params.authContext,
701694
userMaxPrices: targetNodePrices,
702695
});
703696

@@ -720,7 +713,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
720713
const res = await this._handleNodePromises(
721714
nodePromises,
722715
requestId,
723-
params.useSingleNode ? 1 : this._getThreshold()
716+
_params.useSingleNode ? 1 : this._getThreshold()
724717
);
725718

726719
// -- case: promises rejected
@@ -737,13 +730,13 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
737730
});
738731

739732
// -- find the responseData that has the most common response
740-
const mostCommonResponse = findMostCommonResponse(
733+
const mostCommonResponse = assembleMostCommonResponse(
741734
responseData
742735
) as NodeShare;
743736

744737
const responseFromStrategy = processLitActionResponseStrategy(
745738
responseData,
746-
params.responseStrategy ?? { strategy: 'leastCommon' }
739+
_params.responseStrategy ?? { strategy: 'leastCommon' }
747740
);
748741
mostCommonResponse.response = responseFromStrategy;
749742

@@ -792,7 +785,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
792785
const parsedResponse = parseAsJsonOrString(mostCommonResponse.response);
793786

794787
// -- 3. combine logs
795-
const mostCommonLogs: string = mostCommonString(
788+
const mostCommonLogs: string = mostCommonValue(
796789
responseData.map(
797790
(r: {
798791
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -813,7 +806,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
813806
[key]: await getSignatures({
814807
requestId,
815808
networkPubKeySet: this.networkPubKeySet,
816-
threshold: params.useSingleNode ? 1 : this._getThreshold(),
809+
threshold: _params.useSingleNode ? 1 : this._getThreshold(),
817810
signedMessageShares: flattenedSignedMessageShares,
818811
}),
819812
}
@@ -997,6 +990,12 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
997990
*/
998991
encrypt = async (params: EncryptSdkParams): Promise<EncryptResponse> => {
999992
// ========== Validate Params ==========
993+
const _params = applySchemaWithValidation(
994+
'encrypt',
995+
params,
996+
EncryptRequestSchema
997+
);
998+
1000999
// -- validate if it's ready
10011000
if (!this.ready) {
10021001
throw new LitNodeClientNotReadyError(
@@ -1010,29 +1009,10 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
10101009
throw new LitNodeClientNotReadyError({}, 'subnetPubKey cannot be null');
10111010
}
10121011

1013-
const paramsIsSafe = safeParams({
1014-
functionName: 'encrypt',
1015-
params,
1016-
});
1017-
1018-
if (!paramsIsSafe) {
1019-
throw new InvalidArgumentException(
1020-
{
1021-
info: {
1022-
params,
1023-
},
1024-
},
1025-
'You must provide either accessControlConditions or evmContractConditions or solRpcConditions or unifiedAccessControlConditions'
1026-
);
1027-
}
1028-
1029-
// ========== Validate Access Control Conditions Schema ==========
1030-
await validateAccessControlConditions(params);
1031-
10321012
// ========== Hashing Access Control Conditions =========
10331013
// hash the access control conditions
10341014
const hashOfConditions: ArrayBuffer | undefined =
1035-
await getHashedAccessControlConditions(params);
1015+
await getHashedAccessControlConditions(_params);
10361016

10371017
if (!hashOfConditions) {
10381018
throw new InvalidArgumentException(
@@ -1083,10 +1063,10 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
10831063
*
10841064
*/
10851065
decrypt = async (params: DecryptRequest): Promise<DecryptResponse> => {
1086-
const { authContext, authSig, chain, ciphertext, dataToEncryptHash } =
1087-
params;
1066+
// -- validate params
1067+
const { authContext, chain, ciphertext, dataToEncryptHash, userMaxPrice } =
1068+
applySchemaWithValidation('decrypt', params, DecryptRequestSchema);
10881069

1089-
// ========== Validate Params ==========
10901070
// -- validate if it's ready
10911071
if (!this.ready) {
10921072
throw new LitNodeClientNotReadyError(
@@ -1100,22 +1080,6 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
11001080
throw new LitNodeClientNotReadyError({}, 'subnetPubKey cannot be null');
11011081
}
11021082

1103-
const paramsIsSafe = safeParams({
1104-
functionName: 'decrypt',
1105-
params,
1106-
});
1107-
1108-
if (!paramsIsSafe) {
1109-
throw new InvalidArgumentException(
1110-
{
1111-
info: {
1112-
params,
1113-
},
1114-
},
1115-
'Parameter validation failed.'
1116-
);
1117-
}
1118-
11191083
// ========== Hashing Access Control Conditions =========
11201084
// hash the access control conditions
11211085
const hashOfConditions: ArrayBuffer | undefined =
@@ -1165,37 +1129,23 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
11651129

11661130
this.#logger.info('identityParam', identityParam);
11671131

1168-
let sessionSigs: SessionSigsMap = {};
11691132
const userMaxPrices = await this.getMaxPricesForNodeProduct({
11701133
product: 'DECRYPTION',
1171-
userMaxPrice: params.userMaxPrice,
1134+
userMaxPrice,
11721135
});
11731136

1174-
if (!authSig) {
1175-
if (!authContext) {
1176-
throw new InvalidArgumentException(
1177-
{
1178-
info: {
1179-
params,
1180-
},
1181-
},
1182-
'Missing auth context; you must provide either authSig or authContext.'
1183-
);
1184-
}
1185-
1186-
sessionSigs = await this._getSessionSigs({
1187-
...authContext,
1188-
userMaxPrices,
1189-
});
1190-
}
1137+
const sessionSigs = await this._getSessionSigs({
1138+
...authContext,
1139+
userMaxPrices,
1140+
});
11911141

11921142
// ========== Get Network Signature ==========
11931143
const requestId = this._getNewRequestId();
11941144
const nodePromises = this._getNodePromises(
11951145
userMaxPrices.map(({ url }) => url),
11961146
(url: string) => {
11971147
// -- if session key is available, use it
1198-
const authSigToSend = authSig ? authSig : sessionSigs[url];
1148+
const authSigToSend = sessionSigs[url];
11991149

12001150
if (!authSigToSend) {
12011151
throw new InvalidArgumentException(
@@ -1479,7 +1429,7 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
14791429

14801430
const blsSignedData: BlsResponseData[] = validatedSignedDataList;
14811431

1482-
const sigType = mostCommonString(blsSignedData.map((s) => s.curveType));
1432+
const sigType = mostCommonValue(blsSignedData.map((s) => s.curveType));
14831433
this.#logger.info(`[signSessionKey] sigType:`, sigType);
14841434

14851435
const signatureShares = getBlsSignatures(blsSignedData);
@@ -1496,10 +1446,10 @@ export class LitNodeClient extends LitCore implements ILitNodeClient {
14961446
const publicKey = removeHexPrefix(params.pkpPublicKey);
14971447
this.#logger.info(`[signSessionKey] publicKey:`, publicKey);
14981448

1499-
const dataSigned = mostCommonString(blsSignedData.map((s) => s.dataSigned));
1449+
const dataSigned = mostCommonValue(blsSignedData.map((s) => s.dataSigned));
15001450
this.#logger.info(`[signSessionKey] dataSigned:`, dataSigned);
15011451

1502-
const mostCommonSiweMessage = mostCommonString(
1452+
const mostCommonSiweMessage = mostCommonValue(
15031453
blsSignedData.map((s) => s.siweMessage)
15041454
);
15051455

0 commit comments

Comments
 (0)