use super::{Hasher, Proof, Prover};
use crate::chunk::ChunkAddress;
use alloy_primitives::B256;
use digest::Digest;
use js_sys::{Array, Uint8Array};
use wasm_bindgen::prelude::*;
#[wasm_bindgen(js_name = Hasher)]
pub struct WasmHasher(Hasher);
#[wasm_bindgen(js_class = Hasher)]
impl WasmHasher {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
Self(Hasher::new())
}
#[wasm_bindgen]
pub fn set_span(&mut self, span: u64) {
self.0.set_span(span);
}
#[wasm_bindgen(js_name = prefixWith)]
pub fn prefix_with(&mut self, prefix: &Uint8Array) {
self.0.prefix_with(&prefix.to_vec());
}
#[wasm_bindgen]
pub fn update(&mut self, data: &Uint8Array) {
let data_vec = data.to_vec();
self.0.update(&data_vec);
}
#[wasm_bindgen(js_name = sum)]
pub fn sum(&self) -> Uint8Array {
let hash = self.0.sum();
let result = Uint8Array::new_with_length(32);
result.copy_from(hash.as_slice());
result
}
#[wasm_bindgen(js_name = generateProof)]
pub fn generate_proof(
&self,
data: &Uint8Array,
segment_index: usize,
) -> Result<WasmProof, JsValue> {
match self.0.generate_proof(&data.to_vec(), segment_index) {
Ok(proof) => Ok(WasmProof(proof)),
Err(e) => Err(JsValue::from_str(&e.to_string())),
}
}
#[wasm_bindgen(js_name = verifyProof, static_method_of = Hasher)]
pub fn verify_proof(proof: &WasmProof, root_hash: &Uint8Array) -> Result<bool, JsValue> {
match Hasher::verify_proof(&proof.0, &root_hash.to_vec()) {
Ok(result) => Ok(result),
Err(e) => Err(JsValue::from_str(&e.to_string())),
}
}
}
#[wasm_bindgen(js_name = Proof)]
pub struct WasmProof(pub(crate) Proof);
#[wasm_bindgen(js_class = Proof)]
impl WasmProof {
#[wasm_bindgen(js_name = segmentIndex)]
pub fn segment_index(&self) -> usize {
self.0.segment_index
}
#[wasm_bindgen]
pub fn segment(&self) -> Uint8Array {
let result = Uint8Array::new_with_length(32);
result.copy_from(self.0.segment.as_slice());
result
}
#[wasm_bindgen(js_name = proofSegments)]
pub fn proof_segments(&self) -> Array {
let result = Array::new();
for segment in &self.0.proof_segments {
let segment_array = Uint8Array::new_with_length(32);
segment_array.copy_from(segment.as_slice());
result.push(&segment_array);
}
result
}
#[wasm_bindgen]
pub fn span(&self) -> u64 {
self.0.span
}
#[wasm_bindgen]
pub fn verify(&self, root_hash: &Uint8Array) -> Result<bool, JsValue> {
match self.0.verify(&root_hash.to_vec()) {
Ok(result) => Ok(result),
Err(e) => Err(JsValue::from_str(&e.to_string())),
}
}
}