Skip to content

Commit

Permalink
blind computation example uses update js api
Browse files Browse the repository at this point in the history
  • Loading branch information
oceans404 committed Apr 1, 2024
1 parent e9decec commit c5eb6fe
Show file tree
Hide file tree
Showing 7 changed files with 71 additions and 48 deletions.
4 changes: 0 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,5 @@
"@types/react-syntax-highlighter": "^15",
"husky": "^8.0.1",
"lint-staged": "^13.0.3"
},
"dependencies": {
"@nillion/nillion-client-js-browser": "^0.1.21",
"react-syntax-highlighter": "^15.5.0"
}
}
31 changes: 18 additions & 13 deletions packages/nextjs/app/nillion-compute/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const Home: NextPage = () => {
my_int2: null,
});
const [parties] = useState<string[]>(["Party1"]);
const [outputs] = useState<string[]>(["my_output"]);

// connect to snap
async function handleConnectToSnap() {
Expand Down Expand Up @@ -89,23 +90,27 @@ const Home: NextPage = () => {
) {
if (programId) {
const partyName = parties[0];
await storeSecretsInteger(nillion, nillionClient, secretValue, secretName, programId, partyName).then(
async (store_id: string) => {
console.log("Secret stored at store_id:", store_id);
setStoredSecretsNameToStoreId(prevSecrets => ({
...prevSecrets,
[secretName]: store_id,
}));
},
);
await storeSecretsInteger(
nillion,
nillionClient,
[{ name: secretName, value: secretValue }],
programId,
partyName,
).then(async (store_id: string) => {
console.log("Secret stored at store_id:", store_id);
setStoredSecretsNameToStoreId(prevSecrets => ({
...prevSecrets,
[secretName]: store_id,
}));
});
}
}

// compute on secrets
async function handleCompute() {
if (programId) {
await compute(nillion, nillionClient, Object.values(storedSecretsNameToStoreId), programId).then(result =>
setComputeResult(result),
await compute(nillion, nillionClient, Object.values(storedSecretsNameToStoreId), programId, outputs[0]).then(
result => setComputeResult(result),
);
}
}
Expand Down Expand Up @@ -200,7 +205,7 @@ const Home: NextPage = () => {
{Object.keys(storedSecretsNameToStoreId).map(key => (
<div className="flex-1 px-2" key={key}>
{!!storedSecretsNameToStoreId[key] ? (
<p>
<span>
✅ Stored SecretInteger {key} <br />{" "}
<CopyString str={storedSecretsNameToStoreId[key] || ""} textBefore={`store_id: `} full />
<br />
Expand All @@ -214,7 +219,7 @@ const Home: NextPage = () => {
end={30}
code
/>
</p>
</span>
) : (
<SecretForm
secretName={key}
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"dependencies": {
"@ethersproject/providers": "^5.7.2",
"@heroicons/react": "^2.0.11",
"@nillion/nillion-client-js-browser": "^0.0.9",
"@rainbow-me/rainbowkit": "1.3.5",
"@uniswap/sdk-core": "^4.0.1",
"@uniswap/v2-sdk": "^3.0.1",
Expand All @@ -29,6 +30,7 @@
"react-copy-to-clipboard": "^5.1.0",
"react-dom": "^18.2.0",
"react-hot-toast": "^2.4.0",
"react-syntax-highlighter": "^15.5.0",
"use-debounce": "^8.0.4",
"usehooks-ts": "^2.13.0",
"viem": "1.19.9",
Expand Down
42 changes: 26 additions & 16 deletions packages/nextjs/utils/nillion/compute.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { nillionConfig } from "./nillionConfig";

const bigIntFromByteArray = (byteArray: Uint8Array) => {
let hexString = "0x";
for (let i = byteArray.length - 1; i >= 0; i--) {
hexString += byteArray[i].toString(16).padStart(2, "0");
}
return BigInt(hexString);
};
interface JsInput {
name: string;
value: string;
}

export async function compute(
nillion: any,
nillionClient: any,
store_ids: (string | null)[],
program_id: string,
outputName: string,
computeTimeSecrets: JsInput[] = [],
publicVariables: JsInput[] = [],
): Promise<string> {
try {
// create program bindings with the program id
Expand All @@ -26,28 +26,38 @@ export async function compute(

console.log(program_bindings);
console.log(party_id);

console.log(store_ids);

// all secrets were stored ahead of time, so there
// are no compute time secrets used in this computation
// compute_time_secrets is an empty object of secrets
// create a compute time secrets object
const compute_time_secrets = new nillion.Secrets();
console.log(compute_time_secrets);

// iterate through computeTimeSecrets, inserting each into the compute_time_secrets object
for (const compute_secret of computeTimeSecrets) {
const newComputeTimeSecret = nillion.Secret.new_integer(compute_secret.value.toString());
compute_time_secrets.insert(compute_secret.name, newComputeTimeSecret);
}

// create a public variables object
const public_variables = new nillion.PublicVariables();

// iterate through computeTimeSecrets, inserting each into the compute_time_secrets object
for (const public_variable of publicVariables) {
const newPublicVariable = nillion.Secret.new_integer(public_variable.value.toString());
compute_time_secrets.insert(public_variable.name, newPublicVariable);
}

// compute
const compute_result_uuid = await nillionClient.compute(
nillionConfig.cluster_id,
program_bindings,
store_ids,
compute_time_secrets,
public_variables,
);

const compute_result = await nillionClient.compute_result(compute_result_uuid);

// transform bytearray to bigint and get compute result value
const decoded_compute_result = bigIntFromByteArray(compute_result.value);
return decoded_compute_result.toString();
const result = compute_result[outputName].toString();
return result;
} catch (error: any) {
console.log("error", error);
return "error";
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/utils/nillion/nillionClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,15 @@ export const initializeNillionClient = (
nodekey: any,
websockets: string[],
payments_config: PaymentsConfig,
): nillion.NillionClient => new nillion.NillionClient(userkey, nodekey, websockets, false, payments_config);
): nillion.NillionClient => new nillion.NillionClient(userkey, nodekey, websockets, payments_config);

export const getNillionClient = async (userKey: string) => {
await nillion.default();
const nillionUserKey = nillion.UserKey.from_base58(userKey);
// temporary fix for an issue where nodekey cannot be reused between calls
const nodeKey = nillion.NodeKey.from_seed(`scaffold-eth-${Math.floor(Math.random() * 10000)}`);
console.log(nillionConfig);

const client = initializeNillionClient(
nillionUserKey,
nodeKey,
Expand Down
24 changes: 16 additions & 8 deletions packages/nextjs/utils/nillion/storeSecretsInteger.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,33 @@
import { nillionConfig } from "./nillionConfig";

interface JsInput {
name: string;
value: string;
}

export async function storeSecretsInteger(
nillion: any,
nillionClient: any,
secretValue: string,
secretName: string,
secretsToStore: JsInput[],
program_id: string,
party_name: string,
): Promise<string> {
try {
// create secrets object
const secrets = new nillion.Secrets();
// encode integer for storage
const encodedIntegerSecret = await nillion.encode_signed_integer_secret(secretName, {
as_string: secretValue.toString(),
});
// insert 1 or more encoded SecretInteger(s) into secrets object
await secrets.insert(encodedIntegerSecret);

// iterate through secretsToStore, inserting each into the secrets object
for (const secret of secretsToStore) {
// create new SecretInteger with value cast to string
const newSecret = nillion.Secret.new_integer(secret.value.toString());

// insert the SecretInteger into secrets object
secrets.insert(secret.name, newSecret);
}

// create program bindings for secret so it can be used in a specific program
const secret_program_bindings = new nillion.ProgramBindings(program_id);

// set the input party to the bindings to specify which party will provide the secret
const party_id = await nillionClient.party_id();
secret_program_bindings.add_input_party(party_name, party_id);
Expand Down
12 changes: 6 additions & 6 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1155,10 +1155,10 @@ __metadata:
languageName: node
linkType: hard

"@nillion/nillion-client-js-browser@npm:^0.1.21":
version: 0.1.21
resolution: "@nillion/nillion-client-js-browser@npm:0.1.21"
checksum: 31952e531b34751e313774343439ffbb34d121c2a34cc7e4f28d9fecab5b9f045a615b4131386e05994bbb039ee510fe3763629c57bdd7cbc2976987f1fcff25
"@nillion/nillion-client-js-browser@npm:^0.0.9":
version: 0.0.9
resolution: "@nillion/nillion-client-js-browser@npm:0.0.9"
checksum: 445feeb669823be209cd16892f0af41bcedee5789953d8fb29d8fa69701c1ea542b021537d9b4a4bc63f27d246390e872d63fb72ae50307b42c8b619ee641cf1
languageName: node
linkType: hard

Expand Down Expand Up @@ -1931,6 +1931,7 @@ __metadata:
dependencies:
"@ethersproject/providers": ^5.7.2
"@heroicons/react": ^2.0.11
"@nillion/nillion-client-js-browser": ^0.0.9
"@rainbow-me/rainbowkit": 1.3.5
"@trivago/prettier-plugin-sort-imports": ^4.1.1
"@types/node": ^17.0.35
Expand All @@ -1957,6 +1958,7 @@ __metadata:
react-copy-to-clipboard: ^5.1.0
react-dom: ^18.2.0
react-hot-toast: ^2.4.0
react-syntax-highlighter: ^15.5.0
tailwindcss: ^3.3.3
type-fest: ^4.6.0
typescript: ^5.1.6
Expand Down Expand Up @@ -11717,11 +11719,9 @@ __metadata:
version: 0.0.0-use.local
resolution: "se-2@workspace:."
dependencies:
"@nillion/nillion-client-js-browser": ^0.1.21
"@types/react-syntax-highlighter": ^15
husky: ^8.0.1
lint-staged: ^13.0.3
react-syntax-highlighter: ^15.5.0
languageName: unknown
linkType: soft

Expand Down

0 comments on commit c5eb6fe

Please sign in to comment.