Skip to content

Commit

Permalink
Merge pull request #2269 from b-zee/feat-vault-user-data-wasm
Browse files Browse the repository at this point in the history
feat vault user data wasm
  • Loading branch information
b-zee authored Oct 22, 2024
2 parents a5df15f + 284608d commit b5917e8
Show file tree
Hide file tree
Showing 4 changed files with 114 additions and 51 deletions.
42 changes: 21 additions & 21 deletions autonomi/src/client/archive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,12 @@ impl Default for Metadata {
}

impl Archive {
/// Deserialize from bytes.
pub fn from_bytes(data: Bytes) -> Result<Archive, rmp_serde::decode::Error> {
let root: Archive = rmp_serde::from_slice(&data[..])?;

Ok(root)
}

/// Serialize to bytes.
pub fn into_bytes(&self) -> Result<Bytes, rmp_serde::encode::Error> {
let root_serialized = rmp_serde::to_vec(&self)?;
let root_serialized = Bytes::from(root_serialized);

Ok(root_serialized)
/// Create a new emtpy local archive
/// Note that this does not upload the archive to the network
pub fn new() -> Self {
Self {
map: HashMap::new(),
}
}

/// Rename a file in an archive
Expand All @@ -99,14 +92,6 @@ impl Archive {
Ok(())
}

/// Create a new emtpy local archive
/// Note that this does not upload the archive to the network
pub fn new() -> Self {
Self {
map: HashMap::new(),
}
}

/// Add a file to a local archive
/// Note that this does not upload the archive to the network
pub fn add_file(&mut self, path: PathBuf, data_addr: DataAddr, meta: Metadata) {
Expand Down Expand Up @@ -144,6 +129,21 @@ impl Archive {
pub fn map(&self) -> &HashMap<PathBuf, (DataAddr, Metadata)> {
&self.map
}

/// Deserialize from bytes.
pub fn from_bytes(data: Bytes) -> Result<Archive, rmp_serde::decode::Error> {
let root: Archive = rmp_serde::from_slice(&data[..])?;

Ok(root)
}

/// Serialize to bytes.
pub fn into_bytes(&self) -> Result<Bytes, rmp_serde::encode::Error> {
let root_serialized = rmp_serde::to_vec(&self)?;
let root_serialized = Bytes::from(root_serialized);

Ok(root_serialized)
}
}

impl Client {
Expand Down
33 changes: 23 additions & 10 deletions autonomi/src/client/vault_user_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
// permissions and limitations relating to use of the SAFE Network Software.

use std::collections::HashMap;
use std::collections::HashSet;

use super::archive::ArchiveAddr;
use super::data::GetError;
Expand Down Expand Up @@ -35,15 +34,10 @@ pub static USER_DATA_VAULT_CONTENT_IDENTIFIER: LazyLock<VaultContentType> =
pub struct UserData {
/// The register secret key hex encoded
pub register_sk: Option<String>,
/// Owned register addresses
pub registers: HashSet<RegisterAddress>,
/// Owned file archive addresses
pub file_archives: HashSet<ArchiveAddr>,

/// Owner register names, providing it is optional
pub register_names: HashMap<String, RegisterAddress>,
/// Owned file archive addresses along with a name for that archive providing it is optional
pub file_archive_names: HashMap<String, ArchiveAddr>,
/// Owned register addresses, along with their names (can be empty)
pub registers: HashMap<RegisterAddress, String>,
/// Owned file archive addresses, along with their names (can be empty)
pub file_archives: HashMap<ArchiveAddr, String>,
}

/// Errors that can occur during the get operation.
Expand All @@ -65,6 +59,25 @@ impl UserData {
Self::default()
}

/// Add an archive. Returning `Option::Some` with the old name if the archive was already in the set.
pub fn add_file_archive(&mut self, archive: ArchiveAddr) -> Option<String> {
self.file_archives.insert(archive, "".into())
}

/// Add an archive. Returning `Option::Some` with the old name if the archive was already in the set.
pub fn add_file_archive_with_name(
&mut self,
archive: ArchiveAddr,
name: String,
) -> Option<String> {
self.file_archives.insert(archive, name)
}

/// Remove an archive. Returning `Option::Some` with the old name if the archive was already in the set.
pub fn remove_file_archive(&mut self, archive: ArchiveAddr) -> Option<String> {
self.file_archives.remove(&archive)
}

/// To bytes
pub fn to_bytes(&self) -> Result<Bytes, rmp_serde::encode::Error> {
let bytes = rmp_serde::to_vec(&self)?;
Expand Down
74 changes: 58 additions & 16 deletions autonomi/src/client/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ use wasm_bindgen::prelude::*;
use super::address::{addr_to_str, str_to_addr};
use super::vault_user_data::UserData;

#[wasm_bindgen(js_name = UserData)]
pub struct JsUserData(UserData);

#[wasm_bindgen(js_name = Client)]
pub struct JsClient(super::Client);

Expand Down Expand Up @@ -141,44 +138,89 @@ mod vault {
use super::*;
use bls::SecretKey;

#[wasm_bindgen(js_name = UserData)]
pub struct JsUserData(UserData);

#[wasm_bindgen(js_class = UserData)]
impl JsUserData {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
Self(UserData::new())
}

#[wasm_bindgen(js_name = addFileArchive)]
pub fn add_file_archive(
&mut self,
archive: String,
name: Option<String>,
) -> Result<(), JsError> {
let archive = str_to_addr(&archive)?;

let old_name = if let Some(ref name) = name {
self.0.add_file_archive_with_name(archive, name.clone())
} else {
self.0.add_file_archive(archive)
};

if let Some(old_name) = old_name {
tracing::warn!(
"Changing name of archive `{archive}` from `{old_name:?}` to `{name:?}`"
);
}

Ok(())
}

#[wasm_bindgen(js_name = removeFileArchive)]
pub fn remove_file_archive(&mut self, archive: String) -> Result<(), JsError> {
let archive = str_to_addr(&archive)?;
self.0.remove_file_archive(archive);

Ok(())
}

#[wasm_bindgen(js_name = fileArchives)]
pub fn file_archives(&self) -> Result<JsValue, JsError> {
let archives = serde_wasm_bindgen::to_value(&self.0.file_archives)?;
Ok(archives)
}
}

#[wasm_bindgen(js_class = Client)]
impl JsClient {
#[wasm_bindgen(js_name = getUserDataFromVault)]
pub async fn get_user_data_from_vault(
&self,
secret_key: Vec<u8>,
secret_key: &SecretKeyJs,
) -> Result<JsUserData, JsError> {
let secret_key: [u8; 32] = secret_key[..].try_into()?;
let secret_key = SecretKey::from_bytes(secret_key)?;

let user_data = self.0.get_user_data_from_vault(&secret_key).await?;
let user_data = self.0.get_user_data_from_vault(&secret_key.0).await?;

Ok(JsUserData(user_data))
}

#[wasm_bindgen(js_name = putUserDataToVault)]
pub async fn put_user_data_to_vault(
&self,
user_data: JsUserData,
user_data: &JsUserData,
wallet: &JsWallet,
secret_key: Vec<u8>,
secret_key: &SecretKeyJs,
) -> Result<(), JsError> {
let secret_key: [u8; 32] = secret_key[..].try_into()?;
let secret_key = SecretKey::from_bytes(secret_key)?;

self.0
.put_user_data_to_vault(&secret_key, &wallet.0, user_data.0)
.put_user_data_to_vault(&secret_key.0, &wallet.0, user_data.0.clone())
.await?;

Ok(())
}
}
}

#[wasm_bindgen(js_name = SecretKey)]
pub struct SecretKeyJs(bls::SecretKey);

#[wasm_bindgen(js_name = genSecretKey)]
pub fn gen_secret_key() -> Vec<u8> {
pub fn gen_secret_key() -> SecretKeyJs {
let secret_key = bls::SecretKey::random();
secret_key.to_bytes().to_vec()
SecretKeyJs(secret_key)
}

#[wasm_bindgen(js_name = Wallet)]
Expand Down
16 changes: 12 additions & 4 deletions autonomi/tests-js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,21 @@ describe('autonomi', function () {
assert.deepEqual(archive, archiveFetched);
});

it('writes bytes to vault and fetches it', async () => {
it('writes archive to vault and fetches it', async () => {
const addr = "0000000000000000000000000000000000000000000000000000000000000000"; // Dummy data address
const data = randomData(32);
const secretKey = atnm.genSecretKey();

await client.writeBytesToVault(data, wallet, secretKey);
const dataFetched = await client.fetchAndDecryptVault(secretKey);
const archive = new atnm.Archive();
archive.addNewFile('foo', addr);
const archiveAddr = await client.archivePut(archive, wallet);

const userData = new atnm.UserData();
userData.addFileArchive(archiveAddr, 'foo');

assert.deepEqual(data, dataFetched);
await client.putUserDataToVault(userData, wallet, secretKey);
const userDataFetched = await client.getUserDataFromVault(secretKey);

assert.deepEqual(userDataFetched.fileArchives(), userData.fileArchives());
});
});

0 comments on commit b5917e8

Please sign in to comment.