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

Cleanup #33

Merged
merged 3 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -87,4 +88,4 @@
"webpack-dev-server": "^4.11.1",
"zip-webpack-plugin": "^4.0.1"
}
}
}
2 changes: 1 addition & 1 deletion src/pages/Offscreen/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class TLSN {
const {
method = 'GET',
headers = {},
body= '',
body = '',
maxTranscriptSize = 16384,
notaryUrl,
websocketProxyUrl,
Expand Down
2 changes: 2 additions & 0 deletions wasm/prover/check.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/sh
cargo check --target "wasm32-unknown-unknown"
130 changes: 64 additions & 66 deletions wasm/prover/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -68,13 +59,13 @@ async fn fetch_as_json_string(url: &str, opts: &RequestInit) -> Result<String, J

#[wasm_bindgen]
pub async fn prover(
targetUrl: &str,
target_url_str: &str,
val: JsValue,
secret_headers: JsValue,
secret_body: JsValue,
) -> Result<String, JsValue> {
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();
Expand Down Expand Up @@ -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::<NotarizationSessionResponse>(&rust_string).unwrap();
let notarization_response =
serde_json::from_str::<NotarizationSessionResponse>(&rust_string).unwrap();
log!("Response: {}", rust_string);

log!("Notarization response: {:?}", notarization_response,);
Expand All @@ -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");

Expand All @@ -181,23 +170,21 @@ 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.
let (mpc_tls_connection, prover_fut) = prover.connect(client_ws_stream_into).await.unwrap();

log!("!@# 3");


// let prover_task = tokio::spawn(prover_fut);
let (prover_sender, prover_receiver) = oneshot::channel();
let handled_prover_fut = async {
match prover_fut.await {
Ok(prover_result) => {
// Send the prover
let _ = prover_sender.send(prover_result);
},
}
Err(err) => {
panic!("An error occurred in prover_fut: {:?}", err);
}
Expand All @@ -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
Expand All @@ -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 {
Expand All @@ -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");

Expand All @@ -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(
Expand All @@ -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(
Expand All @@ -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();

Expand Down Expand Up @@ -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<String, JsValue> {
pub async fn verify(proof: &str, notary_pubkey_str: &str) -> Result<String, JsValue> {
log!("!@# proof {}", proof);
let proof: TlsProof = serde_json::from_str(proof).unwrap();

Expand All @@ -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,
Expand All @@ -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:");
Expand All @@ -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: ?Sized>(_: &T) {
log!("{}", std::any::type_name::<T>())
log!("{}", std::any::type_name::<T>());
}

/// Returns a Notary pubkey trusted by this Verifier
Expand Down
File renamed without changes.
2 changes: 0 additions & 2 deletions wasm/prover/src/requests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::{collections::HashMap, sync::Arc};

use serde::{Deserialize, Serialize};

/// Response object of the /session API
Expand Down
Loading