feat: interactive prover in TypeScript

This commit is contained in:
Hendrik Eeckhaut
2024-09-05 21:01:05 +02:00
parent a5a1f7ac7c
commit 7551015519
22 changed files with 825 additions and 408 deletions

View File

@@ -1,8 +1,6 @@
{
"rust-analyzer.linkedProjects": [
"wasm/prover/Cargo.toml",
"interactive-demo/verifier-rs/Cargo.toml",
"interactive-demo/prover-rs/Cargo.toml"
],
"rust-analyzer.cargo.target": "wasm32-unknown-unknown"
}
}

View File

@@ -0,0 +1,29 @@
# Interactive Verifier: Verifying Data from an API in Rust
This example demonstrates how to use TLSNotary in a simple interactive session between a Prover and a Verifier. It involves the Verifier first verifying the MPC-TLS session and then confirming the correctness of the data.
In this example, the Verifier connects to <https://swapi.dev> and proves data to the verifier.
# Run example on a single computer
You can run both the verifier and prover with:
```sh
cargo run -release --example interactive_networked
```
# Run example on two different computers
To run the example on two different computers, start the verifier first on machine 1:
```sh
cd verifier
cargo run --release
```
Note: make sure port `9816` is open if you run a firewall.
Next, on machine 2:
1. Update the (ip address of the verifier on machine 1)[file:./prover/src/main.rs]
2. Run:
```sh
cd prover
cargo run --release
```

View File

@@ -0,0 +1,38 @@
# Test Rust Prover
1. Start the verifier:
```bash
cd verifier-rs; cargo run --release
```
2. Run the prover:
```bash
cd prover-rs; cargo run --release
```
# Test Browser Prover
1. Start the verifier:
```bash
cd verifier-rs; cargo run --release
```
2. Since a web browser doesn't have the ability to make TCP connection, we need to use a websocket proxy server to access <swapi.dev>.
```bash
cargo install wstcp
wstcp --bind-addr 127.0.0.1:55688 swapi.dev:443
```
3. Run the prover
1. Build tlsn-js
```bash
cd ..
npm i
npm run build
npm link
```
2. Build demo prover-ts
```bash
cd prover-ts
npm i
npm link
npm run dev
```
3. Open <http://localhost:8080/> and click **Start Prover**

76
interactive-demo/main.rs Normal file
View File

@@ -0,0 +1,76 @@
use std::{
io::{BufRead, BufReader},
path::Path,
process::{Child, Command, Stdio},
thread,
time::Duration,
};
fn main() -> std::io::Result<()> {
let examples_folder = Path::new(env!("CARGO_MANIFEST_DIR"));
let verifier_dir = examples_folder.join(Path::new("interactive-networked/verifier"));
let prover_dir = examples_folder.join(Path::new("interactive-networked/prover"));
const SLEEP_TIME_SECS: u64 = 2; // allow the verifier some extra seconds to start and stop
// Run the verifier in the background
println!("Starting the verifier...");
let mut verifier = run(&verifier_dir, "cargo", &["run", "--release"], "VERIFIER")?;
// Allow the verifier some time to start
thread::sleep(Duration::from_secs(SLEEP_TIME_SECS));
// Run the prover in the foreground
println!("Starting the prover...");
let prover_status = run(&prover_dir, "cargo", &["run", "--release"], "PROVER")?.wait()?;
if prover_status.success() {
println!("Prover finished successfully.");
} else {
eprintln!("Prover finished with errors.");
}
// Allow the verifier some time to finish the verification
thread::sleep(Duration::from_secs(SLEEP_TIME_SECS));
// Stop the verifier after the prover finishes
println!("Stopping the verifier...");
verifier.kill()?;
println!("Verifier stopped. Script finished.");
Ok(())
}
fn run(working_dir: &Path, cmd: &str, args: &[&str], prefix: &str) -> std::io::Result<Child> {
let mut process = Command::new(cmd)
.args(args)
.current_dir(working_dir)
.stdout(Stdio::piped()) // Capture stdout
.stderr(Stdio::piped()) // Capture stderr
.spawn()?;
// Helper function to handle reading from a stream and prefixing its output
fn handle_output<R: std::io::Read + Send + 'static, F>(stream: R, prefix: String, print_fn: F)
where
F: Fn(String) + Send + 'static,
{
thread::spawn(move || {
BufReader::new(stream)
.lines()
.map_while(Result::ok)
.for_each(|line| print_fn(format!("[{}] {}", prefix, line)));
});
}
// Prefix stdout
if let Some(stdout) = process.stdout.take() {
handle_output(stdout, prefix.to_string(), |line| println!("{}", line));
}
// Prefix stderr
if let Some(stderr) = process.stderr.take() {
handle_output(stderr, prefix.to_string(), |line| eprintln!("{}", line));
}
Ok(process)
}

View File

@@ -1,5 +1,5 @@
[package]
name = "prover"
name = "interactive-networked-prover"
version = "0.1.0"
edition = "2021"
@@ -25,5 +25,6 @@ tracing-subscriber = { version ="0.3.18", features = ["env-filter"] }
uuid = { version = "1.4.1", features = ["v4", "fast-rng"] }
ws_stream_tungstenite = { version = "0.13", features = ["tokio_io"] }
tlsn-core = { git = "https://github.com/tlsnotary/tlsn.git", tag = "v0.1.0-alpha.6", package = "tlsn-core" }
tlsn-prover = { git = "https://github.com/tlsnotary/tlsn.git", tag = "v0.1.0-alpha.6", package = "tlsn-prover" }
tlsn-core = { git = "https://github.com/tlsnotary/tlsn.git", tag = "v0.1.0-alpha.7", package = "tlsn-core" }
tlsn-prover = { git = "https://github.com/tlsnotary/tlsn.git", tag = "v0.1.0-alpha.7", package = "tlsn-prover" }
tlsn-common = { git = "https://github.com/tlsnotary/tlsn.git", tag = "v0.1.0-alpha.7", package = "tlsn-common" }

View File

@@ -3,24 +3,27 @@ use http_body_util::Empty;
use hyper::{body::Bytes, Request, StatusCode, Uri};
use hyper_util::rt::TokioIo;
use regex::Regex;
use tlsn_core::Direction;
use tlsn_prover::tls::{state::Prove, Prover, ProverConfig};
use tlsn_common::config::ProtocolConfig;
use tlsn_core::transcript::Idx;
use tlsn_prover::{state::Prove, Prover, ProverConfig};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_util::compat::{FuturesAsyncReadCompatExt, TokioAsyncReadCompatExt};
use tracing::{debug, info};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
use ws_stream_tungstenite::WsStream;
const TRACING_FILTER: &str = "DEBUG";
const TRACING_FILTER: &str = "INFO";
const VERIFIER_HOST: &str = "localhost";
const VERIFIER_PORT: u16 = 9816;
// Maximum number of bytes that can be sent from prover to server
const MAX_SENT_DATA: usize = 1 << 12;
// Maximum number of bytes that can be received by prover from server
const MAX_RECV_DATA: usize = 1 << 14;
const SECRET: &str = "TLSNotary's private key 🤡";
/// Make sure the following url's domain is the same as SERVER_DOMAIN on the verifier side
const SERVER_URL: &str = "https://swapi.dev/api/people/1";
/// Make sure this is the same on the verifier side
const VERIFICATION_SESSION_ID: &str = "interactive-verifier-demo";
#[tokio::main]
async fn main() {
@@ -29,21 +32,10 @@ async fn main() {
.with(tracing_subscriber::fmt::layer())
.init();
run_prover(
VERIFIER_HOST,
VERIFIER_PORT,
SERVER_URL,
VERIFICATION_SESSION_ID,
)
.await;
run_prover(VERIFIER_HOST, VERIFIER_PORT, SERVER_URL).await;
}
async fn run_prover(
verifier_host: &str,
verifier_port: u16,
server_uri: &str,
verification_session_id: &str,
) {
async fn run_prover(verifier_host: &str, verifier_port: u16, server_uri: &str) {
info!("Sending websocket request...");
let request = http::Request::builder()
.uri(format!("ws://{}:{}/verify", verifier_host, verifier_port,))
@@ -62,15 +54,11 @@ async fn run_prover(
info!("Websocket connection established!");
let verifier_ws_socket = WsStream::new(verifier_ws_stream);
prover(verifier_ws_socket, server_uri, verification_session_id).await;
prover(verifier_ws_socket, server_uri).await;
info!("Proving is successful!");
}
async fn prover<T: AsyncWrite + AsyncRead + Send + Unpin + 'static>(
verifier_socket: T,
uri: &str,
id: &str,
) {
async fn prover<T: AsyncWrite + AsyncRead + Send + Unpin + 'static>(verifier_socket: T, uri: &str) {
debug!("Starting proving...");
let uri = uri.parse::<Uri>().unwrap();
@@ -79,10 +67,18 @@ async fn prover<T: AsyncWrite + AsyncRead + Send + Unpin + 'static>(
let server_port = uri.port_u16().unwrap_or(443);
// Create prover and connect to verifier.
//
// Perform the setup phase with the verifier.
let prover = Prover::new(
ProverConfig::builder()
.id(id)
.server_dns(server_domain)
.server_name(server_domain)
.protocol_config(
ProtocolConfig::builder()
.max_sent_data(MAX_SENT_DATA)
.max_recv_data(MAX_RECV_DATA)
.build()
.unwrap(),
)
.build()
.unwrap(),
)
@@ -91,13 +87,18 @@ async fn prover<T: AsyncWrite + AsyncRead + Send + Unpin + 'static>(
.unwrap();
// Connect to TLS Server.
info!("Connect to TLS Server");
let tls_client_socket = tokio::net::TcpStream::connect((server_domain, server_port))
.await
.unwrap();
// Pass server connection into the prover.
let (mpc_tls_connection, prover_fut) =
prover.connect(tls_client_socket.compat()).await.unwrap();
// Wrap the connection in a TokioIo compatibility layer to use it with hyper.
let mpc_tls_connection = TokioIo::new(mpc_tls_connection.compat());
// Spawn the Prover to run in the background.
let prover_task = tokio::spawn(prover_fut);
// MPC-TLS Handshake.
@@ -123,55 +124,49 @@ async fn prover<T: AsyncWrite + AsyncRead + Send + Unpin + 'static>(
debug!("TLS response: {:?}", response);
assert!(response.status() == StatusCode::OK);
// Close TLS Connection.
// let tls_connection = connection_task.await.unwrap().unwrap().io.into_inner();
// debug!("TLS connection: {:?}", tls_connection);
// tls_connection.compat().close().await.unwrap();
// info!("TLS Connection closed");
// Create proof for the Verifier.
info!("Create proof for the Verifier");
let mut prover = prover_task.await.unwrap().unwrap().start_prove();
redact_and_reveal_sent_data(&mut prover);
redact_and_reveal_received_data(&mut prover);
prover.prove().await.unwrap();
let idx_sent = redact_and_reveal_sent_data(&mut prover);
let idx_recv = redact_and_reveal_received_data(&mut prover);
// Reveal parts of the transcript
prover.prove_transcript(idx_sent, idx_recv).await.unwrap();
// Finalize.
info!("Finalize prover");
prover.finalize().await.unwrap()
}
/// Redacts and reveals received data to the verifier.
fn redact_and_reveal_received_data(prover: &mut Prover<Prove>) {
let recv_transcript_len = prover.recv_transcript().data().len();
fn redact_and_reveal_received_data(prover: &mut Prover<Prove>) -> Idx {
let recv_transcript = prover.transcript().received();
let recv_transcript_len = recv_transcript.len();
// Get the homeworld from the received data.
let received_string = String::from_utf8(prover.recv_transcript().data().to_vec()).unwrap();
let received_string = String::from_utf8(recv_transcript.to_vec()).unwrap();
debug!("Received data: {}", received_string);
let re = Regex::new(r#""homeworld"\s?:\s?"(.*?)""#).unwrap();
let homeworld_match = re.captures(&received_string).unwrap().get(1).unwrap();
// Reveal everything except for the homeworld.
_ = prover.reveal(0..homeworld_match.start(), Direction::Received);
_ = prover.reveal(
homeworld_match.end()..recv_transcript_len,
Direction::Received,
);
let start = homeworld_match.start();
let end = homeworld_match.end();
Idx::new([0..start, end..recv_transcript_len])
}
/// Redacts and reveals sent data to the verifier.
fn redact_and_reveal_sent_data(prover: &mut Prover<Prove>) {
let sent_transcript_len = prover.sent_transcript().data().len();
fn redact_and_reveal_sent_data(prover: &mut Prover<Prove>) -> Idx {
let sent_transcript = prover.transcript().sent();
let sent_transcript_len = sent_transcript.len();
let sent_string = String::from_utf8(prover.sent_transcript().data().to_vec()).unwrap();
let sent_string: String = String::from_utf8(sent_transcript.to_vec()).unwrap();
let secret_start = sent_string.find(SECRET).unwrap();
debug!("Send data: {}", sent_string);
// Reveal everything except for the SECRET.
_ = prover.reveal(0..secret_start, Direction::Sent);
_ = prover.reveal(
Idx::new([
0..secret_start,
secret_start + SECRET.len()..sent_transcript_len,
Direction::Sent,
);
])
}

View File

@@ -1,20 +0,0 @@
TODO
1. Start Verifier
2. Start websocket proxy
3. Start app
Since a web browser doesn't have the ability to make TCP connection, we need to use a websocket proxy server.
To run your own websockify proxy **locally**, run:
```sh
git clone https://github.com/novnc/websockify && cd websockify
./docker/build.sh
docker run -it --rm -p 55688:80 novnc/websockify 80 swapi.dev:443
```
Run a local websocket proxy
cargo install wstcp
wstcp $(dig swapi.dev +short):443 --bind-addr 127.0.0.1:55688

View File

@@ -1,9 +1,15 @@
import React, { ReactElement, useCallback, useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { interactive_prove, prove, verify } from 'tlsn-js';
import { Proof } from 'tlsn-js/build/types';
import * as Comlink from 'comlink';
import { Watch } from 'react-loader-spinner';
import {
Prover as TProver
} from 'tlsn-js';
const { init, Prover, NotarizedSession, TlsProof }: any = Comlink.wrap(
new Worker(new URL('./worker.ts', import.meta.url)),
);
import { Method } from 'tlsn-js/wasm/pkg';
const container = document.getElementById('root');
const root = createRoot(container!);
@@ -12,21 +18,76 @@ root.render(<App />);
function App(): ReactElement {
const [processing, setProcessing] = useState(false);
const [result, setResult] = useState<String | null>(null);
const [proofHex, setProofHex] = useState<null | string>(null);
const onClick = useCallback(async () => {
setProcessing(true);
const result = await interactive_prove('https://swapi.dev/api/people/1', {
headers: {
RTT: '125',
'Sec-GPC': '1',
},
id: "interactive-verifier-demo",
verifierProxyUrl: 'ws://localhost:9816',
websocketProxyUrl: 'wss://notary.pse.dev/proxy?token=swapi.dev', //'ws://localhost:55688',
});
setResult(result);
setProcessing(false);
let url = "https://swapi.dev/api/people/1";
let method: Method = 'GET';
let headers = {
'secret': "TLSNotary's private key"
};
let body = null;
// let websocketProxyUrl = 'wss://notary.pse.dev/proxy?token=swapi.dev';
let websocketProxyUrl = 'ws://localhost:55688';
let verifierProxyUrl = 'ws://localhost:9816/verify';
const hostname = new URL(url).hostname;
console.time('setup');
await init({ loggingLevel: 'Debug' });
console.log("Setting up Prover for", hostname)
const prover = await new Prover({ serverDns: hostname }) as TProver;
console.log("Setting up Prover: 1/2")
await prover.setup(verifierProxyUrl);
console.log("Setting up Prover: done")
console.timeEnd('setup');
console.time('request');
console.log("Sending request to proxy")
const resp = await prover.sendRequest(
`${websocketProxyUrl}?token=${hostname}`, { url, method, headers, body, }
);
console.log("Response:", resp);
console.log("Wait for transcript")
const transcript = await prover.transcript();
console.log("Transcript:", transcript);
console.timeEnd('request');
console.time('reveal');
const reveal = {
sent: [
transcript.ranges.sent.info!,
transcript.ranges.sent.headers!['connection'],
transcript.ranges.sent.headers!['host'],
...transcript.ranges.sent.lineBreaks,
],
recv: [
transcript.ranges.recv.info,
transcript.ranges.recv.headers['server'],
transcript.ranges.recv.headers['date'],
transcript.ranges.recv.json!['name'],
transcript.ranges.recv.json!['eye_color'],
transcript.ranges.recv.json!['gender'],
...transcript.ranges.recv.lineBreaks,
],
};
console.log("Start reveal:", reveal);
await prover.reveal(reveal);
console.timeEnd('reveal');
console.log("Ready");
console.log("Unredacted data:", { sent: transcript.sent, received: transcript.recv })
setResult("Unredacted data successfully revealed to Verifier.");
setProcessing(false);
}, [setResult, setProcessing]);
return (
@@ -34,7 +95,9 @@ function App(): ReactElement {
<h1>TLSNotary interactive prover demo</h1>
<div>
Before clicking the start button, make sure the <i>interactive verifier</i> is running: <pre>cd interactive-demo/verifier; cargo run --release</pre>
You also need a websocket proxy.
</div>
<br />
<button onClick={!processing ? onClick : undefined} disabled={processing}>
Start Prover

View File

@@ -12,7 +12,7 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-loader-spinner": "^6.1.6",
"tlsn-js": "../../../tlsn-js"
"tlsn-js": "file:../.."
},
"devDependencies": {
"@types/react": "^18.0.26",

View File

@@ -1,7 +1,11 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
@@ -15,5 +19,8 @@
"noEmit": false,
"jsx": "react"
},
"include": ["app.tsx"]
"include": [
"app.tsx",
"worker.ts"
]
}

View File

@@ -0,0 +1,9 @@
import * as Comlink from 'comlink';
import init, { Prover, NotarizedSession, TlsProof } from 'tlsn-js';
Comlink.expose({
init,
Prover,
NotarizedSession,
TlsProof,
});

View File

@@ -1,5 +1,5 @@
[package]
name = "verifier"
name = "interactive-networked-verifier"
version = "0.1.0"
edition = "2021"
@@ -32,5 +32,7 @@ tracing = "0.1.40"
tracing-subscriber = { version ="0.3.18", features = ["env-filter"] }
ws_stream_tungstenite = { version = "0.13", features = ["tokio_io"] }
tlsn-core = { git = "https://github.com/tlsnotary/tlsn.git", tag = "v0.1.0-alpha.6", package = "tlsn-core" }
tlsn-verifier = { git = "https://github.com/tlsnotary/tlsn.git", tag = "v0.1.0-alpha.6", package = "tlsn-verifier" }
tlsn-core = { git = "https://github.com/tlsnotary/tlsn.git", tag = "v0.1.0-alpha.7", package = "tlsn-core" }
tlsn-verifier = { git = "https://github.com/tlsnotary/tlsn.git", tag = "v0.1.0-alpha.7", package = "tlsn-verifier" }
tlsn-common = { git = "https://github.com/tlsnotary/tlsn.git", tag = "v0.1.0-alpha.7", package = "tlsn-common" }
tower-util = "0.3.1"

View File

@@ -12,7 +12,3 @@ cargo run --release
## WebSocket APIs
### /verify
To perform verification via websocket, i.e. `ws://localhost:9816/verify`
## Design Choices
### WebSocket
Refer to https://github.com/tlsnotary/tlsn/tree/main/notary-server#websocket

View File

@@ -882,7 +882,8 @@ mod tests {
use super::*;
use axum::{body::Body, routing::get, Router};
use http::{Request, Version};
use tower::ServiceExt;
// NOTARY_MODIFICATION: use tower_util instead of tower to make clippy happy
use tower_util::ServiceExt;
#[tokio::test]
async fn rejects_http_1_0_requests() {

View File

@@ -12,8 +12,9 @@ use std::{
net::{IpAddr, SocketAddr},
sync::Arc,
};
use tlsn_core::proof::SessionInfo;
use tlsn_verifier::tls::{Verifier, VerifierConfig};
use tlsn_common::config::ProtocolConfigValidator;
use tlsn_verifier::{SessionInfo, Verifier, VerifierConfig};
use tokio::{
io::{AsyncRead, AsyncWrite},
net::TcpListener,
@@ -25,18 +26,21 @@ use ws_stream_tungstenite::WsStream;
mod axum_websocket;
// Maximum number of bytes that can be sent from prover to server
const MAX_SENT_DATA: usize = 1 << 12;
// Maximum number of bytes that can be received by prover from server
const MAX_RECV_DATA: usize = 1 << 14;
/// Global data that needs to be shared with the axum handlers
#[derive(Clone, Debug)]
struct VerifierGlobals {
pub server_domain: String,
pub verification_session_id: String,
}
pub async fn run_server(
verifier_host: &str,
verifier_port: u16,
server_domain: &str,
verification_session_id: &str,
) -> Result<(), eyre::ErrReport> {
let verifier_address = SocketAddr::new(
IpAddr::V4(verifier_host.parse().map_err(|err| {
@@ -55,7 +59,6 @@ pub async fn run_server(
.route("/verify", get(ws_handler))
.with_state(VerifierGlobals {
server_domain: server_domain.to_string(),
verification_session_id: verification_session_id.to_string(),
});
loop {
@@ -101,13 +104,7 @@ async fn handle_socket(socket: WebSocket, verifier_globals: VerifierGlobals) {
debug!("Upgraded to websocket connection");
let stream = WsStream::new(socket.into_inner());
match verifier(
stream,
&verifier_globals.verification_session_id,
&verifier_globals.server_domain,
)
.await
{
match verifier(stream, &verifier_globals.server_domain).await {
Ok((sent, received, _session_info)) => {
info!("Successfully verified {}", &verifier_globals.server_domain);
info!("Verified sent data:\n{}", sent,);
@@ -121,36 +118,41 @@ async fn handle_socket(socket: WebSocket, verifier_globals: VerifierGlobals) {
async fn verifier<T: AsyncWrite + AsyncRead + Send + Unpin + 'static>(
socket: T,
verification_session_id: &str,
server_domain: &str,
) -> Result<(String, String, SessionInfo), eyre::ErrReport> {
debug!("Starting verification...");
// Setup Verifier.
let config_validator = ProtocolConfigValidator::builder()
.max_sent_data(MAX_SENT_DATA)
.max_recv_data(MAX_RECV_DATA)
.build()
.unwrap();
let verifier_config = VerifierConfig::builder()
.id(verification_session_id)
.build()?;
.protocol_config_validator(config_validator)
.build()
.unwrap();
let verifier = Verifier::new(verifier_config);
// Verify MPC-TLS and wait for (redacted) data.
debug!("Starting MPC-TLS verification...");
let (sent, received, session_info) = verifier
.verify(socket.compat())
.await
.map_err(|err| eyre!("Verification failed: {err}"))?;
// Verify MPC-TLS and wait for (redacted) data.
let (mut partial_transcript, session_info) = verifier.verify(socket.compat()).await.unwrap();
partial_transcript.set_unauthed(0);
// Check sent data: check host.
debug!("Starting sent data verification...");
let sent_data = String::from_utf8(sent.data().to_vec())
.map_err(|err| eyre!("Failed to parse sent data: {err}"))?;
let sent = partial_transcript.sent_unsafe().to_vec();
let sent_data = String::from_utf8(sent.clone()).expect("Verifier expected sent data");
sent_data
.find(server_domain)
.ok_or_else(|| eyre!("Verification failed: Expected host {}", server_domain))?;
// Check received data: check json and version number.
debug!("Starting received data verification...");
let response = String::from_utf8(received.data().to_vec())
.map_err(|err| eyre!("Failed to parse received data: {err}"))?;
let received = partial_transcript.received_unsafe().to_vec();
let response = String::from_utf8(received.clone()).expect("Verifier expected received data");
debug!("Received data: {:?}", response);
response
.find("eye_color")
@@ -160,8 +162,8 @@ async fn verifier<T: AsyncWrite + AsyncRead + Send + Unpin + 'static>(
return Err(eyre!("Verification failed: server name mismatches"));
}
let sent_string = bytes_to_redacted_string(sent.data())?;
let received_string = bytes_to_redacted_string(received.data())?;
let sent_string = bytes_to_redacted_string(&sent)?;
let received_string = bytes_to_redacted_string(&received)?;
Ok((sent_string, received_string, session_info))
}

View File

@@ -1,15 +1,13 @@
use interactive_networked_verifier::run_server;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
use verifier::run_server;
const TRACING_FILTER: &str = "DEBUG";
const TRACING_FILTER: &str = "INFO";
const VERIFIER_HOST: &str = "0.0.0.0";
const VERIFIER_PORT: u16 = 9816;
/// Make sure the following domain is the same in SERVER_URL on the prover side
const SERVER_DOMAIN: &str = "swapi.dev";
/// Make sure this is the same on the prover side
const VERIFICATION_SESSION_ID: &str = "interactive-verifier-demo";
#[tokio::main]
async fn main() -> Result<(), eyre::ErrReport> {
@@ -18,13 +16,7 @@ async fn main() -> Result<(), eyre::ErrReport> {
.with(tracing_subscriber::fmt::layer())
.init();
run_server(
VERIFIER_HOST,
VERIFIER_PORT,
SERVER_DOMAIN,
VERIFICATION_SESSION_ID,
)
.await?;
run_server(VERIFIER_HOST, VERIFIER_PORT, SERVER_DOMAIN).await?;
Ok(())
}

View File

@@ -47,9 +47,9 @@ export default async function init(config?: {
});
// 6422528 ~= 6.12 mb
debug('res.memory=', res.memory);
debug('res.memory.buffer.length=', res.memory.buffer.byteLength);
debug('DEBUG', 'initialize thread pool');
debug('res.memory', res.memory);
debug('res.memory.buffer.length', res.memory.buffer.byteLength);
debug('initialize thread pool');
await initThreadPool(hardwareConcurrency);
debug('initialized thread pool');
@@ -206,6 +206,10 @@ export class Prover {
const notarizedSession = await this.#prover.notarize(commit);
return arrayToHex(notarizedSession.serialize());
}
async reveal(reveal: Reveal): Promise<void> {
await this.#prover.reveal(reveal);
}
}
export class Verifier {

View File

@@ -1,15 +1,16 @@
{
"name": "tlsn-wasm",
"type": "module",
"version": "0.1.0-alpha.6",
"version": "0.1.0-alpha.8-pre",
"files": [
"tlsn_wasm_bg.wasm",
"tlsn_wasm.js",
"tlsn_wasm.d.ts"
"tlsn_wasm.d.ts",
"snippets/"
],
"main": "tlsn_wasm.js",
"types": "tlsn_wasm.d.ts",
"sideEffects": [
"./snippets/*"
]
}
}

View File

@@ -6,6 +6,14 @@
*/
export function init_logging(config?: LoggingConfig): void;
/**
* Builds a presentation.
* @param {Attestation} attestation
* @param {Secrets} secrets
* @param {Reveal} reveal
* @returns {Presentation}
*/
export function build_presentation(attestation: Attestation, secrets: Secrets, reveal: Reveal): Presentation;
/**
* @param {number} num_threads
* @returns {Promise<any>}
*/
@@ -30,11 +38,31 @@ export interface HttpResponse {
headers: [string, number[]][];
}
export type TlsVersion = "V1_2" | "V1_3";
export interface TranscriptLength {
sent: number;
recv: number;
}
export interface ConnectionInfo {
time: number;
version: TlsVersion;
transcript_length: TranscriptLength;
}
export interface Transcript {
sent: number[];
recv: number[];
}
export interface PartialTranscript {
sent: number[];
sent_authed: { start: number; end: number }[];
recv: number[];
recv_authed: { start: number; end: number }[];
}
export interface Commit {
sent: { start: number; end: number }[];
recv: { start: number; end: number }[];
@@ -47,26 +75,35 @@ export interface Reveal {
export type KeyType = "P256";
export interface NotaryPublicKey {
typ: KeyType;
key: string;
export interface PresentationOutput {
attestation: Attestation;
server_name: string | undefined;
connection_info: ConnectionInfo;
transcript: PartialTranscript | undefined;
}
export interface ProofData {
time: number;
server_dns: string;
sent: number[];
sent_auth_ranges: { start: number; end: number }[];
received: number[];
received_auth_ranges: { start: number; end: number }[];
export interface VerifierOutput {
server_name: string;
connection_info: ConnectionInfo;
transcript: PartialTranscript;
}
export interface VerifierData {
server_dns: string;
sent: number[];
sent_auth_ranges: { start: number; end: number }[];
received: number[];
received_auth_ranges: { start: number; end: number }[];
export interface VerifyingKey {
alg: number;
data: number[];
}
export interface VerifierConfig {
max_sent_data: number;
max_recv_data: number;
}
export interface ProverConfig {
server_name: string;
max_sent_data: number;
max_recv_data_online: number | undefined;
max_recv_data: number;
defer_decryption_from_start: boolean | undefined;
}
export interface CrateLogFilter {
@@ -84,34 +121,14 @@ export type SpanEvent = "New" | "Close" | "Active";
export type LoggingLevel = "Trace" | "Debug" | "Info" | "Warn" | "Error";
export interface VerifierConfig {
id: string;
max_sent_data: number | undefined;
max_received_data: number | undefined;
}
export interface ProverConfig {
id: string;
server_dns: string;
max_sent_data: number | undefined;
max_recv_data: number | undefined;
}
/**
*/
export class NotarizedSession {
export class Attestation {
free(): void;
/**
* Builds a new proof.
* @param {Reveal} reveal
* @returns {TlsProof}
* @returns {VerifyingKey}
*/
proof(reveal: Reveal): TlsProof;
/**
* Returns the transcript.
* @returns {Transcript}
*/
transcript(): Transcript;
verifying_key(): VerifyingKey;
/**
* Serializes to a byte array.
* @returns {Uint8Array}
@@ -120,9 +137,44 @@ export class NotarizedSession {
/**
* Deserializes from a byte array.
* @param {Uint8Array} bytes
* @returns {NotarizedSession}
* @returns {Attestation}
*/
static deserialize(bytes: Uint8Array): NotarizedSession;
static deserialize(bytes: Uint8Array): Attestation;
}
/**
*/
export class NotarizationOutput {
free(): void;
/**
*/
attestation: Attestation;
/**
*/
secrets: Secrets;
}
/**
*/
export class Presentation {
free(): void;
/**
* Returns the verifying key.
* @returns {VerifyingKey}
*/
verifying_key(): VerifyingKey;
/**
* Verifies the presentation.
* @returns {PresentationOutput}
*/
verify(): PresentationOutput;
/**
* @returns {Uint8Array}
*/
serialize(): Uint8Array;
/**
* @param {Uint8Array} bytes
* @returns {Presentation}
*/
static deserialize(bytes: Uint8Array): Presentation;
}
/**
*/
@@ -156,9 +208,9 @@ export class Prover {
/**
* Runs the notarization protocol.
* @param {Commit} commit
* @returns {Promise<NotarizedSession>}
* @returns {Promise<NotarizationOutput>}
*/
notarize(commit: Commit): Promise<NotarizedSession>;
notarize(commit: Commit): Promise<NotarizationOutput>;
/**
* Reveals data to the verifier and finalizes the protocol.
* @param {Reveal} reveal
@@ -168,23 +220,24 @@ export class Prover {
}
/**
*/
export class TlsProof {
export class Secrets {
free(): void;
/**
* Returns the transcript.
* @returns {Transcript}
*/
transcript(): Transcript;
/**
* Serializes to a byte array.
* @returns {Uint8Array}
*/
serialize(): Uint8Array;
/**
* Deserializes from a byte array.
* @param {Uint8Array} bytes
* @returns {TlsProof}
* @returns {Secrets}
*/
static deserialize(bytes: Uint8Array): TlsProof;
/**
* Verifies the proof using the provided notary public key.
* @param {NotaryPublicKey} notary_key
* @returns {ProofData}
*/
verify(notary_key: NotaryPublicKey): ProofData;
static deserialize(bytes: Uint8Array): Secrets;
}
/**
*/
@@ -202,9 +255,9 @@ export class Verifier {
connect(prover_url: string): Promise<void>;
/**
* Verifies the connection and finalizes the protocol.
* @returns {Promise<VerifierData>}
* @returns {Promise<VerifierOutput>}
*/
verify(): Promise<VerifierData>;
verify(): Promise<VerifierOutput>;
}
/**
*/
@@ -226,20 +279,26 @@ export class wbg_rayon_PoolBuilder {
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
export interface InitOutput {
readonly __wbg_notarizedsession_free: (a: number) => void;
readonly notarizedsession_proof: (a: number, b: number, c: number) => void;
readonly notarizedsession_transcript: (a: number) => number;
readonly notarizedsession_serialize: (a: number, b: number) => void;
readonly notarizedsession_deserialize: (a: number, b: number, c: number) => void;
readonly __wbg_tlsproof_free: (a: number) => void;
readonly tlsproof_serialize: (a: number, b: number) => void;
readonly tlsproof_deserialize: (a: number, b: number, c: number) => void;
readonly tlsproof_verify: (a: number, b: number, c: number) => void;
readonly __wbg_verifier_free: (a: number) => void;
readonly verifier_new: (a: number) => number;
readonly verifier_connect: (a: number, b: number, c: number) => number;
readonly verifier_verify: (a: number) => number;
readonly __wbg_attestation_free: (a: number) => void;
readonly attestation_verifying_key: (a: number) => number;
readonly attestation_serialize: (a: number, b: number) => void;
readonly attestation_deserialize: (a: number, b: number, c: number) => void;
readonly __wbg_secrets_free: (a: number) => void;
readonly secrets_transcript: (a: number) => number;
readonly secrets_serialize: (a: number, b: number) => void;
readonly secrets_deserialize: (a: number, b: number, c: number) => void;
readonly __wbg_presentation_free: (a: number) => void;
readonly presentation_verify: (a: number, b: number) => void;
readonly presentation_serialize: (a: number, b: number) => void;
readonly presentation_deserialize: (a: number, b: number, c: number) => void;
readonly __wbg_notarizationoutput_free: (a: number) => void;
readonly __wbg_get_notarizationoutput_attestation: (a: number) => number;
readonly __wbg_set_notarizationoutput_attestation: (a: number, b: number) => void;
readonly __wbg_get_notarizationoutput_secrets: (a: number) => number;
readonly __wbg_set_notarizationoutput_secrets: (a: number, b: number) => void;
readonly init_logging: (a: number) => void;
readonly build_presentation: (a: number, b: number, c: number, d: number) => void;
readonly presentation_verifying_key: (a: number) => number;
readonly __wbg_prover_free: (a: number) => void;
readonly prover_new: (a: number) => number;
readonly prover_setup: (a: number, b: number, c: number) => number;
@@ -247,6 +306,10 @@ export interface InitOutput {
readonly prover_transcript: (a: number, b: number) => void;
readonly prover_notarize: (a: number, b: number) => number;
readonly prover_reveal: (a: number, b: number) => number;
readonly __wbg_verifier_free: (a: number) => void;
readonly verifier_new: (a: number) => number;
readonly verifier_connect: (a: number, b: number, c: number) => number;
readonly verifier_verify: (a: number) => number;
readonly __wbg_wbg_rayon_poolbuilder_free: (a: number) => void;
readonly wbg_rayon_poolbuilder_numThreads: (a: number) => number;
readonly wbg_rayon_poolbuilder_receiver: (a: number) => number;
@@ -258,14 +321,14 @@ export interface InitOutput {
readonly __wbindgen_malloc: (a: number, b: number) => number;
readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
readonly __wbindgen_export_3: WebAssembly.Table;
readonly _dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h55b2cafb95688ebd: (a: number, b: number) => void;
readonly _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hd2e6f08741139974: (a: number, b: number, c: number) => void;
readonly _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h6f377bea5980efdf: (a: number, b: number, c: number) => void;
readonly _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h71d6551dc02f3cc7: (a: number, b: number, c: number) => void;
readonly _dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hcbd1c326bff7445c: (a: number, b: number) => void;
readonly _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h341de7f2df06a7d1: (a: number, b: number, c: number) => void;
readonly _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hefc86e2f37cb1e42: (a: number, b: number, c: number) => void;
readonly _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__ha674a4f6aa010123: (a: number, b: number, c: number) => void;
readonly __wbindgen_add_to_stack_pointer: (a: number) => number;
readonly __wbindgen_free: (a: number, b: number, c: number) => void;
readonly __wbindgen_exn_store: (a: number) => void;
readonly wasm_bindgen__convert__closures__invoke2_mut__h0a86b19f1fa78a2d: (a: number, b: number, c: number, d: number) => void;
readonly wasm_bindgen__convert__closures__invoke2_mut__h316a499d4f512bef: (a: number, b: number, c: number, d: number) => void;
readonly __wbindgen_thread_destroy: (a?: number, b?: number) => void;
readonly __wbindgen_start: () => void;
}

View File

@@ -8,6 +8,42 @@ heap.push(undefined, null, true, false);
function getObject(idx) { return heap[idx]; }
let heap_next = heap.length;
function dropObject(idx) {
if (idx < 132) return;
heap[idx] = heap_next;
heap_next = idx;
}
function takeObject(idx) {
const ret = getObject(idx);
dropObject(idx);
return ret;
}
function isLikeNone(x) {
return x === undefined || x === null;
}
let cachedFloat64Memory0 = null;
function getFloat64Memory0() {
if (cachedFloat64Memory0 === null || cachedFloat64Memory0.buffer !== wasm.memory.buffer) {
cachedFloat64Memory0 = new Float64Array(wasm.memory.buffer);
}
return cachedFloat64Memory0;
}
let cachedInt32Memory0 = null;
function getInt32Memory0() {
if (cachedInt32Memory0 === null || cachedInt32Memory0.buffer !== wasm.memory.buffer) {
cachedInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachedInt32Memory0;
}
let WASM_VECTOR_LEN = 0;
let cachedUint8Memory0 = null;
@@ -69,42 +105,6 @@ function passStringToWasm0(arg, malloc, realloc) {
return ptr;
}
function isLikeNone(x) {
return x === undefined || x === null;
}
let cachedInt32Memory0 = null;
function getInt32Memory0() {
if (cachedInt32Memory0 === null || cachedInt32Memory0.buffer !== wasm.memory.buffer) {
cachedInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachedInt32Memory0;
}
let heap_next = heap.length;
function dropObject(idx) {
if (idx < 132) return;
heap[idx] = heap_next;
heap_next = idx;
}
function takeObject(idx) {
const ret = getObject(idx);
dropObject(idx);
return ret;
}
const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } );
if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); };
function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0;
return cachedTextDecoder.decode(getUint8Memory0().slice(ptr, ptr + len));
}
function addHeapObject(obj) {
if (heap_next === heap.length) heap.push(heap.length + 1);
const idx = heap_next;
@@ -114,13 +114,13 @@ function addHeapObject(obj) {
return idx;
}
let cachedFloat64Memory0 = null;
const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } );
function getFloat64Memory0() {
if (cachedFloat64Memory0 === null || cachedFloat64Memory0.buffer !== wasm.memory.buffer) {
cachedFloat64Memory0 = new Float64Array(wasm.memory.buffer);
}
return cachedFloat64Memory0;
if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); };
function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0;
return cachedTextDecoder.decode(getUint8Memory0().slice(ptr, ptr + len));
}
let cachedBigInt64Memory0 = null;
@@ -228,19 +228,19 @@ function makeMutClosure(arg0, arg1, dtor, f) {
return real;
}
function __wbg_adapter_54(arg0, arg1) {
wasm._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h55b2cafb95688ebd(arg0, arg1);
wasm._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hcbd1c326bff7445c(arg0, arg1);
}
function __wbg_adapter_57(arg0, arg1, arg2) {
wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hd2e6f08741139974(arg0, arg1, addHeapObject(arg2));
wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h341de7f2df06a7d1(arg0, arg1, addHeapObject(arg2));
}
function __wbg_adapter_60(arg0, arg1, arg2) {
wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h6f377bea5980efdf(arg0, arg1, addHeapObject(arg2));
wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hefc86e2f37cb1e42(arg0, arg1, addHeapObject(arg2));
}
function __wbg_adapter_63(arg0, arg1, arg2) {
wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h71d6551dc02f3cc7(arg0, arg1, addHeapObject(arg2));
wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__ha674a4f6aa010123(arg0, arg1, addHeapObject(arg2));
}
function getArrayU8FromWasm0(ptr, len) {
@@ -254,6 +254,13 @@ function passArray8ToWasm0(arg, malloc) {
WASM_VECTOR_LEN = arg.length;
return ptr;
}
function _assertClass(instance, klass) {
if (!(instance instanceof klass)) {
throw new Error(`expected instance of ${klass.name}`);
}
return instance.ptr;
}
/**
* Initializes logging.
* @param {LoggingConfig | undefined} [config]
@@ -262,6 +269,31 @@ export function init_logging(config) {
wasm.init_logging(isLikeNone(config) ? 0 : addHeapObject(config));
}
/**
* Builds a presentation.
* @param {Attestation} attestation
* @param {Secrets} secrets
* @param {Reveal} reveal
* @returns {Presentation}
*/
export function build_presentation(attestation, secrets, reveal) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
_assertClass(attestation, Attestation);
_assertClass(secrets, Secrets);
wasm.build_presentation(retptr, attestation.__wbg_ptr, secrets.__wbg_ptr, addHeapObject(reveal));
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var r2 = getInt32Memory0()[retptr / 4 + 2];
if (r2) {
throw takeObject(r1);
}
return Presentation.__wrap(r0);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
function handleError(f, args) {
try {
return f.apply(this, args);
@@ -269,8 +301,8 @@ function handleError(f, args) {
wasm.__wbindgen_exn_store(addHeapObject(e));
}
}
function __wbg_adapter_235(arg0, arg1, arg2, arg3) {
wasm.wasm_bindgen__convert__closures__invoke2_mut__h0a86b19f1fa78a2d(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3));
function __wbg_adapter_243(arg0, arg1, arg2, arg3) {
wasm.wasm_bindgen__convert__closures__invoke2_mut__h316a499d4f512bef(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3));
}
/**
@@ -289,58 +321,37 @@ export function wbg_rayon_start_worker(receiver) {
wasm.wbg_rayon_start_worker(receiver);
}
const NotarizedSessionFinalization = (typeof FinalizationRegistry === 'undefined')
const AttestationFinalization = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(ptr => wasm.__wbg_notarizedsession_free(ptr >>> 0));
: new FinalizationRegistry(ptr => wasm.__wbg_attestation_free(ptr >>> 0));
/**
*/
export class NotarizedSession {
export class Attestation {
static __wrap(ptr) {
ptr = ptr >>> 0;
const obj = Object.create(NotarizedSession.prototype);
const obj = Object.create(Attestation.prototype);
obj.__wbg_ptr = ptr;
NotarizedSessionFinalization.register(obj, obj.__wbg_ptr, obj);
AttestationFinalization.register(obj, obj.__wbg_ptr, obj);
return obj;
}
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
NotarizedSessionFinalization.unregister(this);
AttestationFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_notarizedsession_free(ptr);
wasm.__wbg_attestation_free(ptr);
}
/**
* Builds a new proof.
* @param {Reveal} reveal
* @returns {TlsProof}
* @returns {VerifyingKey}
*/
proof(reveal) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.notarizedsession_proof(retptr, this.__wbg_ptr, addHeapObject(reveal));
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var r2 = getInt32Memory0()[retptr / 4 + 2];
if (r2) {
throw takeObject(r1);
}
return TlsProof.__wrap(r0);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
/**
* Returns the transcript.
* @returns {Transcript}
*/
transcript() {
const ret = wasm.notarizedsession_transcript(this.__wbg_ptr);
verifying_key() {
const ret = wasm.attestation_verifying_key(this.__wbg_ptr);
return takeObject(ret);
}
/**
@@ -350,7 +361,7 @@ export class NotarizedSession {
serialize() {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.notarizedsession_serialize(retptr, this.__wbg_ptr);
wasm.attestation_serialize(retptr, this.__wbg_ptr);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v1 = getArrayU8FromWasm0(r0, r1).slice();
@@ -363,21 +374,171 @@ export class NotarizedSession {
/**
* Deserializes from a byte array.
* @param {Uint8Array} bytes
* @returns {NotarizedSession}
* @returns {Attestation}
*/
static deserialize(bytes) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
wasm.notarizedsession_deserialize(retptr, ptr0, len0);
wasm.attestation_deserialize(retptr, ptr0, len0);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var r2 = getInt32Memory0()[retptr / 4 + 2];
if (r2) {
throw takeObject(r1);
}
return NotarizedSession.__wrap(r0);
return Attestation.__wrap(r0);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
}
const NotarizationOutputFinalization = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(ptr => wasm.__wbg_notarizationoutput_free(ptr >>> 0));
/**
*/
export class NotarizationOutput {
static __wrap(ptr) {
ptr = ptr >>> 0;
const obj = Object.create(NotarizationOutput.prototype);
obj.__wbg_ptr = ptr;
NotarizationOutputFinalization.register(obj, obj.__wbg_ptr, obj);
return obj;
}
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
NotarizationOutputFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_notarizationoutput_free(ptr);
}
/**
* @returns {Attestation}
*/
get attestation() {
const ret = wasm.__wbg_get_notarizationoutput_attestation(this.__wbg_ptr);
return Attestation.__wrap(ret);
}
/**
* @param {Attestation} arg0
*/
set attestation(arg0) {
_assertClass(arg0, Attestation);
var ptr0 = arg0.__destroy_into_raw();
wasm.__wbg_set_notarizationoutput_attestation(this.__wbg_ptr, ptr0);
}
/**
* @returns {Secrets}
*/
get secrets() {
const ret = wasm.__wbg_get_notarizationoutput_secrets(this.__wbg_ptr);
return Secrets.__wrap(ret);
}
/**
* @param {Secrets} arg0
*/
set secrets(arg0) {
_assertClass(arg0, Secrets);
var ptr0 = arg0.__destroy_into_raw();
wasm.__wbg_set_notarizationoutput_secrets(this.__wbg_ptr, ptr0);
}
}
const PresentationFinalization = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(ptr => wasm.__wbg_presentation_free(ptr >>> 0));
/**
*/
export class Presentation {
static __wrap(ptr) {
ptr = ptr >>> 0;
const obj = Object.create(Presentation.prototype);
obj.__wbg_ptr = ptr;
PresentationFinalization.register(obj, obj.__wbg_ptr, obj);
return obj;
}
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
PresentationFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_presentation_free(ptr);
}
/**
* Returns the verifying key.
* @returns {VerifyingKey}
*/
verifying_key() {
const ret = wasm.attestation_verifying_key(this.__wbg_ptr);
return takeObject(ret);
}
/**
* Verifies the presentation.
* @returns {PresentationOutput}
*/
verify() {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.presentation_verify(retptr, this.__wbg_ptr);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var r2 = getInt32Memory0()[retptr / 4 + 2];
if (r2) {
throw takeObject(r1);
}
return takeObject(r0);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
/**
* @returns {Uint8Array}
*/
serialize() {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.presentation_serialize(retptr, this.__wbg_ptr);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v1 = getArrayU8FromWasm0(r0, r1).slice();
wasm.__wbindgen_free(r0, r1 * 1, 1);
return v1;
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
/**
* @param {Uint8Array} bytes
* @returns {Presentation}
*/
static deserialize(bytes) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
wasm.presentation_deserialize(retptr, ptr0, len0);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var r2 = getInt32Memory0()[retptr / 4 + 2];
if (r2) {
throw takeObject(r1);
}
return Presentation.__wrap(r0);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
@@ -458,7 +619,7 @@ export class Prover {
/**
* Runs the notarization protocol.
* @param {Commit} commit
* @returns {Promise<NotarizedSession>}
* @returns {Promise<NotarizationOutput>}
*/
notarize(commit) {
const ret = wasm.prover_notarize(this.__wbg_ptr, addHeapObject(commit));
@@ -475,39 +636,48 @@ export class Prover {
}
}
const TlsProofFinalization = (typeof FinalizationRegistry === 'undefined')
const SecretsFinalization = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(ptr => wasm.__wbg_tlsproof_free(ptr >>> 0));
: new FinalizationRegistry(ptr => wasm.__wbg_secrets_free(ptr >>> 0));
/**
*/
export class TlsProof {
export class Secrets {
static __wrap(ptr) {
ptr = ptr >>> 0;
const obj = Object.create(TlsProof.prototype);
const obj = Object.create(Secrets.prototype);
obj.__wbg_ptr = ptr;
TlsProofFinalization.register(obj, obj.__wbg_ptr, obj);
SecretsFinalization.register(obj, obj.__wbg_ptr, obj);
return obj;
}
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
TlsProofFinalization.unregister(this);
SecretsFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_tlsproof_free(ptr);
wasm.__wbg_secrets_free(ptr);
}
/**
* Returns the transcript.
* @returns {Transcript}
*/
transcript() {
const ret = wasm.secrets_transcript(this.__wbg_ptr);
return takeObject(ret);
}
/**
* Serializes to a byte array.
* @returns {Uint8Array}
*/
serialize() {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.tlsproof_serialize(retptr, this.__wbg_ptr);
wasm.secrets_serialize(retptr, this.__wbg_ptr);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var v1 = getArrayU8FromWasm0(r0, r1).slice();
@@ -518,43 +688,23 @@ export class TlsProof {
}
}
/**
* Deserializes from a byte array.
* @param {Uint8Array} bytes
* @returns {TlsProof}
* @returns {Secrets}
*/
static deserialize(bytes) {
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
wasm.tlsproof_deserialize(retptr, ptr0, len0);
wasm.secrets_deserialize(retptr, ptr0, len0);
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var r2 = getInt32Memory0()[retptr / 4 + 2];
if (r2) {
throw takeObject(r1);
}
return TlsProof.__wrap(r0);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
}
/**
* Verifies the proof using the provided notary public key.
* @param {NotaryPublicKey} notary_key
* @returns {ProofData}
*/
verify(notary_key) {
try {
const ptr = this.__destroy_into_raw();
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.tlsproof_verify(retptr, ptr, addHeapObject(notary_key));
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
var r2 = getInt32Memory0()[retptr / 4 + 2];
if (r2) {
throw takeObject(r1);
}
return takeObject(r0);
return Secrets.__wrap(r0);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
}
@@ -600,7 +750,7 @@ export class Verifier {
}
/**
* Verifies the connection and finalizes the protocol.
* @returns {Promise<VerifierData>}
* @returns {Promise<VerifierOutput>}
*/
verify() {
const ret = wasm.verifier_verify(this.__wbg_ptr);
@@ -689,35 +839,18 @@ async function __wbg_load(module, imports) {
function __wbg_get_imports() {
const imports = {};
imports.wbg = {};
imports.wbg.__wbg_notarizedsession_new = function(arg0) {
const ret = NotarizedSession.__wrap(arg0);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_string_get = function(arg0, arg1) {
const obj = getObject(arg1);
const ret = typeof(obj) === 'string' ? obj : undefined;
var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len1 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len1;
getInt32Memory0()[arg0 / 4 + 0] = ptr1;
};
imports.wbg.__wbindgen_object_drop_ref = function(arg0) {
takeObject(arg0);
};
imports.wbg.__wbindgen_is_object = function(arg0) {
const val = getObject(arg0);
const ret = typeof(val) === 'object' && val !== null;
return ret;
};
imports.wbg.__wbindgen_error_new = function(arg0, arg1) {
const ret = new Error(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
};
imports.wbg.__wbindgen_boolean_get = function(arg0) {
const v = getObject(arg0);
const ret = typeof(v) === 'boolean' ? (v ? 1 : 0) : 2;
return ret;
};
imports.wbg.__wbg_notarizationoutput_new = function(arg0) {
const ret = NotarizationOutput.__wrap(arg0);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_is_bigint = function(arg0) {
const ret = typeof(getObject(arg0)) === 'bigint';
return ret;
@@ -728,6 +861,19 @@ function __wbg_get_imports() {
getFloat64Memory0()[arg0 / 8 + 1] = isLikeNone(ret) ? 0 : ret;
getInt32Memory0()[arg0 / 4 + 0] = !isLikeNone(ret);
};
imports.wbg.__wbindgen_string_get = function(arg0, arg1) {
const obj = getObject(arg1);
const ret = typeof(obj) === 'string' ? obj : undefined;
var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len1 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len1;
getInt32Memory0()[arg0 / 4 + 0] = ptr1;
};
imports.wbg.__wbindgen_is_object = function(arg0) {
const val = getObject(arg0);
const ret = typeof(val) === 'object' && val !== null;
return ret;
};
imports.wbg.__wbindgen_in = function(arg0, arg1) {
const ret = getObject(arg0) in getObject(arg1);
return ret;
@@ -744,18 +890,22 @@ function __wbg_get_imports() {
const ret = BigInt.asUintN(64, arg0);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_error_new = function(arg0, arg1) {
const ret = new Error(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
};
imports.wbg.__wbindgen_is_undefined = function(arg0) {
const ret = getObject(arg0) === undefined;
return ret;
};
imports.wbg.__wbindgen_is_string = function(arg0) {
const ret = typeof(getObject(arg0)) === 'string';
return ret;
};
imports.wbg.__wbindgen_object_clone_ref = function(arg0) {
const ret = getObject(arg0);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_is_string = function(arg0) {
const ret = typeof(getObject(arg0)) === 'string';
return ret;
};
imports.wbg.__wbindgen_cb_drop = function(arg0) {
const obj = takeObject(arg0).original;
if (obj.cnt-- == 1) {
@@ -765,6 +915,10 @@ function __wbg_get_imports() {
const ret = false;
return ret;
};
imports.wbg.__wbindgen_as_number = function(arg0) {
const ret = +getObject(arg0);
return ret;
};
imports.wbg.__wbindgen_string_new = function(arg0, arg1) {
const ret = getStringFromWasm0(arg0, arg1);
return addHeapObject(ret);
@@ -791,6 +945,22 @@ function __wbg_get_imports() {
wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);
}
};
imports.wbg.__wbg_waitAsync_5d743fc9058ba01a = function() {
const ret = Atomics.waitAsync;
return addHeapObject(ret);
};
imports.wbg.__wbg_waitAsync_46d5c36955b71a79 = function(arg0, arg1, arg2) {
const ret = Atomics.waitAsync(getObject(arg0), arg1, arg2);
return addHeapObject(ret);
};
imports.wbg.__wbg_async_19c0400d97cc72fe = function(arg0) {
const ret = getObject(arg0).async;
return ret;
};
imports.wbg.__wbg_value_571d60108110e917 = function(arg0) {
const ret = getObject(arg0).value;
return addHeapObject(ret);
};
imports.wbg.__wbindgen_number_new = function(arg0) {
const ret = arg0;
return addHeapObject(ret);
@@ -819,22 +989,6 @@ function __wbg_get_imports() {
const ret = typeof(getObject(arg0)) === 'function';
return ret;
};
imports.wbg.__wbg_waitAsync_5d743fc9058ba01a = function() {
const ret = Atomics.waitAsync;
return addHeapObject(ret);
};
imports.wbg.__wbg_waitAsync_46d5c36955b71a79 = function(arg0, arg1, arg2) {
const ret = Atomics.waitAsync(getObject(arg0), arg1, arg2);
return addHeapObject(ret);
};
imports.wbg.__wbg_async_19c0400d97cc72fe = function(arg0) {
const ret = getObject(arg0).async;
return ret;
};
imports.wbg.__wbg_value_571d60108110e917 = function(arg0) {
const ret = getObject(arg0).value;
return addHeapObject(ret);
};
imports.wbg.__wbg_timeOrigin_5c8b9e35719de799 = function(arg0) {
const ret = getObject(arg0).timeOrigin;
return ret;
@@ -1001,10 +1155,6 @@ function __wbg_get_imports() {
const ret = getObject(arg0) == getObject(arg1);
return ret;
};
imports.wbg.__wbindgen_as_number = function(arg0) {
const ret = +getObject(arg0);
return ret;
};
imports.wbg.__wbg_String_b9412f8799faab3e = function(arg0, arg1) {
const ret = String(getObject(arg1));
const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
@@ -1145,7 +1295,7 @@ function __wbg_get_imports() {
const a = state0.a;
state0.a = 0;
try {
return __wbg_adapter_235(a, state0.b, arg0, arg1);
return __wbg_adapter_243(a, state0.b, arg0, arg1);
} finally {
state0.a = a;
}
@@ -1236,24 +1386,24 @@ function __wbg_get_imports() {
const ret = startWorkers(takeObject(arg0), takeObject(arg1), wbg_rayon_PoolBuilder.__wrap(arg2));
return addHeapObject(ret);
};
imports.wbg.__wbindgen_closure_wrapper3391 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 1128, __wbg_adapter_54);
imports.wbg.__wbindgen_closure_wrapper3367 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 1192, __wbg_adapter_54);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_closure_wrapper3393 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 1128, __wbg_adapter_57);
imports.wbg.__wbindgen_closure_wrapper3369 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 1192, __wbg_adapter_57);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_closure_wrapper3853 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 1428, __wbg_adapter_60);
imports.wbg.__wbindgen_closure_wrapper3847 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 1430, __wbg_adapter_60);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_closure_wrapper5184 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 2256, __wbg_adapter_63);
imports.wbg.__wbindgen_closure_wrapper5985 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 2751, __wbg_adapter_63);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_closure_wrapper5185 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 2256, __wbg_adapter_63);
imports.wbg.__wbindgen_closure_wrapper5987 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 2751, __wbg_adapter_63);
return addHeapObject(ret);
};

Binary file not shown.

View File

@@ -1,19 +1,25 @@
/* tslint:disable */
/* eslint-disable */
export function __wbg_notarizedsession_free(a: number): void;
export function notarizedsession_proof(a: number, b: number, c: number): void;
export function notarizedsession_transcript(a: number): number;
export function notarizedsession_serialize(a: number, b: number): void;
export function notarizedsession_deserialize(a: number, b: number, c: number): void;
export function __wbg_tlsproof_free(a: number): void;
export function tlsproof_serialize(a: number, b: number): void;
export function tlsproof_deserialize(a: number, b: number, c: number): void;
export function tlsproof_verify(a: number, b: number, c: number): void;
export function __wbg_verifier_free(a: number): void;
export function verifier_new(a: number): number;
export function verifier_connect(a: number, b: number, c: number): number;
export function verifier_verify(a: number): number;
export function __wbg_attestation_free(a: number): void;
export function attestation_verifying_key(a: number): number;
export function attestation_serialize(a: number, b: number): void;
export function attestation_deserialize(a: number, b: number, c: number): void;
export function __wbg_secrets_free(a: number): void;
export function secrets_transcript(a: number): number;
export function secrets_serialize(a: number, b: number): void;
export function secrets_deserialize(a: number, b: number, c: number): void;
export function __wbg_presentation_free(a: number): void;
export function presentation_verify(a: number, b: number): void;
export function presentation_serialize(a: number, b: number): void;
export function presentation_deserialize(a: number, b: number, c: number): void;
export function __wbg_notarizationoutput_free(a: number): void;
export function __wbg_get_notarizationoutput_attestation(a: number): number;
export function __wbg_set_notarizationoutput_attestation(a: number, b: number): void;
export function __wbg_get_notarizationoutput_secrets(a: number): number;
export function __wbg_set_notarizationoutput_secrets(a: number, b: number): void;
export function init_logging(a: number): void;
export function build_presentation(a: number, b: number, c: number, d: number): void;
export function presentation_verifying_key(a: number): number;
export function __wbg_prover_free(a: number): void;
export function prover_new(a: number): number;
export function prover_setup(a: number, b: number, c: number): number;
@@ -21,6 +27,10 @@ export function prover_send_request(a: number, b: number, c: number, d: number):
export function prover_transcript(a: number, b: number): void;
export function prover_notarize(a: number, b: number): number;
export function prover_reveal(a: number, b: number): number;
export function __wbg_verifier_free(a: number): void;
export function verifier_new(a: number): number;
export function verifier_connect(a: number, b: number, c: number): number;
export function verifier_verify(a: number): number;
export function __wbg_wbg_rayon_poolbuilder_free(a: number): void;
export function wbg_rayon_poolbuilder_numThreads(a: number): number;
export function wbg_rayon_poolbuilder_receiver(a: number): number;
@@ -32,13 +42,13 @@ export const memory: WebAssembly.Memory;
export function __wbindgen_malloc(a: number, b: number): number;
export function __wbindgen_realloc(a: number, b: number, c: number, d: number): number;
export const __wbindgen_export_3: WebAssembly.Table;
export function _dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h55b2cafb95688ebd(a: number, b: number): void;
export function _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hd2e6f08741139974(a: number, b: number, c: number): void;
export function _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h6f377bea5980efdf(a: number, b: number, c: number): void;
export function _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h71d6551dc02f3cc7(a: number, b: number, c: number): void;
export function _dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hcbd1c326bff7445c(a: number, b: number): void;
export function _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h341de7f2df06a7d1(a: number, b: number, c: number): void;
export function _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hefc86e2f37cb1e42(a: number, b: number, c: number): void;
export function _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__ha674a4f6aa010123(a: number, b: number, c: number): void;
export function __wbindgen_add_to_stack_pointer(a: number): number;
export function __wbindgen_free(a: number, b: number, c: number): void;
export function __wbindgen_exn_store(a: number): void;
export function wasm_bindgen__convert__closures__invoke2_mut__h0a86b19f1fa78a2d(a: number, b: number, c: number, d: number): void;
export function wasm_bindgen__convert__closures__invoke2_mut__h316a499d4f512bef(a: number, b: number, c: number, d: number): void;
export function __wbindgen_thread_destroy(a: number, b: number): void;
export function __wbindgen_start(): void;