diff --git a/veilid-cli/src/client_api_connection.rs b/veilid-cli/src/client_api_connection.rs index 7a79dcd4..b2681257 100644 --- a/veilid-cli/src/client_api_connection.rs +++ b/veilid-cli/src/client_api_connection.rs @@ -38,7 +38,7 @@ fn map_to_internal_error(e: T) -> VeilidAPIError { fn decode_api_result( reader: &api_result::Reader, -) -> Result { +) -> VeilidAPIResult { match reader.which().map_err(map_to_internal_error)? { api_result::Which::Ok(v) => { let ok_val = v.map_err(map_to_internal_error)?; @@ -355,7 +355,7 @@ impl ClientApiConnection { .map_err(map_to_string)? .get_result() .map_err(map_to_string)?; - let res: Result<(), VeilidAPIError> = decode_api_result(&reader); + let res: VeilidAPIResult<()> = decode_api_result(&reader); res.map_err(map_to_string) } @@ -379,7 +379,7 @@ impl ClientApiConnection { .map_err(map_to_string)? .get_result() .map_err(map_to_string)?; - let res: Result<(), VeilidAPIError> = decode_api_result(&reader); + let res: VeilidAPIResult<()> = decode_api_result(&reader); res.map_err(map_to_string) } @@ -422,7 +422,7 @@ impl ClientApiConnection { .map_err(map_to_string)? .get_result() .map_err(map_to_string)?; - let res: Result = decode_api_result(&reader); + let res: VeilidAPIResult = decode_api_result(&reader); res.map_err(map_to_string) } @@ -453,7 +453,7 @@ impl ClientApiConnection { .map_err(map_to_string)? .get_result() .map_err(map_to_string)?; - let res: Result<(), VeilidAPIError> = decode_api_result(&reader); + let res: VeilidAPIResult<()> = decode_api_result(&reader); res.map_err(map_to_string) } @@ -483,7 +483,7 @@ impl ClientApiConnection { .map_err(map_to_string)? .get_result() .map_err(map_to_string)?; - let res: Result<(), VeilidAPIError> = decode_api_result(&reader); + let res: VeilidAPIResult<()> = decode_api_result(&reader); res.map_err(map_to_string) } diff --git a/veilid-core/src/core_context.rs b/veilid-core/src/core_context.rs index 52983521..97096083 100644 --- a/veilid-core/src/core_context.rs +++ b/veilid-core/src/core_context.rs @@ -206,7 +206,7 @@ impl VeilidCoreContext { async fn new_with_config_callback( update_callback: UpdateCallback, config_callback: ConfigCallback, - ) -> Result { + ) -> VeilidAPIResult { // Set up config from callback trace!("setup config with callback"); let mut config = VeilidConfig::new(); @@ -219,7 +219,7 @@ impl VeilidCoreContext { async fn new_with_config_json( update_callback: UpdateCallback, config_json: String, - ) -> Result { + ) -> VeilidAPIResult { // Set up config from callback trace!("setup config with json"); let mut config = VeilidConfig::new(); @@ -231,7 +231,7 @@ impl VeilidCoreContext { async fn new_common( update_callback: UpdateCallback, config: VeilidConfig, - ) -> Result { + ) -> VeilidAPIResult { cfg_if! { if #[cfg(target_os = "android")] { if !crate::intf::android::is_android_ready() { @@ -281,7 +281,7 @@ lazy_static::lazy_static! { pub async fn api_startup( update_callback: UpdateCallback, config_callback: ConfigCallback, -) -> Result { +) -> VeilidAPIResult { // See if we have an API started up already let mut initialized_lock = INITIALIZED.lock().await; if *initialized_lock { @@ -304,7 +304,7 @@ pub async fn api_startup( pub async fn api_startup_json( update_callback: UpdateCallback, config_json: String, -) -> Result { +) -> VeilidAPIResult { // See if we have an API started up already let mut initialized_lock = INITIALIZED.lock().await; if *initialized_lock { diff --git a/veilid-core/src/crypto/byte_array_types.rs b/veilid-core/src/crypto/byte_array_types.rs index 4e8018c8..8a1f7a01 100644 --- a/veilid-core/src/crypto/byte_array_types.rs +++ b/veilid-core/src/crypto/byte_array_types.rs @@ -66,11 +66,11 @@ where { fn encode(&self) -> String; fn encoded_len() -> usize; - fn try_decode>(input: S) -> Result { + fn try_decode>(input: S) -> VeilidAPIResult { let b = input.as_ref().as_bytes(); Self::try_decode_bytes(b) } - fn try_decode_bytes(b: &[u8]) -> Result; + fn try_decode_bytes(b: &[u8]) -> VeilidAPIResult; } ////////////////////////////////////////////////////////////////////// @@ -180,7 +180,7 @@ macro_rules! byte_array_type { fn encoded_len() -> usize { $encoded_size } - fn try_decode_bytes(b: &[u8]) -> Result { + fn try_decode_bytes(b: &[u8]) -> VeilidAPIResult { let mut bytes = [0u8; $size]; let res = BASE64URL_NOPAD.decode_len(b.len()); match res { diff --git a/veilid-core/src/crypto/crypto_system.rs b/veilid-core/src/crypto/crypto_system.rs index 70967e04..c2a65695 100644 --- a/veilid-core/src/crypto/crypto_system.rs +++ b/veilid-core/src/crypto/crypto_system.rs @@ -6,36 +6,20 @@ pub trait CryptoSystem { fn crypto(&self) -> Crypto; // Cached Operations - fn cached_dh( - &self, - key: &PublicKey, - secret: &SecretKey, - ) -> Result; + fn cached_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult; // Generation fn random_bytes(&self, len: u32) -> Vec; fn default_salt_length(&self) -> u32; - fn hash_password(&self, password: &[u8], salt: &[u8]) -> Result; - fn verify_password(&self, password: &[u8], password_hash: &str) - -> Result; - fn derive_shared_secret( - &self, - password: &[u8], - salt: &[u8], - ) -> Result; + fn hash_password(&self, password: &[u8], salt: &[u8]) -> VeilidAPIResult; + fn verify_password(&self, password: &[u8], password_hash: &str) -> VeilidAPIResult; + fn derive_shared_secret(&self, password: &[u8], salt: &[u8]) -> VeilidAPIResult; fn random_nonce(&self) -> Nonce; fn random_shared_secret(&self) -> SharedSecret; - fn compute_dh( - &self, - key: &PublicKey, - secret: &SecretKey, - ) -> Result; + fn compute_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult; fn generate_keypair(&self) -> KeyPair; fn generate_hash(&self, data: &[u8]) -> HashDigest; - fn generate_hash_reader( - &self, - reader: &mut dyn std::io::Read, - ) -> Result; + fn generate_hash_reader(&self, reader: &mut dyn std::io::Read) -> VeilidAPIResult; // Validation fn validate_keypair(&self, key: &PublicKey, secret: &SecretKey) -> bool; @@ -44,24 +28,14 @@ pub trait CryptoSystem { &self, reader: &mut dyn std::io::Read, hash: &HashDigest, - ) -> Result; + ) -> VeilidAPIResult; // Distance Metric fn distance(&self, key1: &CryptoKey, key2: &CryptoKey) -> CryptoKeyDistance; // Authentication - fn sign( - &self, - key: &PublicKey, - secret: &SecretKey, - data: &[u8], - ) -> Result; - fn verify( - &self, - key: &PublicKey, - data: &[u8], - signature: &Signature, - ) -> Result<(), VeilidAPIError>; + fn sign(&self, key: &PublicKey, secret: &SecretKey, data: &[u8]) -> VeilidAPIResult; + fn verify(&self, key: &PublicKey, data: &[u8], signature: &Signature) -> VeilidAPIResult<()>; // AEAD Encrypt/Decrypt fn aead_overhead(&self) -> usize; @@ -71,28 +45,28 @@ pub trait CryptoSystem { nonce: &Nonce, shared_secret: &SharedSecret, associated_data: Option<&[u8]>, - ) -> Result<(), VeilidAPIError>; + ) -> VeilidAPIResult<()>; fn decrypt_aead( &self, body: &[u8], nonce: &Nonce, shared_secret: &SharedSecret, associated_data: Option<&[u8]>, - ) -> Result, VeilidAPIError>; + ) -> VeilidAPIResult>; fn encrypt_in_place_aead( &self, body: &mut Vec, nonce: &Nonce, shared_secret: &SharedSecret, associated_data: Option<&[u8]>, - ) -> Result<(), VeilidAPIError>; + ) -> VeilidAPIResult<()>; fn encrypt_aead( &self, body: &[u8], nonce: &Nonce, shared_secret: &SharedSecret, associated_data: Option<&[u8]>, - ) -> Result, VeilidAPIError>; + ) -> VeilidAPIResult>; // NoAuth Encrypt/Decrypt fn crypt_in_place_no_auth( diff --git a/veilid-core/src/crypto/envelope.rs b/veilid-core/src/crypto/envelope.rs index 4a043588..c123ea52 100644 --- a/veilid-core/src/crypto/envelope.rs +++ b/veilid-core/src/crypto/envelope.rs @@ -66,7 +66,7 @@ impl Envelope { } } - pub fn from_signed_data(crypto: Crypto, data: &[u8]) -> Result { + pub fn from_signed_data(crypto: Crypto, data: &[u8]) -> VeilidAPIResult { // Ensure we are at least the length of the envelope // Silent drop here, as we use zero length packets as part of the protocol for hole punching if data.len() < MIN_ENVELOPE_SIZE { @@ -175,7 +175,7 @@ impl Envelope { crypto: Crypto, data: &[u8], node_id_secret: &SecretKey, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { // Get DH secret let vcrypto = crypto .get(self.crypto_kind) @@ -197,7 +197,7 @@ impl Envelope { crypto: Crypto, body: &[u8], node_id_secret: &SecretKey, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { // Ensure body isn't too long let envelope_size: usize = body.len() + MIN_ENVELOPE_SIZE; if envelope_size > MAX_ENVELOPE_SIZE { diff --git a/veilid-core/src/crypto/mod.rs b/veilid-core/src/crypto/mod.rs index 816c9515..be5879a3 100644 --- a/veilid-core/src/crypto/mod.rs +++ b/veilid-core/src/crypto/mod.rs @@ -146,7 +146,7 @@ impl Crypto { if let Err(e) = self .unlocked_inner .config - .init_node_ids(self.clone(), self.unlocked_inner.protected_store.clone()) + .init_node_ids(self.clone(), table_store.clone()) .await { return Err(e).wrap_err("init node id failed"); @@ -267,7 +267,7 @@ impl Crypto { node_ids: &[TypedKey], data: &[u8], typed_signatures: &[TypedSignature], - ) -> Result { + ) -> VeilidAPIResult { let mut out = TypedKeySet::with_capacity(node_ids.len()); for sig in typed_signatures { for nid in node_ids { @@ -290,7 +290,7 @@ impl Crypto { data: &[u8], typed_key_pairs: &[TypedKeyPair], transform: F, - ) -> Result, VeilidAPIError> + ) -> VeilidAPIResult> where F: Fn(&TypedKeyPair, Signature) -> R, { @@ -306,7 +306,7 @@ impl Crypto { /// Generate keypair /// Does not require startup/init - pub fn generate_keypair(crypto_kind: CryptoKind) -> Result { + pub fn generate_keypair(crypto_kind: CryptoKind) -> VeilidAPIResult { #[cfg(feature = "enable-crypto-vld0")] if crypto_kind == CRYPTO_KIND_VLD0 { let kp = vld0_generate_keypair(); @@ -327,7 +327,7 @@ impl Crypto { vcrypto: &T, key: &PublicKey, secret: &SecretKey, - ) -> Result { + ) -> VeilidAPIResult { Ok( match self.inner.lock().dh_cache.entry( DHCacheKey { diff --git a/veilid-core/src/crypto/none/mod.rs b/veilid-core/src/crypto/none/mod.rs index 9b92783c..b81056b6 100644 --- a/veilid-core/src/crypto/none/mod.rs +++ b/veilid-core/src/crypto/none/mod.rs @@ -71,11 +71,7 @@ impl CryptoSystem for CryptoSystemNONE { } // Cached Operations - fn cached_dh( - &self, - key: &PublicKey, - secret: &SecretKey, - ) -> Result { + fn cached_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult { self.crypto .cached_dh_internal::(self, key, secret) } @@ -89,7 +85,7 @@ impl CryptoSystem for CryptoSystemNONE { fn default_salt_length(&self) -> u32 { 4 } - fn hash_password(&self, password: &[u8], salt: &[u8]) -> Result { + fn hash_password(&self, password: &[u8], salt: &[u8]) -> VeilidAPIResult { if salt.len() < Salt::MIN_LENGTH || salt.len() > Salt::MAX_LENGTH { apibail_generic!("invalid salt length"); } @@ -99,11 +95,7 @@ impl CryptoSystem for CryptoSystemNONE { BASE64URL_NOPAD.encode(password) )) } - fn verify_password( - &self, - password: &[u8], - password_hash: &str, - ) -> Result { + fn verify_password(&self, password: &[u8], password_hash: &str) -> VeilidAPIResult { let Some((salt, _)) = password_hash.split_once(":") else { apibail_generic!("invalid format"); }; @@ -113,11 +105,7 @@ impl CryptoSystem for CryptoSystemNONE { return Ok(&self.hash_password(password, &salt)? == password_hash); } - fn derive_shared_secret( - &self, - password: &[u8], - salt: &[u8], - ) -> Result { + fn derive_shared_secret(&self, password: &[u8], salt: &[u8]) -> VeilidAPIResult { if salt.len() < Salt::MIN_LENGTH || salt.len() > Salt::MAX_LENGTH { apibail_generic!("invalid salt length"); } @@ -136,11 +124,7 @@ impl CryptoSystem for CryptoSystemNONE { random_bytes(&mut s).unwrap(); SharedSecret::new(s) } - fn compute_dh( - &self, - key: &PublicKey, - secret: &SecretKey, - ) -> Result { + fn compute_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult { let s = do_xor_32(&key.bytes, &secret.bytes); Ok(SharedSecret::new(s)) } @@ -150,10 +134,7 @@ impl CryptoSystem for CryptoSystemNONE { fn generate_hash(&self, data: &[u8]) -> PublicKey { PublicKey::new(*blake3::hash(data).as_bytes()) } - fn generate_hash_reader( - &self, - reader: &mut dyn std::io::Read, - ) -> Result { + fn generate_hash_reader(&self, reader: &mut dyn std::io::Read) -> VeilidAPIResult { let mut hasher = blake3::Hasher::new(); std::io::copy(reader, &mut hasher).map_err(VeilidAPIError::generic)?; Ok(PublicKey::new(*hasher.finalize().as_bytes())) @@ -178,7 +159,7 @@ impl CryptoSystem for CryptoSystemNONE { &self, reader: &mut dyn std::io::Read, dht_key: &PublicKey, - ) -> Result { + ) -> VeilidAPIResult { let mut hasher = blake3::Hasher::new(); std::io::copy(reader, &mut hasher).map_err(VeilidAPIError::generic)?; let bytes = *hasher.finalize().as_bytes(); @@ -201,7 +182,7 @@ impl CryptoSystem for CryptoSystemNONE { dht_key: &PublicKey, dht_key_secret: &SecretKey, data: &[u8], - ) -> Result { + ) -> VeilidAPIResult { if !is_bytes_eq_32(&do_xor_32(&dht_key.bytes, &dht_key_secret.bytes), 0xFFu8) { return Err(VeilidAPIError::parse_error( "Keypair is invalid", @@ -224,7 +205,7 @@ impl CryptoSystem for CryptoSystemNONE { dht_key: &PublicKey, data: &[u8], signature: &Signature, - ) -> Result<(), VeilidAPIError> { + ) -> VeilidAPIResult<()> { let mut dig = Blake3Digest512::new(); dig.update(data); let sig = dig.finalize(); @@ -261,7 +242,7 @@ impl CryptoSystem for CryptoSystemNONE { nonce: &Nonce, shared_secret: &SharedSecret, _associated_data: Option<&[u8]>, - ) -> Result<(), VeilidAPIError> { + ) -> VeilidAPIResult<()> { let mut blob = nonce.bytes.to_vec(); blob.extend_from_slice(&[0u8; 8]); let blob = do_xor_32(&blob, &shared_secret.bytes); @@ -283,7 +264,7 @@ impl CryptoSystem for CryptoSystemNONE { nonce: &Nonce, shared_secret: &SharedSecret, associated_data: Option<&[u8]>, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { let mut out = body.to_vec(); self.decrypt_in_place_aead(&mut out, nonce, shared_secret, associated_data) .map_err(map_to_string) @@ -297,7 +278,7 @@ impl CryptoSystem for CryptoSystemNONE { nonce: &Nonce, shared_secret: &SharedSecret, _associated_data: Option<&[u8]>, - ) -> Result<(), VeilidAPIError> { + ) -> VeilidAPIResult<()> { let mut blob = nonce.bytes.to_vec(); blob.extend_from_slice(&[0u8; 8]); let blob = do_xor_32(&blob, &shared_secret.bytes); @@ -312,7 +293,7 @@ impl CryptoSystem for CryptoSystemNONE { nonce: &Nonce, shared_secret: &SharedSecret, associated_data: Option<&[u8]>, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { let mut out = body.to_vec(); self.encrypt_in_place_aead(&mut out, nonce, shared_secret, associated_data) .map_err(map_to_string) diff --git a/veilid-core/src/crypto/receipt.rs b/veilid-core/src/crypto/receipt.rs index 50496d04..4f8d4b15 100644 --- a/veilid-core/src/crypto/receipt.rs +++ b/veilid-core/src/crypto/receipt.rs @@ -49,7 +49,7 @@ impl Receipt { nonce: Nonce, sender_id: PublicKey, extra_data: D, - ) -> Result { + ) -> VeilidAPIResult { assert!(VALID_ENVELOPE_VERSIONS.contains(&version)); assert!(VALID_CRYPTO_KINDS.contains(&crypto_kind)); @@ -68,7 +68,7 @@ impl Receipt { }) } - pub fn from_signed_data(crypto: Crypto, data: &[u8]) -> Result { + pub fn from_signed_data(crypto: Crypto, data: &[u8]) -> VeilidAPIResult { // Ensure we are at least the length of the envelope if data.len() < MIN_RECEIPT_SIZE { apibail_parse_error!("receipt too small", data.len()); @@ -153,11 +153,7 @@ impl Receipt { }) } - pub fn to_signed_data( - &self, - crypto: Crypto, - secret: &SecretKey, - ) -> Result, VeilidAPIError> { + pub fn to_signed_data(&self, crypto: Crypto, secret: &SecretKey) -> VeilidAPIResult> { // Ensure extra data isn't too long let receipt_size: usize = self.extra_data.len() + MIN_RECEIPT_SIZE; if receipt_size > MAX_RECEIPT_SIZE { diff --git a/veilid-core/src/crypto/types/keypair.rs b/veilid-core/src/crypto/types/keypair.rs index 0ea30b23..fc53af44 100644 --- a/veilid-core/src/crypto/types/keypair.rs +++ b/veilid-core/src/crypto/types/keypair.rs @@ -39,7 +39,7 @@ impl Encodable for KeyPair { fn encoded_len() -> usize { PublicKey::encoded_len() + 1 + SecretKey::encoded_len() } - fn try_decode_bytes(b: &[u8]) -> Result { + fn try_decode_bytes(b: &[u8]) -> VeilidAPIResult { if b.len() != Self::encoded_len() { apibail_parse_error!("input has wrong encoded length", format!("len={}", b.len())); } diff --git a/veilid-core/src/crypto/vld0/mod.rs b/veilid-core/src/crypto/vld0/mod.rs index 9bd65567..5d3a30bf 100644 --- a/veilid-core/src/crypto/vld0/mod.rs +++ b/veilid-core/src/crypto/vld0/mod.rs @@ -17,7 +17,7 @@ use x25519_dalek as xd; const AEAD_OVERHEAD: usize = 16; pub const CRYPTO_KIND_VLD0: CryptoKind = FourCC([b'V', b'L', b'D', b'0']); -fn ed25519_to_x25519_pk(key: &ed::PublicKey) -> Result { +fn ed25519_to_x25519_pk(key: &ed::PublicKey) -> VeilidAPIResult { let bytes = key.to_bytes(); let compressed = cd::edwards::CompressedEdwardsY(bytes); let point = compressed @@ -26,7 +26,7 @@ fn ed25519_to_x25519_pk(key: &ed::PublicKey) -> Result Result { +fn ed25519_to_x25519_sk(key: &ed::SecretKey) -> VeilidAPIResult { let exp = ed::ExpandedSecretKey::from(key); let bytes: [u8; ed::EXPANDED_SECRET_KEY_LENGTH] = exp.to_bytes(); let lowbytes: [u8; 32] = bytes[0..32].try_into().map_err(VeilidAPIError::internal)?; @@ -65,11 +65,7 @@ impl CryptoSystem for CryptoSystemVLD0 { } // Cached Operations - fn cached_dh( - &self, - key: &PublicKey, - secret: &SecretKey, - ) -> Result { + fn cached_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult { self.crypto .cached_dh_internal::(self, key, secret) } @@ -83,7 +79,7 @@ impl CryptoSystem for CryptoSystemVLD0 { fn default_salt_length(&self) -> u32 { 16 } - fn hash_password(&self, password: &[u8], salt: &[u8]) -> Result { + fn hash_password(&self, password: &[u8], salt: &[u8]) -> VeilidAPIResult { if salt.len() < Salt::MIN_LENGTH || salt.len() > Salt::MAX_LENGTH { apibail_generic!("invalid salt length"); } @@ -100,11 +96,7 @@ impl CryptoSystem for CryptoSystemVLD0 { .to_string(); Ok(password_hash) } - fn verify_password( - &self, - password: &[u8], - password_hash: &str, - ) -> Result { + fn verify_password(&self, password: &[u8], password_hash: &str) -> VeilidAPIResult { let parsed_hash = PasswordHash::new(password_hash).map_err(VeilidAPIError::generic)?; // Argon2 with default params (Argon2id v19) let argon2 = Argon2::default(); @@ -112,11 +104,7 @@ impl CryptoSystem for CryptoSystemVLD0 { Ok(argon2.verify_password(password, &parsed_hash).is_ok()) } - fn derive_shared_secret( - &self, - password: &[u8], - salt: &[u8], - ) -> Result { + fn derive_shared_secret(&self, password: &[u8], salt: &[u8]) -> VeilidAPIResult { if salt.len() < Salt::MIN_LENGTH || salt.len() > Salt::MAX_LENGTH { apibail_generic!("invalid salt length"); } @@ -141,11 +129,7 @@ impl CryptoSystem for CryptoSystemVLD0 { random_bytes(&mut s); SharedSecret::new(s) } - fn compute_dh( - &self, - key: &PublicKey, - secret: &SecretKey, - ) -> Result { + fn compute_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult { let pk_ed = ed::PublicKey::from_bytes(&key.bytes).map_err(VeilidAPIError::internal)?; let pk_xd = ed25519_to_x25519_pk(&pk_ed)?; let sk_ed = ed::SecretKey::from_bytes(&secret.bytes).map_err(VeilidAPIError::internal)?; @@ -158,10 +142,7 @@ impl CryptoSystem for CryptoSystemVLD0 { fn generate_hash(&self, data: &[u8]) -> PublicKey { PublicKey::new(*blake3::hash(data).as_bytes()) } - fn generate_hash_reader( - &self, - reader: &mut dyn std::io::Read, - ) -> Result { + fn generate_hash_reader(&self, reader: &mut dyn std::io::Read) -> VeilidAPIResult { let mut hasher = blake3::Hasher::new(); std::io::copy(reader, &mut hasher).map_err(VeilidAPIError::generic)?; Ok(PublicKey::new(*hasher.finalize().as_bytes())) @@ -187,7 +168,7 @@ impl CryptoSystem for CryptoSystemVLD0 { &self, reader: &mut dyn std::io::Read, dht_key: &PublicKey, - ) -> Result { + ) -> VeilidAPIResult { let mut hasher = blake3::Hasher::new(); std::io::copy(reader, &mut hasher).map_err(VeilidAPIError::generic)?; let bytes = *hasher.finalize().as_bytes(); @@ -210,7 +191,7 @@ impl CryptoSystem for CryptoSystemVLD0 { dht_key: &PublicKey, dht_key_secret: &SecretKey, data: &[u8], - ) -> Result { + ) -> VeilidAPIResult { let mut kpb: [u8; SECRET_KEY_LENGTH + PUBLIC_KEY_LENGTH] = [0u8; SECRET_KEY_LENGTH + PUBLIC_KEY_LENGTH]; @@ -237,7 +218,7 @@ impl CryptoSystem for CryptoSystemVLD0 { dht_key: &PublicKey, data: &[u8], signature: &Signature, - ) -> Result<(), VeilidAPIError> { + ) -> VeilidAPIResult<()> { let pk = ed::PublicKey::from_bytes(&dht_key.bytes) .map_err(|e| VeilidAPIError::parse_error("Public key is invalid", e))?; let sig = ed::Signature::from_bytes(&signature.bytes) @@ -261,7 +242,7 @@ impl CryptoSystem for CryptoSystemVLD0 { nonce: &Nonce, shared_secret: &SharedSecret, associated_data: Option<&[u8]>, - ) -> Result<(), VeilidAPIError> { + ) -> VeilidAPIResult<()> { let key = ch::Key::from(shared_secret.bytes); let xnonce = ch::XNonce::from(nonce.bytes); let aead = ch::XChaCha20Poly1305::new(&key); @@ -276,7 +257,7 @@ impl CryptoSystem for CryptoSystemVLD0 { nonce: &Nonce, shared_secret: &SharedSecret, associated_data: Option<&[u8]>, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { let mut out = body.to_vec(); self.decrypt_in_place_aead(&mut out, nonce, shared_secret, associated_data) .map_err(map_to_string) @@ -290,7 +271,7 @@ impl CryptoSystem for CryptoSystemVLD0 { nonce: &Nonce, shared_secret: &SharedSecret, associated_data: Option<&[u8]>, - ) -> Result<(), VeilidAPIError> { + ) -> VeilidAPIResult<()> { let key = ch::Key::from(shared_secret.bytes); let xnonce = ch::XNonce::from(nonce.bytes); let aead = ch::XChaCha20Poly1305::new(&key); @@ -306,7 +287,7 @@ impl CryptoSystem for CryptoSystemVLD0 { nonce: &Nonce, shared_secret: &SharedSecret, associated_data: Option<&[u8]>, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { let mut out = body.to_vec(); self.encrypt_in_place_aead(&mut out, nonce, shared_secret, associated_data) .map_err(map_to_string) diff --git a/veilid-core/src/intf/mod.rs b/veilid-core/src/intf/mod.rs index ab9d5759..81756b61 100644 --- a/veilid-core/src/intf/mod.rs +++ b/veilid-core/src/intf/mod.rs @@ -9,5 +9,4 @@ mod native; #[cfg(not(target_arch = "wasm32"))] pub use native::*; -pub static KNOWN_PROTECTED_STORE_KEYS: [&'static str; 4] = - ["node_id", "node_id_secret", "_test_key", "RouteSpecStore"]; +pub static KNOWN_PROTECTED_STORE_KEYS: [&'static str; 2] = ["device_encryption_key", "_test_key"]; diff --git a/veilid-core/src/network_manager/types/address.rs b/veilid-core/src/network_manager/types/address.rs index c343c8da..45ec1c98 100644 --- a/veilid-core/src/network_manager/types/address.rs +++ b/veilid-core/src/network_manager/types/address.rs @@ -115,7 +115,7 @@ impl fmt::Display for Address { impl FromStr for Address { type Err = VeilidAPIError; - fn from_str(host: &str) -> Result { + fn from_str(host: &str) -> VeilidAPIResult
{ if let Ok(addr) = Ipv4Addr::from_str(host) { Ok(Address::IPV4(addr)) } else if let Ok(addr) = Ipv6Addr::from_str(host) { diff --git a/veilid-core/src/network_manager/types/dial_info/mod.rs b/veilid-core/src/network_manager/types/dial_info/mod.rs index 4d6a8428..a6a12c69 100644 --- a/veilid-core/src/network_manager/types/dial_info/mod.rs +++ b/veilid-core/src/network_manager/types/dial_info/mod.rs @@ -82,7 +82,7 @@ impl fmt::Display for DialInfo { impl FromStr for DialInfo { type Err = VeilidAPIError; - fn from_str(s: &str) -> Result { + fn from_str(s: &str) -> VeilidAPIResult { let (proto, rest) = s.split_once('|').ok_or_else(|| { VeilidAPIError::parse_error("DialInfo::from_str missing protocol '|' separator", s) })?; @@ -175,7 +175,7 @@ impl DialInfo { socket_address: socket_address.to_canonical(), }) } - pub fn try_ws(socket_address: SocketAddress, url: String) -> Result { + pub fn try_ws(socket_address: SocketAddress, url: String) -> VeilidAPIResult { let split_url = SplitUrl::from_str(&url).map_err(|e| { VeilidAPIError::parse_error(format!("unable to split WS url: {}", e), &url) })?; @@ -199,7 +199,7 @@ impl DialInfo { request: url[5..].to_string(), })) } - pub fn try_wss(socket_address: SocketAddress, url: String) -> Result { + pub fn try_wss(socket_address: SocketAddress, url: String) -> VeilidAPIResult { let split_url = SplitUrl::from_str(&url).map_err(|e| { VeilidAPIError::parse_error(format!("unable to split WSS url: {}", e), &url) })?; @@ -321,7 +321,7 @@ impl DialInfo { pub fn try_vec_from_short, H: AsRef>( short: S, hostname: H, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { let short = short.as_ref(); let hostname = hostname.as_ref(); @@ -348,7 +348,7 @@ impl DialInfo { Self::try_vec_from_url(url) } - pub fn try_vec_from_url>(url: S) -> Result, VeilidAPIError> { + pub fn try_vec_from_url>(url: S) -> VeilidAPIResult> { let url = url.as_ref(); let split_url = SplitUrl::from_str(url) .map_err(|e| VeilidAPIError::parse_error(format!("unable to split url: {}", e), url))?; diff --git a/veilid-core/src/network_manager/types/peer_address.rs b/veilid-core/src/network_manager/types/peer_address.rs index 2ca52329..83df0bea 100644 --- a/veilid-core/src/network_manager/types/peer_address.rs +++ b/veilid-core/src/network_manager/types/peer_address.rs @@ -55,7 +55,7 @@ impl fmt::Display for PeerAddress { impl FromStr for PeerAddress { type Err = VeilidAPIError; - fn from_str(s: &str) -> Result { + fn from_str(s: &str) -> VeilidAPIResult { let Some((first, second)) = s.split_once(':') else { return Err(VeilidAPIError::parse_error("PeerAddress is missing a colon: {}", s)); }; diff --git a/veilid-core/src/network_manager/types/protocol_type.rs b/veilid-core/src/network_manager/types/protocol_type.rs index d0ca4c99..4ba47000 100644 --- a/veilid-core/src/network_manager/types/protocol_type.rs +++ b/veilid-core/src/network_manager/types/protocol_type.rs @@ -87,7 +87,7 @@ impl fmt::Display for ProtocolType { impl FromStr for ProtocolType { type Err = VeilidAPIError; - fn from_str(s: &str) -> Result { + fn from_str(s: &str) -> VeilidAPIResult { match s.to_ascii_uppercase().as_str() { "UDP" => Ok(ProtocolType::UDP), "TCP" => Ok(ProtocolType::TCP), diff --git a/veilid-core/src/network_manager/types/socket_address.rs b/veilid-core/src/network_manager/types/socket_address.rs index bbd21c8a..35515b90 100644 --- a/veilid-core/src/network_manager/types/socket_address.rs +++ b/veilid-core/src/network_manager/types/socket_address.rs @@ -69,7 +69,7 @@ impl fmt::Display for SocketAddress { impl FromStr for SocketAddress { type Err = VeilidAPIError; - fn from_str(s: &str) -> Result { + fn from_str(s: &str) -> VeilidAPIResult { let sa = SocketAddr::from_str(s) .map_err(|e| VeilidAPIError::parse_error("Failed to parse SocketAddress", e))?; Ok(SocketAddress::from_socket_addr(sa)) diff --git a/veilid-core/src/routing_table/privacy.rs b/veilid-core/src/routing_table/privacy.rs index 06819993..fc670375 100644 --- a/veilid-core/src/routing_table/privacy.rs +++ b/veilid-core/src/routing_table/privacy.rs @@ -22,7 +22,7 @@ pub enum RouteNode { } impl RouteNode { - pub fn validate(&self, crypto: Crypto) -> Result<(), VeilidAPIError> { + pub fn validate(&self, crypto: Crypto) -> VeilidAPIResult<()> { match self { RouteNode::NodeId(_) => Ok(()), RouteNode::PeerInfo(pi) => pi.validate(crypto), @@ -74,7 +74,7 @@ pub struct RouteHop { pub next_hop: Option, } impl RouteHop { - pub fn validate(&self, crypto: Crypto) -> Result<(), VeilidAPIError> { + pub fn validate(&self, crypto: Crypto) -> VeilidAPIResult<()> { self.node.validate(crypto) } } @@ -91,7 +91,7 @@ pub enum PrivateRouteHops { } impl PrivateRouteHops { - pub fn validate(&self, crypto: Crypto) -> Result<(), VeilidAPIError> { + pub fn validate(&self, crypto: Crypto) -> VeilidAPIResult<()> { match self { PrivateRouteHops::FirstHop(rh) => rh.validate(crypto), PrivateRouteHops::Data(_) => Ok(()), @@ -129,7 +129,7 @@ impl PrivateRoute { } } - pub fn validate(&self, crypto: Crypto) -> Result<(), VeilidAPIError> { + pub fn validate(&self, crypto: Crypto) -> VeilidAPIResult<()> { self.hops.validate(crypto) } diff --git a/veilid-core/src/routing_table/route_spec_store/route_set_spec_detail.rs b/veilid-core/src/routing_table/route_spec_store/route_set_spec_detail.rs index e7858816..7f5c0334 100644 --- a/veilid-core/src/routing_table/route_spec_store/route_set_spec_detail.rs +++ b/veilid-core/src/routing_table/route_spec_store/route_set_spec_detail.rs @@ -6,7 +6,6 @@ pub struct RouteSpecDetail { /// Crypto kind pub crypto_kind: CryptoKind, /// Secret key - #[with(Skip)] pub secret_key: SecretKey, /// Route hops (node id keys) pub hops: Vec, diff --git a/veilid-core/src/routing_table/route_spec_store/route_spec_store_content.rs b/veilid-core/src/routing_table/route_spec_store/route_spec_store_content.rs index c5b1d404..b193c398 100644 --- a/veilid-core/src/routing_table/route_spec_store/route_spec_store_content.rs +++ b/veilid-core/src/routing_table/route_spec_store/route_spec_store_content.rs @@ -55,47 +55,6 @@ impl RouteSpecStoreContent { content.remove_detail(&id); } - // Load secrets from pstore - let pstore = routing_table.network_manager().protected_store(); - let secret_key_map: HashMap = pstore - .load_user_secret_rkyv("RouteSpecStore") - .await? - .unwrap_or_default(); - - // Ensure we got secret keys for all the public keys - let mut got_secret_key_ids = HashSet::new(); - for (rsid, rssd) in content.details.iter_mut() { - let mut found_all = true; - for (pk, rsd) in rssd.iter_route_set_mut() { - if let Some(sk) = secret_key_map.get(pk) { - rsd.secret_key = *sk; - } else { - found_all = false; - break; - } - } - if found_all { - got_secret_key_ids.insert(rsid.clone()); - } - } - - // If we missed any, nuke those route ids - let dead_ids: Vec = content - .details - .keys() - .filter_map(|id| { - if !got_secret_key_ids.contains(id) { - Some(*id) - } else { - None - } - }) - .collect(); - for id in dead_ids { - log_rtab!(debug "missing secret key, killing off private route: {}", id); - content.remove_detail(&id); - } - Ok(content) } @@ -106,18 +65,6 @@ impl RouteSpecStoreContent { let rsstdb = table_store.open("RouteSpecStore", 1).await?; rsstdb.store_rkyv(0, b"content", self).await?; - // Keep secrets in protected store as well - let pstore = routing_table.network_manager().protected_store(); - - let mut out: HashMap = HashMap::new(); - for (_rsid, rssd) in self.details.iter() { - for (pk, rsd) in rssd.iter_route_set() { - out.insert(*pk, rsd.secret_key); - } - } - - let _ = pstore.save_user_secret_rkyv("RouteSpecStore", &out).await?; // ignore if this previously existed or not - Ok(()) } diff --git a/veilid-core/src/routing_table/types/peer_info.rs b/veilid-core/src/routing_table/types/peer_info.rs index 179de3ef..b7037646 100644 --- a/veilid-core/src/routing_table/types/peer_info.rs +++ b/veilid-core/src/routing_table/types/peer_info.rs @@ -16,7 +16,7 @@ impl PeerInfo { } } - pub fn validate(&self, crypto: Crypto) -> Result<(), VeilidAPIError> { + pub fn validate(&self, crypto: Crypto) -> VeilidAPIResult<()> { let validated_node_ids = self.signed_node_info.validate(&self.node_ids, crypto)?; if validated_node_ids.is_empty() { // Shouldn't get here because signed node info validation also checks this diff --git a/veilid-core/src/routing_table/types/signed_direct_node_info.rs b/veilid-core/src/routing_table/types/signed_direct_node_info.rs index ea8ae032..e6fee40d 100644 --- a/veilid-core/src/routing_table/types/signed_direct_node_info.rs +++ b/veilid-core/src/routing_table/types/signed_direct_node_info.rs @@ -20,11 +20,7 @@ impl SignedDirectNodeInfo { } } - pub fn validate( - &self, - node_ids: &TypedKeySet, - crypto: Crypto, - ) -> Result { + pub fn validate(&self, node_ids: &TypedKeySet, crypto: Crypto) -> VeilidAPIResult { let node_info_bytes = Self::make_signature_bytes(&self.node_info, self.timestamp)?; // Verify the signatures that we can @@ -41,7 +37,7 @@ impl SignedDirectNodeInfo { crypto: Crypto, typed_key_pairs: Vec, node_info: NodeInfo, - ) -> Result { + ) -> VeilidAPIResult { let timestamp = get_aligned_timestamp(); let node_info_bytes = Self::make_signature_bytes(&node_info, timestamp)?; let typed_signatures = @@ -58,7 +54,7 @@ impl SignedDirectNodeInfo { fn make_signature_bytes( node_info: &NodeInfo, timestamp: Timestamp, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { let mut node_info_bytes = Vec::new(); // Add nodeinfo to signature diff --git a/veilid-core/src/routing_table/types/signed_node_info.rs b/veilid-core/src/routing_table/types/signed_node_info.rs index 2a98ceae..5557a76a 100644 --- a/veilid-core/src/routing_table/types/signed_node_info.rs +++ b/veilid-core/src/routing_table/types/signed_node_info.rs @@ -8,11 +8,7 @@ pub enum SignedNodeInfo { } impl SignedNodeInfo { - pub fn validate( - &self, - node_ids: &TypedKeySet, - crypto: Crypto, - ) -> Result { + pub fn validate(&self, node_ids: &TypedKeySet, crypto: Crypto) -> VeilidAPIResult { match self { SignedNodeInfo::Direct(d) => d.validate(node_ids, crypto), SignedNodeInfo::Relayed(r) => r.validate(node_ids, crypto), diff --git a/veilid-core/src/routing_table/types/signed_relayed_node_info.rs b/veilid-core/src/routing_table/types/signed_relayed_node_info.rs index 3439baf7..8a429e4c 100644 --- a/veilid-core/src/routing_table/types/signed_relayed_node_info.rs +++ b/veilid-core/src/routing_table/types/signed_relayed_node_info.rs @@ -31,11 +31,7 @@ impl SignedRelayedNodeInfo { } } - pub fn validate( - &self, - node_ids: &TypedKeySet, - crypto: Crypto, - ) -> Result { + pub fn validate(&self, node_ids: &TypedKeySet, crypto: Crypto) -> VeilidAPIResult { // Ensure the relay info for the node has a superset of the crypto kinds of the node it is relaying if common_crypto_kinds( self.node_info.crypto_support(), @@ -68,7 +64,7 @@ impl SignedRelayedNodeInfo { node_info: NodeInfo, relay_ids: TypedKeySet, relay_info: SignedDirectNodeInfo, - ) -> Result { + ) -> VeilidAPIResult { let timestamp = get_aligned_timestamp(); let node_info_bytes = Self::make_signature_bytes(&node_info, &relay_ids, &relay_info, timestamp)?; @@ -90,7 +86,7 @@ impl SignedRelayedNodeInfo { relay_ids: &[TypedKey], relay_info: &SignedDirectNodeInfo, timestamp: Timestamp, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { let mut sig_bytes = Vec::new(); // Add nodeinfo to signature diff --git a/veilid-core/src/storage_manager/get_value.rs b/veilid-core/src/storage_manager/get_value.rs index f41dd578..3d5584e7 100644 --- a/veilid-core/src/storage_manager/get_value.rs +++ b/veilid-core/src/storage_manager/get_value.rs @@ -22,7 +22,7 @@ impl StorageManager { subkey: ValueSubkey, safety_selection: SafetySelection, last_subkey_result: SubkeyResult, - ) -> Result { + ) -> VeilidAPIResult { let routing_table = rpc_processor.routing_table(); // Get the DHT parameters for 'GetValue' @@ -175,7 +175,7 @@ impl StorageManager { } /// Handle a recieved 'Get Value' query - pub async fn inbound_get_value(&self, key: TypedKey, subkey: ValueSubkey, want_descriptor: bool) -> Result, VeilidAPIError> { + pub async fn inbound_get_value(&self, key: TypedKey, subkey: ValueSubkey, want_descriptor: bool) -> VeilidAPIResult> { let mut inner = self.lock().await?; let res = match inner.handle_get_remote_value(key, subkey, want_descriptor).await { Ok(res) => res, diff --git a/veilid-core/src/storage_manager/mod.rs b/veilid-core/src/storage_manager/mod.rs index 9e9810d4..96f772d2 100644 --- a/veilid-core/src/storage_manager/mod.rs +++ b/veilid-core/src/storage_manager/mod.rs @@ -117,7 +117,7 @@ impl StorageManager { inner.rpc_processor = opt_rpc_processor } - async fn lock(&self) -> Result, VeilidAPIError> { + async fn lock(&self) -> VeilidAPIResult> { let inner = asyncmutex_lock_arc!(&self.inner); if !inner.initialized { apibail_not_initialized!(); @@ -131,7 +131,7 @@ impl StorageManager { kind: CryptoKind, schema: DHTSchema, safety_selection: SafetySelection, - ) -> Result { + ) -> VeilidAPIResult { let mut inner = self.lock().await?; // Create a new owned local record from scratch @@ -154,7 +154,7 @@ impl StorageManager { key: TypedKey, writer: Option, safety_selection: SafetySelection, - ) -> Result { + ) -> VeilidAPIResult { let mut inner = self.lock().await?; // See if we have a local record already or not @@ -202,13 +202,13 @@ impl StorageManager { } /// Close an opened local record - pub async fn close_record(&self, key: TypedKey) -> Result<(), VeilidAPIError> { + pub async fn close_record(&self, key: TypedKey) -> VeilidAPIResult<()> { let mut inner = self.lock().await?; inner.close_record(key) } /// Delete a local record - pub async fn delete_record(&self, key: TypedKey) -> Result<(), VeilidAPIError> { + pub async fn delete_record(&self, key: TypedKey) -> VeilidAPIResult<()> { let mut inner = self.lock().await?; // Ensure the record is closed @@ -233,7 +233,7 @@ impl StorageManager { key: TypedKey, subkey: ValueSubkey, force_refresh: bool, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { let mut inner = self.lock().await?; let Some(opened_record) = inner.opened_records.remove(&key) else { apibail_generic!("record not open"); @@ -301,7 +301,7 @@ impl StorageManager { key: TypedKey, subkey: ValueSubkey, data: Vec, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { let mut inner = self.lock().await?; // Get cryptosystem @@ -395,7 +395,7 @@ impl StorageManager { subkeys: ValueSubkeyRangeSet, expiration: Timestamp, count: u32, - ) -> Result { + ) -> VeilidAPIResult { let inner = self.lock().await?; unimplemented!(); } @@ -404,7 +404,7 @@ impl StorageManager { &self, key: TypedKey, subkeys: ValueSubkeyRangeSet, - ) -> Result { + ) -> VeilidAPIResult { let inner = self.lock().await?; unimplemented!(); } diff --git a/veilid-core/src/storage_manager/record_store.rs b/veilid-core/src/storage_manager/record_store.rs index 25e62725..27119fe7 100644 --- a/veilid-core/src/storage_manager/record_store.rs +++ b/veilid-core/src/storage_manager/record_store.rs @@ -241,11 +241,7 @@ where Ok(()) } - pub async fn new_record( - &mut self, - key: TypedKey, - record: Record, - ) -> Result<(), VeilidAPIError> { + pub async fn new_record(&mut self, key: TypedKey, record: Record) -> VeilidAPIResult<()> { let rtk = RecordTableKey { key }; if self.record_index.contains_key(&rtk) { apibail_internal!("record already exists"); @@ -290,7 +286,7 @@ where Ok(()) } - pub async fn delete_record(&mut self, key: TypedKey) -> Result<(), VeilidAPIError> { + pub async fn delete_record(&mut self, key: TypedKey) -> VeilidAPIResult<()> { // Get the record table key let rtk = RecordTableKey { key }; @@ -357,7 +353,7 @@ where key: TypedKey, subkey: ValueSubkey, want_descriptor: bool, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { // record from index let Some((subkey_count, opt_descriptor)) = self.with_record(key, |record| { (record.subkey_count(), if want_descriptor { @@ -419,7 +415,7 @@ where key: TypedKey, subkey: ValueSubkey, signed_value_data: SignedValueData, - ) -> Result<(), VeilidAPIError> { + ) -> VeilidAPIResult<()> { // Check size limit for data if signed_value_data.value_data().data().len() > self.limits.max_subkey_size { apibail_invalid_argument!( diff --git a/veilid-core/src/storage_manager/set_value.rs b/veilid-core/src/storage_manager/set_value.rs index 911109f7..2ea9ddf2 100644 --- a/veilid-core/src/storage_manager/set_value.rs +++ b/veilid-core/src/storage_manager/set_value.rs @@ -21,7 +21,7 @@ impl StorageManager { safety_selection: SafetySelection, value: SignedValueData, descriptor: SignedValueDescriptor, - ) -> Result { + ) -> VeilidAPIResult { let routing_table = rpc_processor.routing_table(); // Get the DHT parameters for 'SetValue' @@ -164,7 +164,7 @@ impl StorageManager { /// Handle a recieved 'Set Value' query /// Returns a None if the value passed in was set /// Returns a Some(current value) if the value was older and the current value was kept - pub async fn inbound_set_value(&self, key: TypedKey, subkey: ValueSubkey, value: SignedValueData, descriptor: Option) -> Result>, VeilidAPIError> { + pub async fn inbound_set_value(&self, key: TypedKey, subkey: ValueSubkey, value: SignedValueData, descriptor: Option) -> VeilidAPIResult>> { let mut inner = self.lock().await?; // See if the subkey we are modifying has a last known local value diff --git a/veilid-core/src/storage_manager/storage_manager_inner.rs b/veilid-core/src/storage_manager/storage_manager_inner.rs index 133f631d..e50cbcc3 100644 --- a/veilid-core/src/storage_manager/storage_manager_inner.rs +++ b/veilid-core/src/storage_manager/storage_manager_inner.rs @@ -172,7 +172,7 @@ impl StorageManagerInner { kind: CryptoKind, schema: DHTSchema, safety_selection: SafetySelection, - ) -> Result<(TypedKey, KeyPair), VeilidAPIError> { + ) -> VeilidAPIResult<(TypedKey, KeyPair)> { // Get cryptosystem let Some(vcrypto) = self.unlocked_inner.crypto.get(kind) else { apibail_generic!("unsupported cryptosystem"); @@ -214,7 +214,7 @@ impl StorageManagerInner { key: TypedKey, writer: Option, safety_selection: SafetySelection, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { // Ensure the record is closed if self.opened_records.contains_key(&key) { apibail_generic!("record is already open and should be closed first"); @@ -268,7 +268,7 @@ impl StorageManagerInner { subkey: ValueSubkey, subkey_result: SubkeyResult, safety_selection: SafetySelection, - ) -> Result { + ) -> VeilidAPIResult { // Ensure the record is closed if self.opened_records.contains_key(&key) { panic!("new record should never be opened at this point"); @@ -325,7 +325,7 @@ impl StorageManagerInner { Ok(descriptor) } - pub fn close_record(&mut self, key: TypedKey) -> Result<(), VeilidAPIError> { + pub fn close_record(&mut self, key: TypedKey) -> VeilidAPIResult<()> { let Some(_opened_record) = self.opened_records.remove(&key) else { apibail_generic!("record not open"); }; @@ -337,7 +337,7 @@ impl StorageManagerInner { key: TypedKey, subkey: ValueSubkey, want_descriptor: bool, - ) -> Result { + ) -> VeilidAPIResult { // See if it's in the local record store let Some(local_record_store) = self.local_record_store.as_mut() else { apibail_not_initialized!(); @@ -357,7 +357,7 @@ impl StorageManagerInner { key: TypedKey, subkey: ValueSubkey, signed_value_data: SignedValueData, - ) -> Result<(), VeilidAPIError> { + ) -> VeilidAPIResult<()> { // See if it's in the local record store let Some(local_record_store) = self.local_record_store.as_mut() else { apibail_not_initialized!(); @@ -376,7 +376,7 @@ impl StorageManagerInner { key: TypedKey, subkey: ValueSubkey, want_descriptor: bool, - ) -> Result { + ) -> VeilidAPIResult { // See if it's in the remote record store let Some(remote_record_store) = self.remote_record_store.as_mut() else { apibail_not_initialized!(); @@ -397,7 +397,7 @@ impl StorageManagerInner { subkey: ValueSubkey, signed_value_data: SignedValueData, signed_value_descriptor: SignedValueDescriptor, - ) -> Result<(), VeilidAPIError> { + ) -> VeilidAPIResult<()> { // See if it's in the remote record store let Some(remote_record_store) = self.remote_record_store.as_mut() else { apibail_not_initialized!(); diff --git a/veilid-core/src/storage_manager/types/record.rs b/veilid-core/src/storage_manager/types/record.rs index 68afa013..c8ec9cb7 100644 --- a/veilid-core/src/storage_manager/types/record.rs +++ b/veilid-core/src/storage_manager/types/record.rs @@ -27,7 +27,7 @@ where cur_ts: Timestamp, descriptor: SignedValueDescriptor, detail: D, - ) -> Result { + ) -> VeilidAPIResult { let schema = descriptor.schema()?; let subkey_count = schema.subkey_count(); Ok(Self { diff --git a/veilid-core/src/storage_manager/types/signed_value_data.rs b/veilid-core/src/storage_manager/types/signed_value_data.rs index ca5231e7..466764c8 100644 --- a/veilid-core/src/storage_manager/types/signed_value_data.rs +++ b/veilid-core/src/storage_manager/types/signed_value_data.rs @@ -34,7 +34,7 @@ impl SignedValueData { owner: &PublicKey, subkey: ValueSubkey, vcrypto: CryptoSystemVersion, - ) -> Result<(), VeilidAPIError> { + ) -> VeilidAPIResult<()> { let node_info_bytes = Self::make_signature_bytes(&self.value_data, owner, subkey)?; // validate signature vcrypto.verify(&self.value_data.writer(), &node_info_bytes, &self.signature) @@ -46,7 +46,7 @@ impl SignedValueData { subkey: ValueSubkey, vcrypto: CryptoSystemVersion, writer_secret: SecretKey, - ) -> Result { + ) -> VeilidAPIResult { let node_info_bytes = Self::make_signature_bytes(&value_data, owner, subkey)?; // create signature @@ -77,7 +77,7 @@ impl SignedValueData { value_data: &ValueData, owner: &PublicKey, subkey: ValueSubkey, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { let mut node_info_bytes = Vec::with_capacity(PUBLIC_KEY_LENGTH + 4 + 4 + value_data.data().len()); diff --git a/veilid-core/src/storage_manager/types/signed_value_descriptor.rs b/veilid-core/src/storage_manager/types/signed_value_descriptor.rs index 5cef1f2a..fa718dcb 100644 --- a/veilid-core/src/storage_manager/types/signed_value_descriptor.rs +++ b/veilid-core/src/storage_manager/types/signed_value_descriptor.rs @@ -31,7 +31,7 @@ impl SignedValueDescriptor { } } - pub fn validate(&self, vcrypto: CryptoSystemVersion) -> Result<(), VeilidAPIError> { + pub fn validate(&self, vcrypto: CryptoSystemVersion) -> VeilidAPIResult<()> { // validate signature vcrypto.verify(&self.owner, &self.schema_data, &self.signature) } @@ -44,7 +44,7 @@ impl SignedValueDescriptor { &self.schema_data } - pub fn schema(&self) -> Result { + pub fn schema(&self) -> VeilidAPIResult { DHTSchema::try_from(self.schema_data.as_slice()) } @@ -57,7 +57,7 @@ impl SignedValueDescriptor { schema_data: Vec, vcrypto: CryptoSystemVersion, owner_secret: SecretKey, - ) -> Result { + ) -> VeilidAPIResult { // create signature let signature = vcrypto.sign(&owner, &owner_secret, &schema_data)?; Ok(Self { diff --git a/veilid-core/src/table_store/table_store.rs b/veilid-core/src/table_store/table_store.rs index b3a60080..c8fd03a1 100644 --- a/veilid-core/src/table_store/table_store.rs +++ b/veilid-core/src/table_store/table_store.rs @@ -169,7 +169,7 @@ impl TableStore { // Get device encryption key from protected store let mut encryption_key: Option = self .protected_store - .load_user_secret_rkyv("device_encryption_key") + .load_user_secret_json("device_encryption_key") .await?; if let Some(encryption_key) = encryption_key { @@ -183,7 +183,14 @@ impl TableStore { let best_kind = best_crypto_kind(); let mut shared_secret = SharedSecret::default(); random_bytes(&mut shared_secret.bytes); - encryption_key = Some(TypedSharedSecret::new(best_kind, shared_secret)); + let device_encryption_key = TypedSharedSecret::new(best_kind, shared_secret); + + // Save the new device encryption key + self.protected_store + .save_user_secret_json("device_encryption_key", &device_encryption_key) + .await?; + + encryption_key = Some(device_encryption_key); } // Deserialize all table names diff --git a/veilid-core/src/veilid_api/api.rs b/veilid-core/src/veilid_api/api.rs index 7069f0cd..ab40f11f 100644 --- a/veilid-core/src/veilid_api/api.rs +++ b/veilid-core/src/veilid_api/api.rs @@ -49,70 +49,70 @@ impl VeilidAPI { //////////////////////////////////////////////////////////////// // Accessors - pub fn config(&self) -> Result { + pub fn config(&self) -> VeilidAPIResult { let inner = self.inner.lock(); if let Some(context) = &inner.context { return Ok(context.config.clone()); } Err(VeilidAPIError::NotInitialized) } - pub fn crypto(&self) -> Result { + pub fn crypto(&self) -> VeilidAPIResult { let inner = self.inner.lock(); if let Some(context) = &inner.context { return Ok(context.crypto.clone()); } Err(VeilidAPIError::NotInitialized) } - pub fn table_store(&self) -> Result { + pub fn table_store(&self) -> VeilidAPIResult { let inner = self.inner.lock(); if let Some(context) = &inner.context { return Ok(context.table_store.clone()); } Err(VeilidAPIError::not_initialized()) } - pub fn block_store(&self) -> Result { + pub fn block_store(&self) -> VeilidAPIResult { let inner = self.inner.lock(); if let Some(context) = &inner.context { return Ok(context.block_store.clone()); } Err(VeilidAPIError::not_initialized()) } - pub fn protected_store(&self) -> Result { + pub fn protected_store(&self) -> VeilidAPIResult { let inner = self.inner.lock(); if let Some(context) = &inner.context { return Ok(context.protected_store.clone()); } Err(VeilidAPIError::not_initialized()) } - pub fn attachment_manager(&self) -> Result { + pub fn attachment_manager(&self) -> VeilidAPIResult { let inner = self.inner.lock(); if let Some(context) = &inner.context { return Ok(context.attachment_manager.clone()); } Err(VeilidAPIError::not_initialized()) } - pub fn network_manager(&self) -> Result { + pub fn network_manager(&self) -> VeilidAPIResult { let inner = self.inner.lock(); if let Some(context) = &inner.context { return Ok(context.attachment_manager.network_manager()); } Err(VeilidAPIError::not_initialized()) } - pub fn rpc_processor(&self) -> Result { + pub fn rpc_processor(&self) -> VeilidAPIResult { let inner = self.inner.lock(); if let Some(context) = &inner.context { return Ok(context.attachment_manager.network_manager().rpc_processor()); } Err(VeilidAPIError::NotInitialized) } - pub fn routing_table(&self) -> Result { + pub fn routing_table(&self) -> VeilidAPIResult { let inner = self.inner.lock(); if let Some(context) = &inner.context { return Ok(context.attachment_manager.network_manager().routing_table()); } Err(VeilidAPIError::NotInitialized) } - pub fn storage_manager(&self) -> Result { + pub fn storage_manager(&self) -> VeilidAPIResult { let inner = self.inner.lock(); if let Some(context) = &inner.context { return Ok(context.storage_manager.clone()); @@ -124,7 +124,7 @@ impl VeilidAPI { // Attach/Detach /// Get a full copy of the current state - pub async fn get_state(&self) -> Result { + pub async fn get_state(&self) -> VeilidAPIResult { let attachment_manager = self.attachment_manager()?; let network_manager = attachment_manager.network_manager(); let config = self.config()?; @@ -142,7 +142,7 @@ impl VeilidAPI { /// Connect to the network #[instrument(level = "debug", err, skip_all)] - pub async fn attach(&self) -> Result<(), VeilidAPIError> { + pub async fn attach(&self) -> VeilidAPIResult<()> { let attachment_manager = self.attachment_manager()?; if !attachment_manager.attach().await { apibail_generic!("Already attached"); @@ -152,7 +152,7 @@ impl VeilidAPI { /// Disconnect from the network #[instrument(level = "debug", err, skip_all)] - pub async fn detach(&self) -> Result<(), VeilidAPIError> { + pub async fn detach(&self) -> VeilidAPIResult<()> { let attachment_manager = self.attachment_manager()?; if !attachment_manager.detach().await { apibail_generic!("Already detached"); @@ -175,7 +175,7 @@ impl VeilidAPI { /// Returns a route id and a publishable 'blob' with the route encrypted with each crypto kind /// Those nodes importing the blob will have their choice of which crypto kind to use #[instrument(level = "debug", skip(self))] - pub async fn new_private_route(&self) -> Result<(RouteId, Vec), VeilidAPIError> { + pub async fn new_private_route(&self) -> VeilidAPIResult<(RouteId, Vec)> { self.new_custom_private_route( &VALID_CRYPTO_KINDS, Stability::default(), @@ -191,7 +191,7 @@ impl VeilidAPI { crypto_kinds: &[CryptoKind], stability: Stability, sequencing: Sequencing, - ) -> Result<(RouteId, Vec), VeilidAPIError> { + ) -> VeilidAPIResult<(RouteId, Vec)> { let default_route_hop_count: usize = { let config = self.config()?; let c = config.get(); @@ -238,14 +238,14 @@ impl VeilidAPI { } #[instrument(level = "debug", skip(self))] - pub fn import_remote_private_route(&self, blob: Vec) -> Result { + pub fn import_remote_private_route(&self, blob: Vec) -> VeilidAPIResult { let rss = self.routing_table()?.route_spec_store(); rss.import_remote_private_route(blob) .map_err(|e| VeilidAPIError::invalid_argument(e, "blob", "private route blob")) } #[instrument(level = "debug", skip(self))] - pub fn release_private_route(&self, route_id: RouteId) -> Result<(), VeilidAPIError> { + pub fn release_private_route(&self, route_id: RouteId) -> VeilidAPIResult<()> { let rss = self.routing_table()?.route_spec_store(); if !rss.release_route(route_id) { apibail_invalid_argument!("release_private_route", "key", route_id); @@ -257,11 +257,7 @@ impl VeilidAPI { // App Calls #[instrument(level = "debug", skip(self))] - pub async fn app_call_reply( - &self, - id: OperationId, - message: Vec, - ) -> Result<(), VeilidAPIError> { + pub async fn app_call_reply(&self, id: OperationId, message: Vec) -> VeilidAPIResult<()> { let rpc_processor = self.rpc_processor()?; rpc_processor .app_call_reply(id, message) @@ -277,7 +273,7 @@ impl VeilidAPI { &self, _endpoint_mode: TunnelMode, _depth: u8, - ) -> Result { + ) -> VeilidAPIResult { panic!("unimplemented"); } @@ -287,12 +283,12 @@ impl VeilidAPI { _endpoint_mode: TunnelMode, _depth: u8, _partial_tunnel: PartialTunnel, - ) -> Result { + ) -> VeilidAPIResult { panic!("unimplemented"); } #[instrument(level = "debug", err, skip(self))] - pub async fn cancel_tunnel(&self, _tunnel_id: TunnelId) -> Result { + pub async fn cancel_tunnel(&self, _tunnel_id: TunnelId) -> VeilidAPIResult { panic!("unimplemented"); } } diff --git a/veilid-core/src/veilid_api/debug.rs b/veilid-core/src/veilid_api/debug.rs index f54471e2..7151b680 100644 --- a/veilid-core/src/veilid_api/debug.rs +++ b/veilid-core/src/veilid_api/debug.rs @@ -305,7 +305,7 @@ fn get_debug_argument Option>( context: &str, argument: &str, getter: G, -) -> Result { +) -> VeilidAPIResult { let Some(val) = getter(value) else { apibail_invalid_argument!(context, argument, value); }; @@ -317,7 +317,7 @@ fn get_debug_argument_at Option>( context: &str, argument: &str, getter: G, -) -> Result { +) -> VeilidAPIResult { if pos >= debug_args.len() { apibail_missing_argument!(context, argument); } @@ -329,7 +329,7 @@ fn get_debug_argument_at Option>( } impl VeilidAPI { - async fn debug_buckets(&self, args: String) -> Result { + async fn debug_buckets(&self, args: String) -> VeilidAPIResult { let args: Vec = args.split_whitespace().map(|s| s.to_owned()).collect(); let mut min_state = BucketEntryState::Unreliable; if args.len() == 1 { @@ -345,19 +345,19 @@ impl VeilidAPI { Ok(routing_table.debug_info_buckets(min_state)) } - async fn debug_dialinfo(&self, _args: String) -> Result { + async fn debug_dialinfo(&self, _args: String) -> VeilidAPIResult { // Dump routing table dialinfo let routing_table = self.network_manager()?.routing_table(); Ok(routing_table.debug_info_dialinfo()) } - async fn debug_txtrecord(&self, _args: String) -> Result { + async fn debug_txtrecord(&self, _args: String) -> VeilidAPIResult { // Dump routing table txt record let routing_table = self.network_manager()?.routing_table(); Ok(routing_table.debug_info_txtrecord().await) } - async fn debug_entries(&self, args: String) -> Result { + async fn debug_entries(&self, args: String) -> VeilidAPIResult { let args: Vec = args.split_whitespace().map(|s| s.to_owned()).collect(); let mut min_state = BucketEntryState::Unreliable; @@ -374,7 +374,7 @@ impl VeilidAPI { Ok(routing_table.debug_info_entries(min_state)) } - async fn debug_entry(&self, args: String) -> Result { + async fn debug_entry(&self, args: String) -> VeilidAPIResult { let args: Vec = args.split_whitespace().map(|s| s.to_owned()).collect(); let routing_table = self.network_manager()?.routing_table(); @@ -391,13 +391,13 @@ impl VeilidAPI { Ok(routing_table.debug_info_entry(node_ref)) } - async fn debug_nodeinfo(&self, _args: String) -> Result { + async fn debug_nodeinfo(&self, _args: String) -> VeilidAPIResult { // Dump routing table entry let routing_table = self.network_manager()?.routing_table(); Ok(routing_table.debug_info_nodeinfo()) } - async fn debug_config(&self, args: String) -> Result { + async fn debug_config(&self, args: String) -> VeilidAPIResult { let config = self.config()?; let args = args.trim_start(); if args.is_empty() { @@ -426,7 +426,7 @@ impl VeilidAPI { Ok("Config value set".to_owned()) } - async fn debug_restart(&self, args: String) -> Result { + async fn debug_restart(&self, args: String) -> VeilidAPIResult { let args = args.trim_start(); if args.is_empty() { apibail_missing_argument!("debug_restart", "arg_0"); @@ -452,7 +452,7 @@ impl VeilidAPI { } } - async fn debug_purge(&self, args: String) -> Result { + async fn debug_purge(&self, args: String) -> VeilidAPIResult { let args: Vec = args.split_whitespace().map(|s| s.to_owned()).collect(); if !args.is_empty() { if args[0] == "buckets" { @@ -504,7 +504,7 @@ impl VeilidAPI { } } - async fn debug_attach(&self, _args: String) -> Result { + async fn debug_attach(&self, _args: String) -> VeilidAPIResult { if !matches!( self.get_state().await?.attachment.state, AttachmentState::Detached @@ -517,7 +517,7 @@ impl VeilidAPI { Ok("Attached".to_owned()) } - async fn debug_detach(&self, _args: String) -> Result { + async fn debug_detach(&self, _args: String) -> VeilidAPIResult { if matches!( self.get_state().await?.attachment.state, AttachmentState::Detaching @@ -530,7 +530,7 @@ impl VeilidAPI { Ok("Detached".to_owned()) } - async fn debug_contact(&self, args: String) -> Result { + async fn debug_contact(&self, args: String) -> VeilidAPIResult { let args: Vec = args.split_whitespace().map(|s| s.to_owned()).collect(); let network_manager = self.network_manager()?; @@ -551,7 +551,7 @@ impl VeilidAPI { Ok(format!("{:#?}", cm)) } - async fn debug_ping(&self, args: String) -> Result { + async fn debug_ping(&self, args: String) -> VeilidAPIResult { let netman = self.network_manager()?; let routing_table = netman.routing_table(); let rpc = netman.rpc_processor(); @@ -593,7 +593,7 @@ impl VeilidAPI { Ok(format!("{:#?}", out)) } - async fn debug_route_allocate(&self, args: Vec) -> Result { + async fn debug_route_allocate(&self, args: Vec) -> VeilidAPIResult { // [ord|*ord] [rel] [] [in|out] [avoid_node_id] let netman = self.network_manager()?; @@ -652,7 +652,7 @@ impl VeilidAPI { Ok(out) } - async fn debug_route_release(&self, args: Vec) -> Result { + async fn debug_route_release(&self, args: Vec) -> VeilidAPIResult { // let netman = self.network_manager()?; let routing_table = netman.routing_table(); @@ -684,7 +684,7 @@ impl VeilidAPI { Ok(out) } - async fn debug_route_publish(&self, args: Vec) -> Result { + async fn debug_route_publish(&self, args: Vec) -> VeilidAPIResult { // [full] let netman = self.network_manager()?; let routing_table = netman.routing_table(); @@ -736,7 +736,7 @@ impl VeilidAPI { Ok(out) } - async fn debug_route_unpublish(&self, args: Vec) -> Result { + async fn debug_route_unpublish(&self, args: Vec) -> VeilidAPIResult { // let netman = self.network_manager()?; let routing_table = netman.routing_table(); @@ -758,7 +758,7 @@ impl VeilidAPI { }; Ok(out) } - async fn debug_route_print(&self, args: Vec) -> Result { + async fn debug_route_print(&self, args: Vec) -> VeilidAPIResult { // let netman = self.network_manager()?; let routing_table = netman.routing_table(); @@ -777,7 +777,7 @@ impl VeilidAPI { None => Ok("Route does not exist".to_owned()), } } - async fn debug_route_list(&self, _args: Vec) -> Result { + async fn debug_route_list(&self, _args: Vec) -> VeilidAPIResult { // let netman = self.network_manager()?; let routing_table = netman.routing_table(); @@ -800,7 +800,7 @@ impl VeilidAPI { Ok(out) } - async fn debug_route_import(&self, args: Vec) -> Result { + async fn debug_route_import(&self, args: Vec) -> VeilidAPIResult { // let blob = get_debug_argument_at(&args, 1, "debug_route", "blob", get_string)?; @@ -820,7 +820,7 @@ impl VeilidAPI { return Ok(out); } - async fn debug_route_test(&self, args: Vec) -> Result { + async fn debug_route_test(&self, args: Vec) -> VeilidAPIResult { // let netman = self.network_manager()?; let routing_table = netman.routing_table(); @@ -848,7 +848,7 @@ impl VeilidAPI { return Ok(out); } - async fn debug_route(&self, args: String) -> Result { + async fn debug_route(&self, args: String) -> VeilidAPIResult { let args: Vec = args.split_whitespace().map(|s| s.to_owned()).collect(); let command = get_debug_argument_at(&args, 0, "debug_route", "command", get_string)?; @@ -874,7 +874,7 @@ impl VeilidAPI { } } - async fn debug_record_list(&self, args: Vec) -> Result { + async fn debug_record_list(&self, args: Vec) -> VeilidAPIResult { // let storage_manager = self.storage_manager()?; @@ -895,7 +895,7 @@ impl VeilidAPI { return Ok(out); } - async fn debug_record(&self, args: String) -> Result { + async fn debug_record(&self, args: String) -> VeilidAPIResult { let args: Vec = args.split_whitespace().map(|s| s.to_owned()).collect(); let command = get_debug_argument_at(&args, 0, "debug_record", "command", get_string)?; @@ -907,7 +907,7 @@ impl VeilidAPI { } } - pub async fn debug_help(&self, _args: String) -> Result { + pub async fn debug_help(&self, _args: String) -> VeilidAPIResult { Ok(r#">>> Debug commands: help buckets [dead|reliable] @@ -947,7 +947,7 @@ impl VeilidAPI { .to_owned()) } - pub async fn debug(&self, args: String) -> Result { + pub async fn debug(&self, args: String) -> VeilidAPIResult { let res = { let args = args.trim_start(); if args.is_empty() { diff --git a/veilid-core/src/veilid_api/routing_context.rs b/veilid-core/src/veilid_api/routing_context.rs index d7ba5e2c..952a42b7 100644 --- a/veilid-core/src/veilid_api/routing_context.rs +++ b/veilid-core/src/veilid_api/routing_context.rs @@ -45,11 +45,11 @@ impl RoutingContext { } } - pub fn with_privacy(self) -> Result { + pub fn with_privacy(self) -> VeilidAPIResult { self.with_custom_privacy(Stability::default()) } - pub fn with_custom_privacy(self, stability: Stability) -> Result { + pub fn with_custom_privacy(self, stability: Stability) -> VeilidAPIResult { let config = self.api.config()?; let c = config.get(); @@ -96,10 +96,7 @@ impl RoutingContext { self.api.clone() } - async fn get_destination( - &self, - target: Target, - ) -> Result { + async fn get_destination(&self, target: Target) -> VeilidAPIResult { let rpc_processor = self.api.rpc_processor()?; match target { @@ -141,11 +138,7 @@ impl RoutingContext { // App-level Messaging #[instrument(level = "debug", err, skip(self))] - pub async fn app_call( - &self, - target: Target, - request: Vec, - ) -> Result, VeilidAPIError> { + pub async fn app_call(&self, target: Target, request: Vec) -> VeilidAPIResult> { let rpc_processor = self.api.rpc_processor()?; // Get destination @@ -170,11 +163,7 @@ impl RoutingContext { } #[instrument(level = "debug", err, skip(self))] - pub async fn app_message( - &self, - target: Target, - message: Vec, - ) -> Result<(), VeilidAPIError> { + pub async fn app_message(&self, target: Target, message: Vec) -> VeilidAPIResult<()> { let rpc_processor = self.api.rpc_processor()?; // Get destination @@ -206,7 +195,7 @@ impl RoutingContext { &self, kind: CryptoKind, schema: DHTSchema, - ) -> Result { + ) -> VeilidAPIResult { let storage_manager = self.api.storage_manager()?; storage_manager .create_record(kind, schema, self.unlocked_inner.safety_selection) @@ -220,7 +209,7 @@ impl RoutingContext { &self, key: TypedKey, writer: Option, - ) -> Result { + ) -> VeilidAPIResult { let storage_manager = self.api.storage_manager()?; storage_manager .open_record(key, writer, self.unlocked_inner.safety_selection) @@ -229,7 +218,7 @@ impl RoutingContext { /// Closes a DHT record at a specific key that was opened with create_dht_record or open_dht_record. /// Closing a record allows you to re-open it with a different routing context - pub async fn close_dht_record(&self, key: TypedKey) -> Result<(), VeilidAPIError> { + pub async fn close_dht_record(&self, key: TypedKey) -> VeilidAPIResult<()> { let storage_manager = self.api.storage_manager()?; storage_manager.close_record(key).await } @@ -237,7 +226,7 @@ impl RoutingContext { /// Deletes a DHT record at a specific key. If the record is opened, it must be closed before it is deleted. /// Deleting a record does not delete it from the network, but will remove the storage of the record /// locally, and will prevent its value from being refreshed on the network by this node. - pub async fn delete_dht_record(&self, key: TypedKey) -> Result<(), VeilidAPIError> { + pub async fn delete_dht_record(&self, key: TypedKey) -> VeilidAPIResult<()> { let storage_manager = self.api.storage_manager()?; storage_manager.delete_record(key).await } @@ -251,7 +240,7 @@ impl RoutingContext { key: TypedKey, subkey: ValueSubkey, force_refresh: bool, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { let storage_manager = self.api.storage_manager()?; storage_manager.get_value(key, subkey, force_refresh).await } @@ -264,7 +253,7 @@ impl RoutingContext { key: TypedKey, subkey: ValueSubkey, data: Vec, - ) -> Result, VeilidAPIError> { + ) -> VeilidAPIResult> { let storage_manager = self.api.storage_manager()?; storage_manager.set_value(key, subkey, data).await } @@ -280,7 +269,7 @@ impl RoutingContext { subkeys: ValueSubkeyRangeSet, expiration: Timestamp, count: u32, - ) -> Result { + ) -> VeilidAPIResult { let storage_manager = self.api.storage_manager()?; storage_manager .watch_values(key, subkeys, expiration, count) @@ -293,7 +282,7 @@ impl RoutingContext { &self, key: TypedKey, subkeys: ValueSubkeyRangeSet, - ) -> Result { + ) -> VeilidAPIResult { let storage_manager = self.api.storage_manager()?; storage_manager.cancel_watch_values(key, subkeys).await } @@ -301,11 +290,11 @@ impl RoutingContext { /////////////////////////////////// /// Block Store - pub async fn find_block(&self, _block_id: PublicKey) -> Result, VeilidAPIError> { + pub async fn find_block(&self, _block_id: PublicKey) -> VeilidAPIResult> { panic!("unimplemented"); } - pub async fn supply_block(&self, _block_id: PublicKey) -> Result { + pub async fn supply_block(&self, _block_id: PublicKey) -> VeilidAPIResult { panic!("unimplemented"); } } diff --git a/veilid-core/src/veilid_api/serialize_helpers/serialize_json.rs b/veilid-core/src/veilid_api/serialize_helpers/serialize_json.rs index 39494fd4..5e98624c 100644 --- a/veilid-core/src/veilid_api/serialize_helpers/serialize_json.rs +++ b/veilid-core/src/veilid_api/serialize_helpers/serialize_json.rs @@ -3,9 +3,7 @@ use super::*; // Don't trace these functions as they are used in the transfer of API logs, which will recurse! // #[instrument(level = "trace", ret, err)] -pub fn deserialize_json<'a, T: de::Deserialize<'a> + Debug>( - arg: &'a str, -) -> Result { +pub fn deserialize_json<'a, T: de::Deserialize<'a> + Debug>(arg: &'a str) -> VeilidAPIResult { serde_json::from_str(arg).map_err(|e| VeilidAPIError::ParseError { message: e.to_string(), value: format!( @@ -19,7 +17,7 @@ pub fn deserialize_json<'a, T: de::Deserialize<'a> + Debug>( // #[instrument(level = "trace", ret, err)] pub fn deserialize_opt_json( arg: Option, -) -> Result { +) -> VeilidAPIResult { let arg = arg.as_ref().ok_or_else(|| VeilidAPIError::ParseError { message: "invalid null string".to_owned(), value: format!( diff --git a/veilid-core/src/veilid_config.rs b/veilid-core/src/veilid_config.rs index d79377af..2b2aab55 100644 --- a/veilid-core/src/veilid_config.rs +++ b/veilid-core/src/veilid_config.rs @@ -1,7 +1,7 @@ use crate::*; //////////////////////////////////////////////////////////////////////////////////////////////// -pub type ConfigCallbackReturn = Result, VeilidAPIError>; +pub type ConfigCallbackReturn = VeilidAPIResult>; pub type ConfigCallback = Arc ConfigCallbackReturn + Send + Sync>; /// Enable and configure HTTPS access to the Veilid node @@ -585,7 +585,7 @@ impl VeilidConfig { &mut self, config: String, update_cb: UpdateCallback, - ) -> Result<(), VeilidAPIError> { + ) -> VeilidAPIResult<()> { self.update_cb = Some(update_cb); self.with_mut(|inner| { @@ -594,11 +594,7 @@ impl VeilidConfig { }) } - pub fn setup( - &mut self, - cb: ConfigCallback, - update_cb: UpdateCallback, - ) -> Result<(), VeilidAPIError> { + pub fn setup(&mut self, cb: ConfigCallback, update_cb: UpdateCallback) -> VeilidAPIResult<()> { self.update_cb = Some(update_cb); self.with_mut(|inner| { // Simple config transformation @@ -738,9 +734,9 @@ impl VeilidConfig { safe_cfg } - pub fn with_mut(&self, f: F) -> Result + pub fn with_mut(&self, f: F) -> VeilidAPIResult where - F: FnOnce(&mut VeilidConfigInner) -> Result, + F: FnOnce(&mut VeilidConfigInner) -> VeilidAPIResult, { let out = { let inner = &mut *self.inner.write(); @@ -764,7 +760,7 @@ impl VeilidConfig { Ok(out) } - pub fn get_key_json(&self, key: &str) -> Result { + pub fn get_key_json(&self, key: &str) -> VeilidAPIResult { let c = self.get(); // Generate json from whole config @@ -787,7 +783,7 @@ impl VeilidConfig { Ok(out.to_string()) } } - pub fn set_key_json(&self, key: &str, value: &str) -> Result<(), VeilidAPIError> { + pub fn set_key_json(&self, key: &str, value: &str) -> VeilidAPIResult<()> { self.with_mut(|c| { // Split key into path parts let keypath: Vec<&str> = key.split('.').collect(); @@ -824,7 +820,7 @@ impl VeilidConfig { }) } - fn validate(inner: &VeilidConfigInner) -> Result<(), VeilidAPIError> { + fn validate(inner: &VeilidConfigInner) -> VeilidAPIResult<()> { if inner.program_name.is_empty() { apibail_generic!("Program name must not be empty in 'program_name'"); } @@ -929,12 +925,12 @@ impl VeilidConfig { Ok(()) } - #[cfg(not(test))] + //xxx#[cfg(not(test))] async fn init_node_id( &self, vcrypto: CryptoSystemVersion, - protected_store: intf::ProtectedStore, - ) -> Result<(TypedKey, TypedSecret), VeilidAPIError> { + table_store: TableStore, + ) -> VeilidAPIResult<(TypedKey, TypedSecret)> { let ck = vcrypto.kind(); let mut node_id = self.inner.read().network.routing_table.node_id.get(ck); let mut node_id_secret = self @@ -945,45 +941,36 @@ impl VeilidConfig { .node_id_secret .get(ck); - // See if node id was previously stored in the protected store + // See if node id was previously stored in the table store + let config_table = table_store.open("__veilid_config", 1).await?; + + let table_key_node_id = format!("node_id_{}", ck); + let table_key_node_id_secret = format!("node_id_secret_{}", ck); + if node_id.is_none() { - debug!("pulling node_id_{} from storage", ck); - if let Some(s) = protected_store - .load_user_secret_string(format!("node_id_{}", ck)) + debug!("pulling {} from storage", table_key_node_id); + if let Ok(Some(stored_node_id)) = config_table + .load_json::(0, table_key_node_id.as_bytes()) .await - .map_err(VeilidAPIError::internal)? { - debug!("node_id_{} found in storage", ck); - node_id = match TypedKey::from_str(s.as_str()) { - Ok(v) => Some(v), - Err(_) => { - debug!("node id in protected store is not valid"); - None - } - } + debug!("{} found in storage", table_key_node_id); + node_id = Some(stored_node_id); } else { - debug!("node_id_{} not found in storage", ck); + debug!("{} not found in storage", table_key_node_id); } } // See if node id secret was previously stored in the protected store if node_id_secret.is_none() { - debug!("pulling node id secret from storage"); - if let Some(s) = protected_store - .load_user_secret_string(format!("node_id_secret_{}", ck)) + debug!("pulling {} from storage", table_key_node_id_secret); + if let Ok(Some(stored_node_id_secret)) = config_table + .load_json::(0, table_key_node_id_secret.as_bytes()) .await - .map_err(VeilidAPIError::internal)? { - debug!("node_id_secret_{} found in storage", ck); - node_id_secret = match TypedSecret::from_str(s.as_str()) { - Ok(v) => Some(v), - Err(_) => { - debug!("node id secret in protected store is not valid"); - None - } - } + debug!("{} found in storage", table_key_node_id_secret); + node_id_secret = Some(stored_node_id_secret); } else { - debug!("node_id_secret_{} not found in storage", ck); + debug!("{} not found in storage", table_key_node_id_secret); } } @@ -1007,14 +994,12 @@ impl VeilidConfig { info!("Node Id: {}", node_id); // Save the node id / secret in storage - protected_store - .save_user_secret_string(format!("node_id_{}", ck), node_id.to_string()) - .await - .map_err(VeilidAPIError::internal)?; - protected_store - .save_user_secret_string(format!("node_id_secret_{}", ck), node_id_secret.to_string()) - .await - .map_err(VeilidAPIError::internal)?; + config_table + .store_json(0, table_key_node_id.as_bytes(), &node_id) + .await?; + config_table + .store_json(0, table_key_node_id_secret.as_bytes(), &node_id_secret) + .await?; Ok((node_id, node_id_secret)) } @@ -1025,8 +1010,8 @@ impl VeilidConfig { pub async fn init_node_ids( &self, crypto: Crypto, - protected_store: intf::ProtectedStore, - ) -> Result<(), VeilidAPIError> { + table_store: TableStore, + ) -> VeilidAPIResult<()> { let mut out_node_id = TypedKeySet::new(); let mut out_node_id_secret = TypedSecretSet::new(); @@ -1041,8 +1026,7 @@ impl VeilidConfig { (TypedKey::new(ck, kp.key), TypedSecret::new(ck, kp.secret)) }; #[cfg(not(test))] - let (node_id, node_id_secret) = - self.init_node_id(vcrypto, protected_store.clone()).await?; + let (node_id, node_id_secret) = self.init_node_id(vcrypto, table_store.clone()).await?; // Save for config out_node_id.add(node_id); diff --git a/veilid-server/src/client_api.rs b/veilid-server/src/client_api.rs index fac14b9a..269dce3a 100644 --- a/veilid-server/src/client_api.rs +++ b/veilid-server/src/client_api.rs @@ -19,7 +19,7 @@ use veilid_core::*; // Encoding for ApiResult fn encode_api_result( - result: &Result, + result: &VeilidAPIResult, builder: &mut api_result::Builder, ) { match result {