Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

build: rebuild wasm tutorial app in next.js #6

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
31 changes: 31 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: Integration Tests
on:
push:
branches: ['main']
pull_request:
branches: ['main']
paths-ignore:
- 'README.md'
jobs:
ts-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Use pnpm 8
uses: pnpm/action-setup@v2
with:
version: 8
- name: Use Node.js 18.12.1
uses: actions/setup-node@v3
with:
node-version: '18.12.1'
cache: 'pnpm'
- name: Run linter
run: pnpm run lint
- name: Install dependencies and run wasm tests
run: |
pnpm install --no-frozen-lockfile
NEXT_PUBLIC_REACT_APP_ENTRY_POINT=test pnpm run build
env:
CI: false
NODE_ENV: development
37 changes: 37 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts

DS_Store
443 changes: 19 additions & 424 deletions README.md

Large diffs are not rendered by default.

82 changes: 82 additions & 0 deletions app/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
'use client'
import React, { useEffect, useState } from 'react'

import init from '../pkg/ezkl'

import ElgamalRandomVar from './components/ElgamalRandomVar'
import ElgamalEncrypt from './components/ElgamalEncrypt'
import ElgamalDecrypt from './components/ElgamalDecrypt'
import GenProof from './components/GenProof'
import Verify from './components/Verify'
import Hash from './components/Hash'

interface Files {
[key: string]: File | null
}

export default function Home() {
const [files, setFiles] = useState<Files>({})

useEffect(() => {
async function run() {
// Initialize the WASM module
await init()
}
run()
})

const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const id = event.target.id
const file = event.target.files?.item(0) || null
setFiles((prevFiles) => ({ ...prevFiles, [id]: file }))
}

return (
<div className='App'>
<ElgamalRandomVar/>

<ElgamalEncrypt
files={{
pk: files['elgamal_pk'],
message: files['elgamal_message'],
r: files['elgamal_r']
}}
handleFileChange={handleFileChange}
/>

<ElgamalDecrypt
files={{
sk: files['elgamal_sk'],
cipher: files['elgamal_cipher']
}}
handleFileChange={handleFileChange}
/>

<GenProof
files={{
data: files['data_prove'],
pk: files['pk_prove'],
model: files['model_ser_prove'],
circuitSettings: files['circuit_settings_ser_prove'],
srs: files['srs_ser_prove'],
}}
handleFileChange={handleFileChange}
/>

<Verify
files={{
proof: files['proof_js'],
vk: files['vk'],
circuitSettings: files['circuit_settings_ser_verify'],
srs: files['srs_ser_verify'],
}}
handleFileChange={handleFileChange}
/>

<Hash
message={files['message_hash']}
handleFileChange={handleFileChange}
/>
</div>
)
}
225 changes: 225 additions & 0 deletions app/Utils.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
import { useEffect, useRef } from 'react'
import {
elgamalGenRandom,
elgamalEncrypt,
elgamalDecrypt,
prove,
poseidonHash,
verify
} from '../pkg/ezkl.js'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'
import JSONBig from 'json-bigint'

export function readUploadedFileAsBuffer(file: File) {
return new Promise<Uint8ClampedArray>((resolve, reject) => {
const reader = new FileReader()

reader.onload = (event) => {
if (event.target && event.target.result instanceof ArrayBuffer) {
resolve(new Uint8ClampedArray(event.target.result))
} else {
reject(new Error('Failed to read file'))
}
}

reader.onerror = (error) => {
reject(new Error('File could not be read: ' + error))
}
reader.readAsArrayBuffer(file)
})
}

interface FileDownloadProps {
fileName: string
buffer: Uint8Array | null
handleDownloadCompleted: () => void
}

export function FileDownload({
fileName,
buffer,
handleDownloadCompleted,
}: FileDownloadProps) {
const linkRef = useRef<HTMLAnchorElement | null>(null)

useEffect(() => {
if (!buffer) {
return
}

const blob = new Blob([buffer], { type: 'application/octet-stream' })
const reader = new FileReader()

// Convert the Blob to a Data URL
reader.readAsDataURL(blob)

reader.onloadend = () => {
const base64data = reader.result

// Use the fetch API to download the file
fetch(base64data as string)
.then((res) => res.blob())
.then((blob) => {
const url = URL.createObjectURL(blob)

if (linkRef.current) {
linkRef.current.href = url
linkRef.current.download = fileName
linkRef.current.click()

// Cleanup
URL.revokeObjectURL(url)

// Notify the parent component that the download operation is complete
handleDownloadCompleted()
}
})
}
}, [buffer, fileName, handleDownloadCompleted])

return <a ref={linkRef} style={{ display: 'none' }} />
}

export function ElgamalZipFileDownload({
fileName,
buffer,
handleDownloadCompleted,
}: FileDownloadProps) {
const linkRef = useRef<HTMLAnchorElement | null>(null)

useEffect(() => {
if (!buffer) {
return
}

const blob = new Blob([buffer], { type: 'application/octet-stream' })
const reader = new FileReader()

reader.onloadend = async () => {
const base64data = reader.result

if (typeof base64data === 'string') {
const elgamalVar = JSONBig.parse(atob(base64data.split(',')[1]))

// Create a new Zip file
var zip = new JSZip()
zip.file('pk.txt', JSONBig.stringify(elgamalVar.pk))
zip.file('r.txt', JSONBig.stringify(elgamalVar.r))
zip.file('sk.txt', JSONBig.stringify(elgamalVar.sk))

// Generate the zip file asynchronously
const content = await zip.generateAsync({type:"blob"})

saveAs(content, fileName)

// Notify the parent component that the download operation is complete
handleDownloadCompleted()
}
}

// Convert the Blob to a Data URL
reader.readAsDataURL(blob)
}, [buffer, fileName, handleDownloadCompleted])

return <a ref={linkRef} style={{ display: 'none' }} />
}

type FileMapping = {
[key: string]: File
}

type FileSerMapping = {
[key: string]: Uint8ClampedArray
}

async function convertFilesToFilesSer<T extends FileMapping>(
files: T,
): Promise<FileSerMapping> {
const fileReadPromises = Object.entries(files).map(async ([key, file]) => {
const fileContent = await readUploadedFileAsBuffer(file)
return { key, fileContent }
})

const fileContents = await Promise.all(fileReadPromises)

const filesSer: FileSerMapping = {}
for (const { key, fileContent } of fileContents) {
filesSer[key] = fileContent
}

return filesSer
}


export async function handleGenProofButton<T extends FileMapping>(
files: T,
): Promise<Uint8Array> {
const result = await convertFilesToFilesSer(files)
return prove(
result['data'],
result['pk'],
result['model'],
result['circuitSettings'],
result['srs'],
)
}

export function handleGenREVButton(): Uint8Array {
const seed = generate256BitSeed()
return elgamalGenRandom(seed)
}

export async function handleGenElgamalEncryptionButton<T extends FileMapping>(
files: T,
): Promise<Uint8Array> {
const result = await convertFilesToFilesSer(files)

return elgamalEncrypt(
result['pk'],
result['message'],
result['r']
)
}

export async function handleGenElgamalDecryptionButton<T extends FileMapping>(
files: T,
): Promise<Uint8Array> {
const result = await convertFilesToFilesSer(files)
return elgamalDecrypt(
result['cipher'],
result['sk']
)
}


export async function handleGenHashButton(message: File): Promise<Uint8Array> {
const message_hash = await readUploadedFileAsBuffer(message)
return poseidonHash(message_hash)
}

export async function handleVerifyButton<T extends FileMapping>(
files: T,
): Promise<boolean> {
const result = await convertFilesToFilesSer(files)
return verify(
result['proof'],
result['vk'],
result['circuitSettings'],
result['srs'],
)
}

function stringToUint8Array(str: string): Uint8Array {
const encoder = new TextEncoder();
const uint8Array = encoder.encode(str);
return uint8Array;
}

function generate256BitSeed(): Uint8ClampedArray {
const uuid = self.crypto.randomUUID();
const buffer = stringToUint8Array(uuid);
let seed = self.crypto.getRandomValues(buffer);
seed = seed.slice(0, 32);
return new Uint8ClampedArray(seed.buffer);
}
Loading
Loading