Added wasm bindings, modified format to have version in share rather than secret and remove some baggage from the encoded share. This is an incompatible change

This commit is contained in:
2024-07-07 21:45:59 +02:00
parent b1dfd56446
commit 937b8eb6b7
11 changed files with 218 additions and 111 deletions

15
rssss-wasm/Cargo.toml Normal file
View File

@@ -0,0 +1,15 @@
[package]
name = "rssss-wasm"
version = "0.1.0"
edition = "2021"
[lib]
crate-type=["cdylib"]
[dependencies]
wasm-bindgen = "0.2.92"
rssss = {path = "../rssss"}
rand = { version = "0.8.5", default-features = false, features = ["getrandom"] }
getrandom = { version = "0.2.15", default-features = false, features = ["js"] }
anyhow = "1.0.86"
thiserror = "1.0.61"

91
rssss-wasm/src/lib.rs Normal file
View File

@@ -0,0 +1,91 @@
use rand::Rng;
use wasm_bindgen::prelude::*;
use rssss::poly::{Poly, UniformPoly};
use rssss::gf256::GF256;
use rssss::s4;
#[wasm_bindgen]
pub struct ShareGenerator {
poly: Vec<Poly<GF256>>,
last_share: u8,
}
// Share format: [0, min_shares, *data]
impl ShareGenerator {
pub fn new_from_vec(min_shares: u8, secret: Vec<u8>) -> Self {
let mut secret_buf = Vec::with_capacity(secret.len() + 5);
let secret = s4::Secret::new(secret);
secret.to_buf(&mut secret_buf);
let mut rng = rand::rngs::OsRng;
let mut poly = Vec::with_capacity(secret.len());
for c in secret_buf.iter().copied() {
poly.push(rng.sample(UniformPoly { intercept: GF256::from(c), degree: min_shares as usize - 1 }))
}
Self{
poly,
last_share: 0,
}
}
}
#[wasm_bindgen]
impl ShareGenerator {
#[wasm_bindgen(constructor)]
pub fn new_from_buf(min_shares: u8, secret: &[u8]) -> Self {
Self::new_from_vec(min_shares, Vec::from(secret))
}
pub fn from_string(min_shares: u8, secret: String) -> Self {
Self::new_from_vec(min_shares, secret.into())
}
pub fn gen_share(&mut self, n: Option<u8>) -> Option<Share> {
let n = if let Some(n) = n {
if self.last_share < n {
self.last_share = n;
}
n
} else {
self.last_share += 1;
self.last_share
};
if n == 0 {
return None
}
let share = s4::Share::new(GF256::from(n), self.poly.as_slice());
Some(Share(share))
}
}
#[wasm_bindgen]
#[repr(transparent)]
pub struct Share(s4::Share<GF256>);
#[wasm_bindgen]
impl Share {
pub fn to_blob(&self) -> Box<[u8]> {
let mut ret = Vec::with_capacity(self.0.y.len() + 1);
self.0.write_to(&mut ret).unwrap();
ret.into_boxed_slice()
}
pub fn from_blob(blob: &[u8]) -> Result<Share, String> {
s4::Share::<GF256>::read_from(blob)
.map(Share)
.map_err(|err| format!("{}", err))
}
#[wasm_bindgen(getter)]
pub fn x(&self) -> usize {
usize::from(self.0.x)
}
}