Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion packages/sdk/core/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY =
'0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d' as const;

/** Maximum total bits for ZK proof packing */
export const TFHE_RS_ZK_MAX_BITS = 2048n as const;
export const TFHE_RS_ZK_MAX_BITS = 2048 as const;

/** Size limit for safe_serialize/safe_deserialize (1 GB) */
export const TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT = BigInt(1 << 30);
Expand Down
12 changes: 6 additions & 6 deletions packages/sdk/core/encrypt/cofheMocksZkVerifySign.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { type EncryptableItem, FheTypes } from '../types.js';
import { MAX_ENCRYPTABLE_BITS, type VerifyResult } from './zkPackProveVerify.js';
import { type VerifyResult } from './zkPackProveVerify.js';
import {
createWalletClient,
http,
Expand All @@ -14,7 +14,7 @@ import { MockZkVerifierAbi } from './MockZkVerifierAbi.js';
import { hardhat } from 'viem/chains';
import { CofheError, CofheErrorCode } from '../error.js';
import { privateKeyToAccount, sign } from 'viem/accounts';
import { MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, MOCKS_ZK_VERIFIER_ADDRESS } from '../consts.js';
import { MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, MOCKS_ZK_VERIFIER_ADDRESS, TFHE_RS_ZK_MAX_BITS } from '../consts.js';

type EncryptableItemWithCtHash = EncryptableItem & {
ctHash: bigint;
Expand Down Expand Up @@ -69,14 +69,14 @@ export async function cofheMocksCheckEncryptableBits(items: EncryptableItem[]):
}
}
}
if (totalBits > MAX_ENCRYPTABLE_BITS) {
if (totalBits > TFHE_RS_ZK_MAX_BITS) {
throw new CofheError({
code: CofheErrorCode.ZkPackFailed,
message: `Total bits ${totalBits} exceeds ${MAX_ENCRYPTABLE_BITS}`,
hint: `Ensure that the total bits of the items to encrypt does not exceed ${MAX_ENCRYPTABLE_BITS}`,
message: `Total bits ${totalBits} exceeds ${TFHE_RS_ZK_MAX_BITS}`,
hint: `Ensure that the total bits of the items to encrypt does not exceed ${TFHE_RS_ZK_MAX_BITS}`,
context: {
totalBits,
maxBits: MAX_ENCRYPTABLE_BITS,
maxBits: TFHE_RS_ZK_MAX_BITS,
items,
},
});
Expand Down
5 changes: 2 additions & 3 deletions packages/sdk/core/encrypt/encryptInputsBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,7 @@ class MockZkListBuilder {

const MockCrs = {
free: () => {},
serialize: () => new Uint8Array(),
safe_serialize: () => new Uint8Array(),
safe_serialize: (_serializedSizeLimit: bigint) => new Uint8Array(),
};

// Setup fetch mock for http://localhost:3001/verify
Expand Down Expand Up @@ -223,7 +222,7 @@ class MockZkProvenList {
this.metadata = metadata;
}

serialize(): Uint8Array {
safe_serialize(_serializedSizeLimit: bigint): Uint8Array {
// Serialize this.items into JSON, then encode as Uint8Array (utf-8)
const json = stringifyWithBigInt({ items: this.items, metadata: this.metadata });
return new TextEncoder().encode(json);
Expand Down
27 changes: 13 additions & 14 deletions packages/sdk/core/encrypt/zkPackProveVerify.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { TFHE_RS_ZK_MAX_BITS, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT } from 'core/consts.js';
import { CofheError, CofheErrorCode } from '../error.js';
import { type EncryptableItem, FheTypes } from '../types.js';
import { toBigIntOrThrow, validateBigIntInRange, toHexString, hexToBytes } from '../utils.js';
import { TFHE_RS_ZK_MAX_BITS, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT } from '../consts';
import { CofheError, CofheErrorCode } from '../error';
import { type EncryptableItem, FheTypes } from '../types';
import { toBigIntOrThrow, validateBigIntInRange, toHexString, hexToBytes } from '../utils';

// ===== TYPES =====

Expand Down Expand Up @@ -90,67 +90,66 @@ export const MAX_UINT64: bigint = 18446744073709551615n; // 2^64 - 1
export const MAX_UINT128: bigint = 340282366920938463463374607431768211455n; // 2^128 - 1
export const MAX_UINT256: bigint = 115792089237316195423570985008687907853269984665640564039457584007913129640319n; // 2^256 - 1
export const MAX_UINT160: bigint = 1461501637330902918203684832716283019655932542975n; // 2^160 - 1
export const MAX_ENCRYPTABLE_BITS: number = 2048;

// ===== CORE FUNCTIONS =====

export const zkPack = (items: EncryptableItem[], builder: ZkCiphertextListBuilder): ZkCiphertextListBuilder => {
let totalBits = 0n;
let totalBits = 0;
for (const item of items) {
switch (item.utype) {
case FheTypes.Bool: {
builder.push_boolean(item.data);
totalBits += 1n;
totalBits += 1;
break;
}
case FheTypes.Uint8: {
const bint = toBigIntOrThrow(item.data);
validateBigIntInRange(bint, MAX_UINT8);
builder.push_u8(parseInt(bint.toString()));
totalBits += 8n;
totalBits += 8;
break;
}
case FheTypes.Uint16: {
const bint = toBigIntOrThrow(item.data);
validateBigIntInRange(bint, MAX_UINT16);
builder.push_u16(parseInt(bint.toString()));
totalBits += 16n;
totalBits += 16;
break;
}
case FheTypes.Uint32: {
const bint = toBigIntOrThrow(item.data);
validateBigIntInRange(bint, MAX_UINT32);
builder.push_u32(parseInt(bint.toString()));
totalBits += 32n;
totalBits += 32;
break;
}
case FheTypes.Uint64: {
const bint = toBigIntOrThrow(item.data);
validateBigIntInRange(bint, MAX_UINT64);
builder.push_u64(bint);
totalBits += 64n;
totalBits += 64;
break;
}
case FheTypes.Uint128: {
const bint = toBigIntOrThrow(item.data);
validateBigIntInRange(bint, MAX_UINT128);
builder.push_u128(bint);
totalBits += 128n;
totalBits += 128;
break;
}
// [U256-DISABLED]
// case FheTypes.Uint256: {
// const bint = toBigIntOrThrow(item.data);
// validateBigIntInRange(bint, MAX_UINT256);
// builder.push_u256(bint);
// totalBits += 256n;
// totalBits += 256;
// break;
// }
case FheTypes.Uint160: {
const bint = toBigIntOrThrow(item.data);
validateBigIntInRange(bint, MAX_UINT160);
builder.push_u160(bint);
totalBits += 160n;
totalBits += 160;
break;
}
default: {
Expand Down
3 changes: 2 additions & 1 deletion packages/sdk/core/keyStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
/* eslint-disable no-undef */

import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { TFHE_RS_KEY_VERSION } from './consts.js';
import { createKeysStore, type KeysStore, type KeysStorage } from './keyStore.js';

// Mock the storage module
Expand Down Expand Up @@ -124,7 +125,7 @@ describe('KeyStore', () => {
it('should clear keys storage', async () => {
await keysStorage.clearKeysStorage();

expect(mockStorage.removeItem).toHaveBeenCalledWith('cofhesdk-keys');
expect(mockStorage.removeItem).toHaveBeenCalledWith(`cofhesdk-keys-v${TFHE_RS_KEY_VERSION}`);
});

it('should rehydrate keys store', async () => {
Expand Down
8 changes: 3 additions & 5 deletions packages/sdk/core/keyStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ export type KeysStorage = {
rehydrateKeysStore: () => Promise<void>;
};

function getKeysStoreName(): string {
return `cofhesdk-keys-v${TFHE_RS_KEY_VERSION}`;
}
const KEYSTORE_NAME = `cofhesdk-keys-v${TFHE_RS_KEY_VERSION}`;

function isValidPersistedState(state: unknown): state is KeysStore {
if (state && typeof state === 'object') {
Expand Down Expand Up @@ -99,7 +97,7 @@ export function createKeysStore(storage: IStorage | null): KeysStorage {

const clearKeysStorage = async () => {
if (storage) {
await storage.removeItem(getKeysStoreName());
await storage.removeItem(KEYSTORE_NAME);
}
// If no storage, this is a no-op
};
Expand Down Expand Up @@ -130,7 +128,7 @@ function createStoreWithPersit(storage: IStorage) {
onRehydrateStorage: () => (_state?, _error?) => {
if (_error) throw new Error(`onRehydrateStorage: Error rehydrating keys store: ${_error}`);
},
name: getKeysStoreName(),
name: KEYSTORE_NAME,
storage: createJSONStorage(() => storage),
merge: (persistedState, currentState) => {
const persisted = isValidPersistedState(persistedState) ? persistedState : DEFAULT_KEYS_STORE;
Expand Down
1 change: 0 additions & 1 deletion packages/sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"name": "@cofhe/sdk",
"version": "0.4.0",
"hello": "world",
"type": "module",
"description": "SDK for Fhenix COFHE coprocessor interaction",
"main": "./dist/core.cjs",
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/web/zkProve.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
/// <reference lib="webworker" />
/* eslint-disable no-undef */

import { TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT } from 'core/consts.js';
import { TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT } from '../core/consts';
import type { ZkProveWorkerRequest, ZkProveWorkerResponse } from '../core/encrypt/zkPackProveVerify.js';

// TFHE module (will be initialized on first use)
Expand Down
Loading