diff --git a/package.json b/package.json index 507f7bf1..f061edb2 100755 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "scripts": { "clone:tlsn": "bash ./utils/download-tlsn.sh", "build:wasm": "wasm-pack build --target web wasm/prover", + "update:wasm": "cargo update --manifest-path wasm/prover/Cargo.toml", "build": "NODE_ENV=production node utils/build.js", "build:webpack": "NODE_ENV=production webpack --config webpack.config.js", "websockify": "docker run -it --rm -p 55688:80 -v $(pwd):/app novnc/websockify 80 --target-config /app/websockify_config", @@ -87,4 +88,4 @@ "webpack-dev-server": "^4.11.1", "zip-webpack-plugin": "^4.0.1" } -} +} \ No newline at end of file diff --git a/src/pages/Offscreen/worker.ts b/src/pages/Offscreen/worker.ts index 3a9f2a8d..b5d4ded6 100644 --- a/src/pages/Offscreen/worker.ts +++ b/src/pages/Offscreen/worker.ts @@ -50,7 +50,7 @@ class TLSN { const { method = 'GET', headers = {}, - body= '', + body = '', maxTranscriptSize = 16384, notaryUrl, websocketProxyUrl, diff --git a/wasm/prover/check.sh b/wasm/prover/check.sh new file mode 100755 index 00000000..a00d51fb --- /dev/null +++ b/wasm/prover/check.sh @@ -0,0 +1,2 @@ +#!/bin/sh +cargo check --target "wasm32-unknown-unknown" diff --git a/wasm/prover/src/lib.rs b/wasm/prover/src/lib.rs index 682f7eda..91a614db 100644 --- a/wasm/prover/src/lib.rs +++ b/wasm/prover/src/lib.rs @@ -1,44 +1,35 @@ +mod request_opt; mod requests; -mod requestOpt; -use std::panic; use std::ops::Range; +use std::panic; use web_time::Instant; -use hyper::{body::to_bytes, Body, Request, StatusCode}; -use futures::{AsyncWriteExt, TryFutureExt}; use futures::channel::oneshot; +use futures::AsyncWriteExt; +use hyper::{body::to_bytes, Body, Request, StatusCode}; use tlsn_prover::tls::{Prover, ProverConfig}; -// use tokio::io::AsyncWriteExt as _; -use tokio_util::compat::{FuturesAsyncReadCompatExt, TokioAsyncReadCompatExt}; +use tokio_util::compat::FuturesAsyncReadCompatExt; -use tokio_util::compat::FuturesAsyncWriteCompatExt; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::spawn_local; -use tracing_web::{MakeConsoleWriter, performance_layer}; -use tracing_subscriber::fmt::format::Pretty; -use tracing_subscriber::fmt::time::UtcTime; -use tracing_subscriber::prelude::*; - -use ws_stream_wasm::{*}; +use ws_stream_wasm::*; -use crate::requests::{NotarizationSessionRequest, NotarizationSessionResponse, ClientType}; -use crate::requestOpt::{RequestOptions, VerifyResult}; +use crate::request_opt::{RequestOptions, VerifyResult}; +use crate::requests::{ClientType, NotarizationSessionRequest, NotarizationSessionResponse}; pub use wasm_bindgen_rayon::init_thread_pool; -// use rayon::iter::IntoParallelRefIterator; -use rayon::prelude::*; -use wasm_bindgen_futures::JsFuture; -use web_sys::{Request as WebsysRequest, RequestInit, Headers, RequestMode, Response}; -use js_sys::{JSON, Array}; +use js_sys::{Array, JSON}; use url::Url; +use wasm_bindgen_futures::JsFuture; +use web_sys::{Headers, Request as WebsysRequest, RequestInit, RequestMode, Response}; -use tlsn_core::proof::{SessionProof, TlsProof}; -use std::time::Duration; use elliptic_curve::pkcs8::DecodePublicKey; +use std::time::Duration; +use tlsn_core::proof::{SessionProof, TlsProof}; // A macro to provide `println!(..)`-style syntax for `console.log` logging. macro_rules! log { @@ -68,13 +59,13 @@ async fn fetch_as_json_string(url: &str, opts: &RequestInit) -> Result Result { - log!("target_url: {}", targetUrl); - let target_url = Url::parse(targetUrl).expect("url must be valid"); + log!("target_url: {}", target_url_str); + let target_url = Url::parse(target_url_str).expect("url must be valid"); log!("target_url.host: {}", target_url.host().unwrap()); let options: RequestOptions = serde_wasm_bindgen::from_value(val).unwrap(); @@ -135,7 +126,8 @@ pub async fn prover( ); log!("Request: {}", url); let rust_string = fetch_as_json_string(&url, &opts).await.unwrap(); - let notarization_response = serde_json::from_str::(&rust_string).unwrap(); + let notarization_response = + serde_json::from_str::(&rust_string).unwrap(); log!("Response: {}", rust_string); log!("Notarization response: {:?}", notarization_response,); @@ -145,22 +137,19 @@ pub async fn prover( notary_host, notarization_response.session_id ); - let (mut notary_ws_meta, mut notary_ws_stream) = WsMeta::connect( - notary_wss_url, - None - ).await - .expect_throw( "assume the notary ws connection succeeds" ); - let mut notary_ws_stream_into = notary_ws_stream.into_io(); + let (_, notary_ws_stream) = WsMeta::connect(notary_wss_url, None) + .await + .expect_throw("assume the notary ws connection succeeds"); + let notary_ws_stream_into = notary_ws_stream.into_io(); /* - Connect Application Server with websocket proxy - */ + Connect Application Server with websocket proxy + */ - let (mut client_ws_meta, mut client_ws_stream) = WsMeta::connect( - options.websocket_proxy_url, - None ).await - .expect_throw( "assume the client ws connection succeeds" ); - let mut client_ws_stream_into = client_ws_stream.into_io(); + let (_, client_ws_stream) = WsMeta::connect(options.websocket_proxy_url, None) + .await + .expect_throw("assume the client ws connection succeeds"); + let client_ws_stream_into = client_ws_stream.into_io(); log!("!@# 0"); @@ -181,7 +170,6 @@ pub async fn prover( .await .unwrap(); - // Bind the Prover to the server connection. // The returned `mpc_tls_connection` is an MPC TLS connection to the Server: all data written // to/read from it will be encrypted/decrypted using MPC with the Notary. @@ -189,7 +177,6 @@ pub async fn prover( log!("!@# 3"); - // let prover_task = tokio::spawn(prover_fut); let (prover_sender, prover_receiver) = oneshot::channel(); let handled_prover_fut = async { @@ -197,7 +184,7 @@ pub async fn prover( Ok(prover_result) => { // Send the prover let _ = prover_sender.send(prover_result); - }, + } Err(err) => { panic!("An error occurred in prover_fut: {:?}", err); } @@ -207,9 +194,10 @@ pub async fn prover( log!("!@# 7"); // Attach the hyper HTTP client to the TLS connection - let (mut request_sender, connection) = hyper::client::conn::handshake(mpc_tls_connection.compat()) - .await - .unwrap(); + let (mut request_sender, connection) = + hyper::client::conn::handshake(mpc_tls_connection.compat()) + .await + .unwrap(); log!("!@# 8"); // Spawn the HTTP task to be run concurrently @@ -221,17 +209,21 @@ pub async fn prover( Ok(connection_result) => { // Send the connection let _ = connection_sender.send(connection_result); - }, + } Err(err) => { panic!("An error occurred in connection_task: {:?}", err); } } }; spawn_local(handled_connection_fut); - log!("!@# 9 - {} request to {}", options.method.as_str(), targetUrl); + log!( + "!@# 9 - {} request to {}", + options.method.as_str(), + target_url_str + ); let mut req_with_header = Request::builder() - .uri(targetUrl) + .uri(target_url_str) .method(options.method.as_str()); for (key, value) in options.headers { @@ -248,14 +240,16 @@ pub async fn prover( log!("added body - {}", options.body.as_str()); req_with_body = req_with_header.body(Body::from(options.body)); } - - let unwrapped_request = req_with_body.unwrap(); + let unwrapped_request = req_with_body.unwrap(); log!("Starting an MPC TLS connection with the server"); // Send the request to the Server and get a response via the MPC TLS connection - let response = request_sender.send_request(unwrapped_request).await.unwrap(); + let response = request_sender + .send_request(unwrapped_request) + .await + .unwrap(); log!("Got a response from the server"); @@ -280,12 +274,15 @@ pub async fn prover( // The Prover task should be done now, so we can grab it. // let mut prover = prover_task.await.unwrap().unwrap(); - let mut prover = prover_receiver.await.unwrap(); + let prover = prover_receiver.await.unwrap(); let mut prover = prover.start_notarize(); log!("!@# 14"); let secret_headers_vecs = string_list_to_bytes_vec(&secret_headers); - let secret_headers_slices: Vec<&[u8]> = secret_headers_vecs.iter().map(|vec| vec.as_slice()).collect(); + let secret_headers_slices: Vec<&[u8]> = secret_headers_vecs + .iter() + .map(|vec| vec.as_slice()) + .collect(); // Identify the ranges in the transcript that contain revealed_headers let (sent_public_ranges, sent_private_ranges) = find_ranges( @@ -294,7 +291,8 @@ pub async fn prover( ); let secret_body_vecs = string_list_to_bytes_vec(&secret_body); - let secret_body_slices: Vec<&[u8]> = secret_body_vecs.iter().map(|vec| vec.as_slice()).collect(); + let secret_body_slices: Vec<&[u8]> = + secret_body_vecs.iter().map(|vec| vec.as_slice()).collect(); // Identify the ranges in the transcript that contain the only data we want to reveal later let (recv_public_ranges, recv_private_ranges) = find_ranges( @@ -303,7 +301,7 @@ pub async fn prover( ); log!("!@# 15"); - let recv_len = prover.recv_transcript().data().len(); + let _recv_len = prover.recv_transcript().data().len(); let builder = prover.commitment_builder(); @@ -357,14 +355,10 @@ pub async fn prover( log!("!@# request takes: {} seconds", duration.as_secs()); Ok(res) - } #[wasm_bindgen] -pub async fn verify( - proof: &str, - notary_pubkey_str: &str, -) -> Result { +pub async fn verify(proof: &str, notary_pubkey_str: &str) -> Result { log!("!@# proof {}", proof); let proof: TlsProof = serde_json::from_str(proof).unwrap(); @@ -377,13 +371,15 @@ pub async fn verify( substrings, } = proof; - - log!("!@# notary_pubkey {}, {}", notary_pubkey_str, notary_pubkey_str.len()); + log!( + "!@# notary_pubkey {}, {}", + notary_pubkey_str, + notary_pubkey_str.len() + ); session .verify_with_default_cert_verifier(get_notary_pubkey(notary_pubkey_str)) .unwrap(); - let SessionProof { // The session header that was signed by the Notary is a succinct commitment to the TLS transcript. header, @@ -407,7 +403,8 @@ pub async fn verify( log!("-------------------------------------------------------------------"); log!( "Successfully verified that the bytes below came from a session with {:?} at {}.", - server_name, time + server_name, + time ); log!("Note that the bytes which the Prover chose not to disclose are shown as X."); log!("Bytes sent:"); @@ -423,12 +420,13 @@ pub async fn verify( recv: String::from_utf8(recv.data().to_vec()).unwrap(), }; let res = serde_json::to_string_pretty(&result).unwrap(); - + Ok(res) } +#[allow(unused)] fn print_type_of(_: &T) { - log!("{}", std::any::type_name::()) + log!("{}", std::any::type_name::()); } /// Returns a Notary pubkey trusted by this Verifier diff --git a/wasm/prover/src/requestOpt.rs b/wasm/prover/src/request_opt.rs similarity index 100% rename from wasm/prover/src/requestOpt.rs rename to wasm/prover/src/request_opt.rs diff --git a/wasm/prover/src/requests.rs b/wasm/prover/src/requests.rs index 75c66ab7..1a9a892e 100644 --- a/wasm/prover/src/requests.rs +++ b/wasm/prover/src/requests.rs @@ -1,5 +1,3 @@ -use std::{collections::HashMap, sync::Arc}; - use serde::{Deserialize, Serialize}; /// Response object of the /session API