Rename crypto types

This commit is contained in:
Brandon Vandegrift 2025-06-16 19:51:58 -04:00 committed by Christien Rioux
parent a73485ab9a
commit 389ffe8152
156 changed files with 2049 additions and 1924 deletions

View file

@ -1,5 +1,9 @@
**UNRELEASED**
- _0.5.0 BREAKING CHANGES_
- Rename crypto types:
- {CryptoBytes} -> Bare{CryptoBytes}
- Typed{CryptoBytes} -> {CryptoBytes}
**Changed in Veilid 0.4.8**

View file

@ -14,7 +14,7 @@ pub enum PeerTableColumn {
// impl PeerTableColumn {
// fn as_str(&self) -> &str {
// match self {
// PeerTableColumn::NodeId => "Node Id",
// PeerTableColumn::BareNodeId => "Node Id",
// PeerTableColumn::Address => "Address",
// PeerTableColumn::LatencyAvg => "Latency",
// PeerTableColumn::TransferDownAvg => "Down",

View file

@ -4,12 +4,14 @@ Demonstration of the creation of private routes in a basic client/server style p
## Running this example
To use, start a *server* that creates a private route:
To use, start a _server_ that creates a private route:
```
# cargo run --example private-route-example
```
which will produce output like this:
```
Veilid Private Routing Example
Waiting.................
@ -19,13 +21,13 @@ cargo run --example private-route-example -- --connect ARAeUAECAQJRBAEBURgBAg8wR
Press ctrl-c when you are finished.
```
Then, in a second terminal, or on another machine, run a *client* that connects to this private route:
Then, in a second terminal, or on another machine, run a _client_ that connects to this private route:
```
# cargo run --example private-route-example -- --connect ARAeUAECAQJRBAEBURgBAg8wRExWEAT/NZxHC0sOm9oDPYts06hETjdBFhQ7akbgwU9cR/+HIODlAAARBARBEAL/XwgITBMjGe8DIS8kAw0VyKcu6d65YES+lapmgYaJmK8SEQQDMQ3yAf9mmhQquLvXsgm1h/MEQma0jQEJmg6dajJdNqQ7EZjyViM9Vp+zA/e2/QG8xyRiMmDKJuJ6ixQ+CW8HQcSSKdgp0wC0ATUrZTTCQmZ8m/BWlJ8/0qySnSFj
```
Now, you can send lines from the *client* to the *server* and the will show up in the *server*'s terminal:
Now, you can send lines from the _client_ to the _server_ and the will show up in the _server_'s terminal:
```
AppMessage received: testing 1 2 3
@ -39,7 +41,7 @@ You may notice spurious route failures and errors in the console of this test pr
For example:
```
VeilidRouteChange { dead_routes: [RouteId(Osifkt3Q3j6O5x03o85iBtpw8sBe5gUhLQW1n6bd7Ws)], dead_remote_routes: [] }
VeilidRouteChange { dead_routes: [BareRouteId(Osifkt3Q3j6O5x03o85iBtpw8sBe5gUhLQW1n6bd7Ws)], dead_remote_routes: [] }
```
This example is a work in progress and is being used as a testbed to improve the quality of Veilid's private routing API. While there exist ways to stabilize the existing private routing mechanism, they are beyond the scope of this example code. Rather, we are working on putting all of the required logic into veilid-core itself. Once this is done, this example will be updated, and this note will be removed.

View file

@ -8,98 +8,128 @@ pub trait CryptoSystem {
fn crypto(&self) -> VeilidComponentGuard<'_, Crypto>;
// Cached Operations
fn cached_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult<SharedSecret>;
fn cached_dh(
&self,
key: &BarePublicKey,
secret: &BareSecretKey,
) -> VeilidAPIResult<BareSharedSecret>;
// Generation
fn random_bytes(&self, len: u32) -> Vec<u8>;
fn default_salt_length(&self) -> u32;
fn hash_password(&self, password: &[u8], salt: &[u8]) -> VeilidAPIResult<String>;
fn verify_password(&self, password: &[u8], password_hash: &str) -> VeilidAPIResult<bool>;
fn derive_shared_secret(&self, password: &[u8], salt: &[u8]) -> VeilidAPIResult<SharedSecret>;
fn random_nonce(&self) -> Nonce;
fn random_shared_secret(&self) -> SharedSecret;
fn compute_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult<SharedSecret>;
fn derive_shared_secret(
&self,
password: &[u8],
salt: &[u8],
) -> VeilidAPIResult<BareSharedSecret>;
fn random_nonce(&self) -> BareNonce;
fn random_shared_secret(&self) -> BareSharedSecret;
fn compute_dh(
&self,
key: &BarePublicKey,
secret: &BareSecretKey,
) -> VeilidAPIResult<BareSharedSecret>;
fn generate_shared_secret(
&self,
key: &PublicKey,
secret: &SecretKey,
key: &BarePublicKey,
secret: &BareSecretKey,
domain: &[u8],
) -> VeilidAPIResult<SharedSecret> {
) -> VeilidAPIResult<BareSharedSecret> {
let dh = self.compute_dh(key, secret)?;
Ok(SharedSecret::from(self.generate_hash(
Ok(BareSharedSecret::from(self.generate_hash(
&[&dh.bytes, domain, VEILID_DOMAIN_API].concat(),
)))
}
fn generate_keypair(&self) -> KeyPair;
fn generate_hash(&self, data: &[u8]) -> HashDigest;
fn generate_hash_reader(&self, reader: &mut dyn std::io::Read) -> VeilidAPIResult<PublicKey>;
fn generate_keypair(&self) -> BareKeyPair;
fn generate_hash(&self, data: &[u8]) -> BareHashDigest;
fn generate_hash_reader(
&self,
reader: &mut dyn std::io::Read,
) -> VeilidAPIResult<BarePublicKey>;
// Validation
fn validate_keypair(&self, key: &PublicKey, secret: &SecretKey) -> bool;
fn validate_hash(&self, data: &[u8], hash: &HashDigest) -> bool;
fn validate_keypair(&self, key: &BarePublicKey, secret: &BareSecretKey) -> bool;
fn validate_hash(&self, data: &[u8], hash: &BareHashDigest) -> bool;
fn validate_hash_reader(
&self,
reader: &mut dyn std::io::Read,
hash: &HashDigest,
hash: &BareHashDigest,
) -> VeilidAPIResult<bool>;
// Distance Metric
fn distance(&self, hash1: &HashDigest, hash2: &HashDigest) -> HashDistance;
fn distance(&self, hash1: &BareHashDigest, hash2: &BareHashDigest) -> BareHashDistance;
// Authentication
fn sign(&self, key: &PublicKey, secret: &SecretKey, data: &[u8]) -> VeilidAPIResult<Signature>;
fn verify(&self, key: &PublicKey, data: &[u8], signature: &Signature) -> VeilidAPIResult<bool>;
fn sign(
&self,
key: &BarePublicKey,
secret: &BareSecretKey,
data: &[u8],
) -> VeilidAPIResult<BareSignature>;
fn verify(
&self,
key: &BarePublicKey,
data: &[u8],
signature: &BareSignature,
) -> VeilidAPIResult<bool>;
// AEAD Encrypt/Decrypt
fn aead_overhead(&self) -> usize;
fn decrypt_in_place_aead(
&self,
body: &mut Vec<u8>,
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<()>;
fn decrypt_aead(
&self,
body: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<Vec<u8>>;
fn encrypt_in_place_aead(
&self,
body: &mut Vec<u8>,
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<()>;
fn encrypt_aead(
&self,
body: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<Vec<u8>>;
// NoAuth Encrypt/Decrypt
fn crypt_in_place_no_auth(&self, body: &mut [u8], nonce: &Nonce, shared_secret: &SharedSecret);
fn crypt_in_place_no_auth(
&self,
body: &mut [u8],
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
);
fn crypt_b2b_no_auth(
&self,
in_buf: &[u8],
out_buf: &mut [u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
);
fn crypt_no_auth_aligned_8(
&self,
body: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) -> Vec<u8>;
fn crypt_no_auth_unaligned(
&self,
body: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) -> Vec<u8>;
}

View file

@ -4,13 +4,13 @@ use crate::*;
// Diffie-Hellman key exchange cache
#[derive(Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct DHCacheKey {
pub key: PublicKey,
pub secret: SecretKey,
pub key: BarePublicKey,
pub secret: BareSecretKey,
}
#[derive(Serialize, Deserialize)]
pub struct DHCacheValue {
pub shared_secret: SharedSecret,
pub shared_secret: BareSharedSecret,
}
pub type DHCache = LruCache<DHCacheKey, DHCacheValue>;
@ -34,11 +34,11 @@ pub fn cache_to_bytes(cache: &DHCache) -> Vec<u8> {
pub fn bytes_to_cache(bytes: &[u8], cache: &mut DHCache) {
for d in bytes.chunks(32 + 32 + 32) {
let k = DHCacheKey {
key: PublicKey::new(d[0..32].try_into().expect("asdf")),
secret: SecretKey::new(d[32..64].try_into().expect("asdf")),
key: BarePublicKey::new(d[0..32].try_into().expect("asdf")),
secret: BareSecretKey::new(d[32..64].try_into().expect("asdf")),
};
let v = DHCacheValue {
shared_secret: SharedSecret::new(d[64..96].try_into().expect("asdf")),
shared_secret: BareSharedSecret::new(d[64..96].try_into().expect("asdf")),
};
cache.insert(k, v);
}

View file

@ -4,7 +4,7 @@ use crate::*;
use core::convert::TryInto;
pub const MAX_ENVELOPE_SIZE: usize = 65507;
pub const MIN_ENVELOPE_SIZE: usize = 0x6A + 0x40; // Header + Signature
pub const MIN_ENVELOPE_SIZE: usize = 0x6A + 0x40; // Header + BareSignature
pub const ENVELOPE_MAGIC: &[u8; 3] = b"VLD";
/// Envelopes are versioned
@ -30,7 +30,7 @@ pub const ENVELOPE_MAGIC: &[u8; 3] = b"VLD";
/// sender_id: [u8; 32], // 0x2A: Node ID of the message source, which is the public key of the sender (must be verified with find_node if this is a new node_id/address combination)
/// recipient_id: [u8; 32], // 0x4A: Node ID of the intended recipient, which is the public key of the recipient (must be the receiving node, or a relay lease holder)
/// // 0x6A: message is appended (operations)
/// signature: [u8; 64], // 0x?? (end-0x40): Signature of the entire envelope including header is appended to the packet
/// signature: [u8; 64], // 0x?? (end-0x40): BareSignature of the entire envelope including header is appended to the packet
/// // entire header needs to be included in message digest, relays are not allowed to modify the envelope without invalidating the signature.
/// }
#[derive(Debug, Clone, PartialEq, Eq, Default)]
@ -38,9 +38,9 @@ pub struct Envelope {
version: EnvelopeVersion,
crypto_kind: CryptoKind,
timestamp: Timestamp,
nonce: Nonce,
sender_id: NodeId,
recipient_id: NodeId,
nonce: BareNonce,
sender_id: BareNodeId,
recipient_id: BareNodeId,
}
impl Envelope {
@ -49,9 +49,9 @@ impl Envelope {
version: EnvelopeVersion,
crypto_kind: CryptoKind,
timestamp: Timestamp,
nonce: Nonce,
sender_id: NodeId,
recipient_id: NodeId,
nonce: BareNonce,
sender_id: BareNodeId,
recipient_id: BareNodeId,
) -> Self {
assert!(VALID_ENVELOPE_VERSIONS.contains(&version));
assert!(VALID_CRYPTO_KINDS.contains(&crypto_kind));
@ -69,7 +69,7 @@ impl Envelope {
pub fn from_signed_data(
crypto: &Crypto,
data: &[u8],
network_key: &Option<SharedSecret>,
network_key: &Option<BareSharedSecret>,
) -> VeilidAPIResult<Envelope> {
// 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
@ -139,9 +139,9 @@ impl Envelope {
let recipient_id_slice: [u8; PUBLIC_KEY_LENGTH] = data[0x4A..0x6A]
.try_into()
.map_err(VeilidAPIError::internal)?;
let mut nonce: Nonce = Nonce::new(nonce_slice);
let mut sender_id = NodeId::new(sender_id_slice);
let mut recipient_id = NodeId::new(recipient_id_slice);
let mut nonce: BareNonce = BareNonce::new(nonce_slice);
let mut sender_id = BareNodeId::new(sender_id_slice);
let mut recipient_id = BareNodeId::new(recipient_id_slice);
// Apply network key (not the best, but it will keep networks from colliding without much overhead)
if let Some(nk) = network_key.as_ref() {
@ -165,7 +165,7 @@ impl Envelope {
}
// Get signature
let signature = Signature::new(
let signature = BareSignature::new(
data[(data.len() - 64)..]
.try_into()
.map_err(VeilidAPIError::internal)?,
@ -195,8 +195,8 @@ impl Envelope {
&self,
crypto: &Crypto,
data: &[u8],
node_id_secret: &SecretKey,
network_key: &Option<SharedSecret>,
node_id_secret: &BareSecretKey,
network_key: &Option<BareSharedSecret>,
) -> VeilidAPIResult<Vec<u8>> {
// Get DH secret
let vcrypto = crypto
@ -225,8 +225,8 @@ impl Envelope {
&self,
crypto: &Crypto,
body: &[u8],
node_id_secret: &SecretKey,
network_key: &Option<SharedSecret>,
node_id_secret: &BareSecretKey,
network_key: &Option<BareSharedSecret>,
) -> VeilidAPIResult<Vec<u8>> {
// Ensure body isn't too long
let uncompressed_body_size: usize = body.len() + MIN_ENVELOPE_SIZE;
@ -325,25 +325,25 @@ impl Envelope {
}
#[expect(dead_code)]
pub fn get_nonce(&self) -> Nonce {
pub fn get_nonce(&self) -> BareNonce {
self.nonce
}
#[expect(dead_code)]
pub fn get_sender_id(&self) -> NodeId {
pub fn get_sender_id(&self) -> BareNodeId {
self.sender_id
}
pub fn get_sender_typed_id(&self) -> TypedNodeId {
TypedNodeId::new(self.crypto_kind, self.sender_id)
pub fn get_sender_typed_id(&self) -> NodeId {
NodeId::new(self.crypto_kind, self.sender_id)
}
#[expect(dead_code)]
pub fn get_recipient_id(&self) -> NodeId {
pub fn get_recipient_id(&self) -> BareNodeId {
self.recipient_id
}
pub fn get_recipient_typed_id(&self) -> TypedNodeId {
TypedNodeId::new(self.crypto_kind, self.recipient_id)
pub fn get_recipient_typed_id(&self) -> NodeId {
NodeId::new(self.crypto_kind, self.recipient_id)
}
}

View file

@ -52,9 +52,9 @@ impl AsyncCryptoSystemGuard<'_> {
// Cached Operations
pub async fn cached_dh(
&self,
key: &PublicKey,
secret: &SecretKey,
) -> VeilidAPIResult<SharedSecret> {
key: &BarePublicKey,
secret: &BareSecretKey,
) -> VeilidAPIResult<BareSharedSecret> {
yielding(|| self.guard.cached_dh(key, secret)).await
}
@ -80,86 +80,86 @@ impl AsyncCryptoSystemGuard<'_> {
&self,
password: &[u8],
salt: &[u8],
) -> VeilidAPIResult<SharedSecret> {
) -> VeilidAPIResult<BareSharedSecret> {
yielding(|| self.guard.derive_shared_secret(password, salt)).await
}
pub async fn random_nonce(&self) -> Nonce {
pub async fn random_nonce(&self) -> BareNonce {
yielding(|| self.guard.random_nonce()).await
}
pub async fn random_shared_secret(&self) -> SharedSecret {
pub async fn random_shared_secret(&self) -> BareSharedSecret {
yielding(|| self.guard.random_shared_secret()).await
}
pub async fn compute_dh(
&self,
key: &PublicKey,
secret: &SecretKey,
) -> VeilidAPIResult<SharedSecret> {
key: &BarePublicKey,
secret: &BareSecretKey,
) -> VeilidAPIResult<BareSharedSecret> {
yielding(|| self.guard.compute_dh(key, secret)).await
}
pub async fn generate_shared_secret(
&self,
key: &PublicKey,
secret: &SecretKey,
key: &BarePublicKey,
secret: &BareSecretKey,
domain: &[u8],
) -> VeilidAPIResult<SharedSecret> {
) -> VeilidAPIResult<BareSharedSecret> {
let dh = self.compute_dh(key, secret).await?;
Ok(SharedSecret::from(
Ok(BareSharedSecret::from(
self.generate_hash(&[&dh.bytes, domain, VEILID_DOMAIN_API].concat())
.await,
))
}
pub async fn generate_keypair(&self) -> KeyPair {
pub async fn generate_keypair(&self) -> BareKeyPair {
yielding(|| self.guard.generate_keypair()).await
}
pub async fn generate_hash(&self, data: &[u8]) -> HashDigest {
pub async fn generate_hash(&self, data: &[u8]) -> BareHashDigest {
yielding(|| self.guard.generate_hash(data)).await
}
pub async fn generate_hash_reader(
&self,
reader: &mut dyn std::io::Read,
) -> VeilidAPIResult<PublicKey> {
) -> VeilidAPIResult<BarePublicKey> {
yielding(|| self.guard.generate_hash_reader(reader)).await
}
// Validation
pub async fn validate_keypair(&self, key: &PublicKey, secret: &SecretKey) -> bool {
pub async fn validate_keypair(&self, key: &BarePublicKey, secret: &BareSecretKey) -> bool {
yielding(|| self.guard.validate_keypair(key, secret)).await
}
pub async fn validate_hash(&self, data: &[u8], hash: &HashDigest) -> bool {
pub async fn validate_hash(&self, data: &[u8], hash: &BareHashDigest) -> bool {
yielding(|| self.guard.validate_hash(data, hash)).await
}
pub async fn validate_hash_reader(
&self,
reader: &mut dyn std::io::Read,
hash: &HashDigest,
hash: &BareHashDigest,
) -> VeilidAPIResult<bool> {
yielding(|| self.guard.validate_hash_reader(reader, hash)).await
}
// Distance Metric
pub async fn distance(&self, key1: &HashDigest, key2: &HashDigest) -> HashDistance {
pub async fn distance(&self, key1: &BareHashDigest, key2: &BareHashDigest) -> BareHashDistance {
yielding(|| self.guard.distance(key1, key2)).await
}
// Authentication
pub async fn sign(
&self,
key: &PublicKey,
secret: &SecretKey,
key: &BarePublicKey,
secret: &BareSecretKey,
data: &[u8],
) -> VeilidAPIResult<Signature> {
) -> VeilidAPIResult<BareSignature> {
yielding(|| self.guard.sign(key, secret, data)).await
}
pub async fn verify(
&self,
key: &PublicKey,
key: &BarePublicKey,
data: &[u8],
signature: &Signature,
signature: &BareSignature,
) -> VeilidAPIResult<bool> {
yielding(|| self.guard.verify(key, data, signature)).await
}
@ -173,8 +173,8 @@ impl AsyncCryptoSystemGuard<'_> {
pub async fn decrypt_in_place_aead(
&self,
body: &mut Vec<u8>,
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<()> {
yielding(|| {
@ -187,8 +187,8 @@ impl AsyncCryptoSystemGuard<'_> {
pub async fn decrypt_aead(
&self,
body: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<Vec<u8>> {
yielding(|| {
@ -201,8 +201,8 @@ impl AsyncCryptoSystemGuard<'_> {
pub async fn encrypt_in_place_aead(
&self,
body: &mut Vec<u8>,
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<()> {
yielding(|| {
@ -215,8 +215,8 @@ impl AsyncCryptoSystemGuard<'_> {
pub async fn encrypt_aead(
&self,
body: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<Vec<u8>> {
yielding(|| {
@ -230,8 +230,8 @@ impl AsyncCryptoSystemGuard<'_> {
pub async fn crypt_in_place_no_auth(
&self,
body: &mut [u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) {
yielding(|| {
self.guard
@ -244,8 +244,8 @@ impl AsyncCryptoSystemGuard<'_> {
&self,
in_buf: &[u8],
out_buf: &mut [u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) {
yielding(|| {
self.guard
@ -257,8 +257,8 @@ impl AsyncCryptoSystemGuard<'_> {
pub async fn crypt_no_auth_aligned_8(
&self,
body: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) -> Vec<u8> {
yielding(|| {
self.guard
@ -270,8 +270,8 @@ impl AsyncCryptoSystemGuard<'_> {
pub async fn crypt_no_auth_unaligned(
&self,
body: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) -> Vec<u8> {
yielding(|| {
self.guard

View file

@ -258,16 +258,16 @@ impl Crypto {
self.get_async(best_crypto_kind()).unwrap()
}
/// Signature set verification
/// BareSignature set verification
/// Returns Some() the set of signature cryptokinds that validate and are supported
/// Returns None if any cryptokinds are supported and do not validate
pub fn verify_signatures(
&self,
public_keys: &[TypedPublicKey],
public_keys: &[PublicKey],
data: &[u8],
typed_signatures: &[TypedSignature],
) -> VeilidAPIResult<Option<TypedPublicKeyGroup>> {
let mut out = TypedPublicKeyGroup::with_capacity(public_keys.len());
typed_signatures: &[Signature],
) -> VeilidAPIResult<Option<PublicKeyGroup>> {
let mut out = PublicKeyGroup::with_capacity(public_keys.len());
for sig in typed_signatures {
for nid in public_keys {
if nid.kind == sig.kind {
@ -283,17 +283,17 @@ impl Crypto {
Ok(Some(out))
}
/// Signature set generation
/// BareSignature set generation
/// Generates the set of signatures that are supported
/// Any cryptokinds that are not supported are silently dropped
pub fn generate_signatures<F, R>(
&self,
data: &[u8],
typed_key_pairs: &[TypedKeyPair],
typed_key_pairs: &[KeyPair],
transform: F,
) -> VeilidAPIResult<Vec<R>>
where
F: Fn(&TypedKeyPair, Signature) -> R,
F: Fn(&KeyPair, BareSignature) -> R,
{
let mut out = Vec::<R>::with_capacity(typed_key_pairs.len());
for kp in typed_key_pairs {
@ -307,16 +307,16 @@ impl Crypto {
/// Generate keypair
/// Does not require startup/init
pub fn generate_keypair(crypto_kind: CryptoKind) -> VeilidAPIResult<TypedKeyPair> {
pub fn generate_keypair(crypto_kind: CryptoKind) -> VeilidAPIResult<KeyPair> {
#[cfg(feature = "enable-crypto-vld0")]
if crypto_kind == CRYPTO_KIND_VLD0 {
let kp = vld0_generate_keypair();
return Ok(TypedKeyPair::new(crypto_kind, kp));
return Ok(KeyPair::new(crypto_kind, kp));
}
#[cfg(feature = "enable-crypto-none")]
if crypto_kind == CRYPTO_KIND_NONE {
let kp = none_generate_keypair();
return Ok(TypedKeyPair::new(crypto_kind, kp));
return Ok(KeyPair::new(crypto_kind, kp));
}
Err(VeilidAPIError::generic("invalid crypto kind"))
}
@ -326,9 +326,9 @@ impl Crypto {
fn cached_dh_internal<T: CryptoSystem>(
&self,
vcrypto: &T,
key: &PublicKey,
secret: &SecretKey,
) -> VeilidAPIResult<SharedSecret> {
key: &BarePublicKey,
secret: &BareSecretKey,
) -> VeilidAPIResult<BareSharedSecret> {
Ok(
match self.inner.lock().dh_cache.entry(DHCacheKey {
key: *key,
@ -356,7 +356,7 @@ impl Crypto {
&self,
vcrypto: AsyncCryptoSystemGuard<'_>,
table_store: &TableStore,
) -> VeilidAPIResult<(TypedNodeId, TypedSecretKey)> {
) -> VeilidAPIResult<(NodeId, SecretKey)> {
let config = self.config();
let ck = vcrypto.kind();
let (mut node_id, mut node_id_secret) = config.with(|c| {
@ -375,7 +375,7 @@ impl Crypto {
if node_id.is_none() {
veilid_log!(self debug "pulling {} from storage", table_key_node_id);
if let Ok(Some(stored_node_id)) = config_table
.load_json::<TypedNodeId>(0, table_key_node_id.as_bytes())
.load_json::<NodeId>(0, table_key_node_id.as_bytes())
.await
{
veilid_log!(self debug "{} found in storage", table_key_node_id);
@ -389,7 +389,7 @@ impl Crypto {
if node_id_secret.is_none() {
veilid_log!(self debug "pulling {} from storage", table_key_node_id_secret);
if let Ok(Some(stored_node_id_secret)) = config_table
.load_json::<TypedSecretKey>(0, table_key_node_id_secret.as_bytes())
.load_json::<SecretKey>(0, table_key_node_id_secret.as_bytes())
.await
{
veilid_log!(self debug "{} found in storage", table_key_node_id_secret);
@ -418,8 +418,8 @@ impl Crypto {
veilid_log!(self debug "generating new node_id_{}", ck);
let kp = vcrypto.generate_keypair().await;
(
TypedNodeId::new(ck, kp.key.into()),
TypedSecretKey::new(ck, kp.secret),
NodeId::new(ck, kp.key.into()),
SecretKey::new(ck, kp.secret),
)
};
veilid_log!(self info "Node Id: {}", node_id);
@ -439,8 +439,8 @@ impl Crypto {
/// Must be done -after- protected store is initialized, during table store init
#[cfg_attr(test, allow(unused_variables))]
async fn setup_node_ids(&self, table_store: &TableStore) -> VeilidAPIResult<()> {
let mut out_node_id = TypedNodeIdGroup::new();
let mut out_node_id_secret = TypedSecretKeyGroup::new();
let mut out_node_id = NodeIdGroup::new();
let mut out_node_id_secret = SecretKeyGroup::new();
for ck in VALID_CRYPTO_KINDS {
let vcrypto = self
@ -451,8 +451,8 @@ impl Crypto {
let (node_id, node_id_secret) = {
let kp = vcrypto.generate_keypair().await;
(
TypedNodeId::new(ck, kp.key.into()),
TypedSecretKey::new(ck, kp.secret),
NodeId::new(ck, kp.key.into()),
SecretKey::new(ck, kp.secret),
)
};
#[cfg(not(test))]

View file

@ -6,7 +6,7 @@ use digest::Digest;
const AEAD_OVERHEAD: usize = PUBLIC_KEY_LENGTH;
pub const CRYPTO_KIND_NONE: CryptoKind = CryptoKind(*b"NONE");
pub fn none_generate_keypair() -> KeyPair {
pub fn none_generate_keypair() -> BareKeyPair {
let mut csprng = VeilidRng {};
let mut pub_bytes = [0u8; PUBLIC_KEY_LENGTH];
let mut sec_bytes = [0u8; SECRET_KEY_LENGTH];
@ -14,9 +14,9 @@ pub fn none_generate_keypair() -> KeyPair {
for n in 0..PUBLIC_KEY_LENGTH {
sec_bytes[n] = !pub_bytes[n];
}
let dht_key = PublicKey::new(pub_bytes);
let dht_key_secret = SecretKey::new(sec_bytes);
KeyPair::new(dht_key, dht_key_secret)
let dht_key = BarePublicKey::new(pub_bytes);
let dht_key_secret = BareSecretKey::new(sec_bytes);
BareKeyPair::new(dht_key, dht_key_secret)
}
fn do_xor_32(a: &[u8], b: &[u8]) -> [u8; 32] {
@ -71,7 +71,11 @@ impl CryptoSystem for CryptoSystemNONE {
}
// Cached Operations
fn cached_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult<SharedSecret> {
fn cached_dh(
&self,
key: &BarePublicKey,
secret: &BareSecretKey,
) -> VeilidAPIResult<BareSharedSecret> {
self.crypto()
.cached_dh_internal::<CryptoSystemNONE>(self, key, secret)
}
@ -105,43 +109,54 @@ impl CryptoSystem for CryptoSystemNONE {
return Ok(&self.hash_password(password, &salt)? == password_hash);
}
fn derive_shared_secret(&self, password: &[u8], salt: &[u8]) -> VeilidAPIResult<SharedSecret> {
fn derive_shared_secret(
&self,
password: &[u8],
salt: &[u8],
) -> VeilidAPIResult<BareSharedSecret> {
if salt.len() < Salt::MIN_LENGTH || salt.len() > Salt::MAX_LENGTH {
apibail_generic!("invalid salt length");
}
Ok(SharedSecret::new(
Ok(BareSharedSecret::new(
*blake3::hash(self.hash_password(password, salt)?.as_bytes()).as_bytes(),
))
}
fn random_nonce(&self) -> Nonce {
fn random_nonce(&self) -> BareNonce {
let mut nonce = [0u8; NONCE_LENGTH];
random_bytes(&mut nonce);
Nonce::new(nonce)
BareNonce::new(nonce)
}
fn random_shared_secret(&self) -> SharedSecret {
fn random_shared_secret(&self) -> BareSharedSecret {
let mut s = [0u8; SHARED_SECRET_LENGTH];
random_bytes(&mut s);
SharedSecret::new(s)
BareSharedSecret::new(s)
}
fn compute_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult<SharedSecret> {
fn compute_dh(
&self,
key: &BarePublicKey,
secret: &BareSecretKey,
) -> VeilidAPIResult<BareSharedSecret> {
let s = do_xor_32(&key.bytes, &secret.bytes);
Ok(SharedSecret::new(s))
Ok(BareSharedSecret::new(s))
}
fn generate_keypair(&self) -> KeyPair {
fn generate_keypair(&self) -> BareKeyPair {
none_generate_keypair()
}
fn generate_hash(&self, data: &[u8]) -> HashDigest {
HashDigest::new(*blake3::hash(data).as_bytes())
fn generate_hash(&self, data: &[u8]) -> BareHashDigest {
BareHashDigest::new(*blake3::hash(data).as_bytes())
}
fn generate_hash_reader(&self, reader: &mut dyn std::io::Read) -> VeilidAPIResult<PublicKey> {
fn generate_hash_reader(
&self,
reader: &mut dyn std::io::Read,
) -> VeilidAPIResult<BarePublicKey> {
let mut hasher = blake3::Hasher::new();
std::io::copy(reader, &mut hasher).map_err(VeilidAPIError::generic)?;
Ok(PublicKey::new(*hasher.finalize().as_bytes()))
Ok(BarePublicKey::new(*hasher.finalize().as_bytes()))
}
// Validation
fn validate_keypair(&self, dht_key: &PublicKey, dht_key_secret: &SecretKey) -> bool {
fn validate_keypair(&self, dht_key: &BarePublicKey, dht_key_secret: &BareSecretKey) -> bool {
let data = vec![0u8; 512];
let Ok(sig) = self.sign(dht_key, dht_key_secret, &data) else {
return false;
@ -151,14 +166,14 @@ impl CryptoSystem for CryptoSystemNONE {
};
v
}
fn validate_hash(&self, data: &[u8], dht_key: &HashDigest) -> bool {
fn validate_hash(&self, data: &[u8], dht_key: &BareHashDigest) -> bool {
let bytes = *blake3::hash(data).as_bytes();
bytes == dht_key.bytes
}
fn validate_hash_reader(
&self,
reader: &mut dyn std::io::Read,
dht_key: &HashDigest,
dht_key: &BareHashDigest,
) -> VeilidAPIResult<bool> {
let mut hasher = blake3::Hasher::new();
std::io::copy(reader, &mut hasher).map_err(VeilidAPIError::generic)?;
@ -166,23 +181,23 @@ impl CryptoSystem for CryptoSystemNONE {
Ok(bytes == dht_key.bytes)
}
// Distance Metric
fn distance(&self, key1: &HashDigest, key2: &HashDigest) -> HashDistance {
fn distance(&self, key1: &BareHashDigest, key2: &BareHashDigest) -> BareHashDistance {
let mut bytes = [0u8; HASH_DIGEST_LENGTH];
for (n, byte) in bytes.iter_mut().enumerate() {
*byte = key1.bytes[n] ^ key2.bytes[n];
}
HashDistance::new(bytes)
BareHashDistance::new(bytes)
}
// Authentication
fn sign(
&self,
dht_key: &PublicKey,
dht_key_secret: &SecretKey,
dht_key: &BarePublicKey,
dht_key_secret: &BareSecretKey,
data: &[u8],
) -> VeilidAPIResult<Signature> {
) -> VeilidAPIResult<BareSignature> {
if !is_bytes_eq_32(&do_xor_32(&dht_key.bytes, &dht_key_secret.bytes), 0xFFu8) {
return Err(VeilidAPIError::parse_error(
"Keypair is invalid",
@ -197,15 +212,15 @@ impl CryptoSystem for CryptoSystemNONE {
let mut sig_bytes = [0u8; SIGNATURE_LENGTH];
sig_bytes[0..32].copy_from_slice(&in_sig_bytes[0..32]);
sig_bytes[32..64].copy_from_slice(&do_xor_32(&in_sig_bytes[32..64], &dht_key_secret.bytes));
let dht_sig = Signature::new(sig_bytes.into());
let dht_sig = BareSignature::new(sig_bytes.into());
println!("DEBUG dht_sig: {:?}", dht_sig);
Ok(dht_sig)
}
fn verify(
&self,
dht_key: &PublicKey,
dht_key: &BarePublicKey,
data: &[u8],
signature: &Signature,
signature: &BareSignature,
) -> VeilidAPIResult<bool> {
let mut dig = Blake3Digest512::new();
dig.update(data);
@ -234,8 +249,8 @@ impl CryptoSystem for CryptoSystemNONE {
fn decrypt_in_place_aead(
&self,
body: &mut Vec<u8>,
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
_associated_data: Option<&[u8]>,
) -> VeilidAPIResult<()> {
let mut blob = nonce.bytes.to_vec();
@ -256,8 +271,8 @@ impl CryptoSystem for CryptoSystemNONE {
fn decrypt_aead(
&self,
body: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<Vec<u8>> {
let mut out = body.to_vec();
@ -270,8 +285,8 @@ impl CryptoSystem for CryptoSystemNONE {
fn encrypt_in_place_aead(
&self,
body: &mut Vec<u8>,
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
_associated_data: Option<&[u8]>,
) -> VeilidAPIResult<()> {
let mut blob = nonce.bytes.to_vec();
@ -285,8 +300,8 @@ impl CryptoSystem for CryptoSystemNONE {
fn encrypt_aead(
&self,
body: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<Vec<u8>> {
let mut out = body.to_vec();
@ -297,7 +312,12 @@ impl CryptoSystem for CryptoSystemNONE {
}
// NoAuth Encrypt/Decrypt
fn crypt_in_place_no_auth(&self, body: &mut [u8], nonce: &Nonce, shared_secret: &SharedSecret) {
fn crypt_in_place_no_auth(
&self,
body: &mut [u8],
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) {
let mut blob = nonce.bytes.to_vec();
blob.extend_from_slice(&[0u8; 8]);
let blob = do_xor_32(&blob, &shared_secret.bytes);
@ -308,8 +328,8 @@ impl CryptoSystem for CryptoSystemNONE {
&self,
in_buf: &[u8],
out_buf: &mut [u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) {
let mut blob = nonce.bytes.to_vec();
blob.extend_from_slice(&[0u8; 8]);
@ -320,8 +340,8 @@ impl CryptoSystem for CryptoSystemNONE {
fn crypt_no_auth_aligned_8(
&self,
in_buf: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) -> Vec<u8> {
let mut out_buf = unsafe { aligned_8_u8_vec_uninit(in_buf.len()) };
self.crypt_b2b_no_auth(in_buf, &mut out_buf, nonce, shared_secret);
@ -331,8 +351,8 @@ impl CryptoSystem for CryptoSystemNONE {
fn crypt_no_auth_unaligned(
&self,
in_buf: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) -> Vec<u8> {
let mut out_buf = unsafe { unaligned_u8_vec_uninit(in_buf.len()) };
self.crypt_b2b_no_auth(in_buf, &mut out_buf, nonce, shared_secret);

View file

@ -29,14 +29,14 @@ pub const RECEIPT_MAGIC: &[u8; 3] = b"RCP";
/// nonce: [u8; 24], // 0x0A: Randomly chosen bytes that represent a unique receipt. Could be used to encrypt the extra data, but it's not required.
/// sender_id: [u8; 32], // 0x22: Node ID of the message source, which is the public key of the sender
/// extra_data: [u8; ??], // 0x42: Extra data is appended (arbitrary extra data, not encrypted by receipt itself, maximum size is 1250 bytes)
/// signature: [u8; 64], // 0x?? (end-0x40): Signature of the entire receipt including header and extra data is appended to the packet
/// signature: [u8; 64], // 0x?? (end-0x40): BareSignature of the entire receipt including header and extra data is appended to the packet
/// }
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Receipt {
version: u8,
crypto_kind: CryptoKind,
nonce: Nonce,
sender_id: NodeId,
nonce: BareNonce,
sender_id: BareNodeId,
extra_data: Vec<u8>,
}
@ -44,8 +44,8 @@ impl Receipt {
pub fn try_new<D: AsRef<[u8]>>(
version: u8,
crypto_kind: CryptoKind,
nonce: Nonce,
sender_id: NodeId,
nonce: BareNonce,
sender_id: BareNodeId,
extra_data: D,
) -> VeilidAPIResult<Self> {
assert!(VALID_ENVELOPE_VERSIONS.contains(&version));
@ -110,14 +110,14 @@ impl Receipt {
}
// Get sender id
let sender_id = NodeId::new(
let sender_id = BareNodeId::new(
data[0x22..0x42]
.try_into()
.map_err(VeilidAPIError::internal)?,
);
// Get signature
let signature = Signature::new(
let signature = BareSignature::new(
data[(data.len() - 64)..]
.try_into()
.map_err(VeilidAPIError::internal)?,
@ -132,7 +132,7 @@ impl Receipt {
}
// Get nonce
let nonce: Nonce = Nonce::new(
let nonce: BareNonce = BareNonce::new(
data[0x0A..0x22]
.try_into()
.map_err(VeilidAPIError::internal)?,
@ -152,7 +152,11 @@ impl Receipt {
}
#[instrument(level = "trace", target = "receipt", skip_all, err)]
pub fn to_signed_data(&self, crypto: &Crypto, secret: &SecretKey) -> VeilidAPIResult<Vec<u8>> {
pub fn to_signed_data(
&self,
crypto: &Crypto,
secret: &BareSecretKey,
) -> VeilidAPIResult<Vec<u8>> {
// Ensure extra data isn't too long
let receipt_size: usize = self.extra_data.len() + MIN_RECEIPT_SIZE;
if receipt_size > MAX_RECEIPT_SIZE {
@ -205,18 +209,18 @@ impl Receipt {
self.crypto_kind
}
pub fn get_nonce(&self) -> Nonce {
pub fn get_nonce(&self) -> BareNonce {
self.nonce
}
#[expect(dead_code)]
pub fn get_sender_id(&self) -> NodeId {
pub fn get_sender_id(&self) -> BareNodeId {
self.sender_id
}
#[expect(dead_code)]
pub fn get_sender_typed_id(&self) -> TypedNodeId {
TypedNodeId::new(self.crypto_kind, self.sender_id)
pub fn get_sender_typed_id(&self) -> NodeId {
NodeId::new(self.crypto_kind, self.sender_id)
}
#[must_use]

View file

@ -3,7 +3,7 @@ use super::*;
pub async fn test_envelope_round_trip(
envelope_version: EnvelopeVersion,
vcrypto: &AsyncCryptoSystemGuard<'_>,
network_key: Option<SharedSecret>,
network_key: Option<BareSharedSecret>,
) {
let crypto = vcrypto.crypto();
if network_key.is_some() {

View file

@ -141,7 +141,7 @@ pub async fn test_sign_and_verify(vcrypto: &AsyncCryptoSystemGuard<'_>) {
pub async fn test_key_conversions(vcrypto: &AsyncCryptoSystemGuard<'_>) {
// Test default key
let (dht_key, dht_key_secret) = (PublicKey::default(), SecretKey::default());
let (dht_key, dht_key_secret) = (BarePublicKey::default(), BareSecretKey::default());
assert_eq!(dht_key.bytes, EMPTY_KEY);
assert_eq!(dht_key_secret.bytes, EMPTY_KEY_SECRET);
let dht_key_string = String::from(&dht_key);
@ -172,49 +172,49 @@ pub async fn test_key_conversions(vcrypto: &AsyncCryptoSystemGuard<'_>) {
assert_ne!(dht_key_secret2_string, dht_key2_string);
// Assert they convert back correctly
let dht_key_back = PublicKey::try_from(dht_key_string.as_str()).unwrap();
let dht_key_back2 = PublicKey::try_from(dht_key_string2.as_str()).unwrap();
let dht_key_back = BarePublicKey::try_from(dht_key_string.as_str()).unwrap();
let dht_key_back2 = BarePublicKey::try_from(dht_key_string2.as_str()).unwrap();
assert_eq!(dht_key_back, dht_key_back2);
assert_eq!(dht_key_back, dht_key);
assert_eq!(dht_key_back2, dht_key);
let dht_key_secret_back = SecretKey::try_from(dht_key_secret_string.as_str()).unwrap();
let dht_key_secret_back = BareSecretKey::try_from(dht_key_secret_string.as_str()).unwrap();
assert_eq!(dht_key_secret_back, dht_key_secret);
let dht_key2_back = PublicKey::try_from(dht_key2_string.as_str()).unwrap();
let dht_key2_back2 = PublicKey::try_from(dht_key2_string2.as_str()).unwrap();
let dht_key2_back = BarePublicKey::try_from(dht_key2_string.as_str()).unwrap();
let dht_key2_back2 = BarePublicKey::try_from(dht_key2_string2.as_str()).unwrap();
assert_eq!(dht_key2_back, dht_key2_back2);
assert_eq!(dht_key2_back, dht_key2);
assert_eq!(dht_key2_back2, dht_key2);
let dht_key_secret2_back = SecretKey::try_from(dht_key_secret2_string.as_str()).unwrap();
let dht_key_secret2_back = BareSecretKey::try_from(dht_key_secret2_string.as_str()).unwrap();
assert_eq!(dht_key_secret2_back, dht_key_secret2);
// Assert string roundtrip
assert_eq!(String::from(&dht_key2_back), dht_key2_string);
// These conversions should fail
assert!(PublicKey::try_from("whatever").is_err());
assert!(SecretKey::try_from("whatever").is_err());
assert!(PublicKey::try_from("").is_err());
assert!(SecretKey::try_from("").is_err());
assert!(PublicKey::try_from(" ").is_err());
assert!(SecretKey::try_from(" ").is_err());
assert!(PublicKey::try_from(
assert!(BarePublicKey::try_from("whatever").is_err());
assert!(BareSecretKey::try_from("whatever").is_err());
assert!(BarePublicKey::try_from("").is_err());
assert!(BareSecretKey::try_from("").is_err());
assert!(BarePublicKey::try_from(" ").is_err());
assert!(BareSecretKey::try_from(" ").is_err());
assert!(BarePublicKey::try_from(
"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"
)
.is_err());
assert!(SecretKey::try_from(
assert!(BareSecretKey::try_from(
"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"
)
.is_err());
}
pub async fn test_encode_decode(vcrypto: &AsyncCryptoSystemGuard<'_>) {
let dht_key = PublicKey::try_decode("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA").unwrap();
let dht_key = BarePublicKey::try_decode("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA").unwrap();
let dht_key_secret =
SecretKey::try_decode("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA").unwrap();
let dht_key_b = PublicKey::new(EMPTY_KEY);
let dht_key_secret_b = SecretKey::new(EMPTY_KEY_SECRET);
BareSecretKey::try_decode("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA").unwrap();
let dht_key_b = BarePublicKey::new(EMPTY_KEY);
let dht_key_secret_b = BareSecretKey::new(EMPTY_KEY_SECRET);
assert_eq!(dht_key, dht_key_b);
assert_eq!(dht_key_secret, dht_key_secret_b);
@ -230,26 +230,26 @@ pub async fn test_encode_decode(vcrypto: &AsyncCryptoSystemGuard<'_>) {
let e2s = dht_key_secret2.encode();
trace!("e2s: {:?}", e2s);
let d1 = PublicKey::try_decode(e1.as_str()).unwrap();
let d1 = BarePublicKey::try_decode(e1.as_str()).unwrap();
trace!("d1: {:?}", d1);
assert_eq!(dht_key, d1);
let d1s = SecretKey::try_decode(e1s.as_str()).unwrap();
let d1s = BareSecretKey::try_decode(e1s.as_str()).unwrap();
trace!("d1s: {:?}", d1s);
assert_eq!(dht_key_secret, d1s);
let d2 = PublicKey::try_decode(e2.as_str()).unwrap();
let d2 = BarePublicKey::try_decode(e2.as_str()).unwrap();
trace!("d2: {:?}", d2);
assert_eq!(dht_key2, d2);
let d2s = SecretKey::try_decode(e2s.as_str()).unwrap();
let d2s = BareSecretKey::try_decode(e2s.as_str()).unwrap();
trace!("d2s: {:?}", d2s);
assert_eq!(dht_key_secret2, d2s);
// Failures
let f1 = SecretKey::try_decode("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
let f1 = BareSecretKey::try_decode("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
assert!(f1.is_err());
let f2 = SecretKey::try_decode("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&");
let f2 = BareSecretKey::try_decode("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&");
assert!(f2.is_err());
}
@ -258,7 +258,7 @@ pub fn test_typed_convert(vcrypto: &AsyncCryptoSystemGuard<'_>) {
"{}:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ",
vcrypto.kind()
);
let tk1 = TypedPublicKey::from_str(&tks1).expect("failed");
let tk1 = PublicKey::from_str(&tks1).expect("failed");
let tks1x = tk1.to_string();
assert_eq!(tks1, tks1x);
@ -266,35 +266,35 @@ pub fn test_typed_convert(vcrypto: &AsyncCryptoSystemGuard<'_>) {
"{}:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzd",
vcrypto.kind()
);
let _tk2 = TypedPublicKey::from_str(&tks2).expect_err("succeeded when it shouldnt have");
let _tk2 = PublicKey::from_str(&tks2).expect_err("succeeded when it shouldnt have");
let tks3 = "XXXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ".to_string();
let tk3 = TypedPublicKey::from_str(&tks3).expect("failed");
let tk3 = PublicKey::from_str(&tks3).expect("failed");
let tks3x = tk3.to_string();
assert_eq!(tks3, tks3x);
let tks4 = "XXXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzd".to_string();
let _tk4 = TypedPublicKey::from_str(&tks4).expect_err("succeeded when it shouldnt have");
let _tk4 = PublicKey::from_str(&tks4).expect_err("succeeded when it shouldnt have");
let tks5 = "XXX:7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ".to_string();
let _tk5 = TypedPublicKey::from_str(&tks5).expect_err("succeeded when it shouldnt have");
let _tk5 = PublicKey::from_str(&tks5).expect_err("succeeded when it shouldnt have");
let tks6 = "7lxDEabK_qgjbe38RtBa3IZLrud84P6NhGP-pRTZzdQ".to_string();
let tk6 = TypedPublicKey::from_str(&tks6).expect("failed");
let tk6 = PublicKey::from_str(&tks6).expect("failed");
let tks6x = tk6.to_string();
assert!(tks6x.ends_with(&tks6));
let b = Vec::from(tk6);
let tk7 = TypedPublicKey::try_from(b).expect("should succeed");
let tk7 = PublicKey::try_from(b).expect("should succeed");
assert_eq!(tk7, tk6);
let b = Vec::from(tk6);
let tk8 = TypedPublicKey::try_from(b.as_slice()).expect("should succeed");
let tk8 = PublicKey::try_from(b.as_slice()).expect("should succeed");
assert_eq!(tk8, tk6);
}
async fn test_hash(vcrypto: &AsyncCryptoSystemGuard<'_>) {
let mut s = BTreeSet::<HashDigest>::new();
let mut s = BTreeSet::<BareHashDigest>::new();
let k1 = vcrypto.generate_hash("abc".as_bytes()).await;
let k2 = vcrypto.generate_hash("abcd".as_bytes()).await;
@ -390,23 +390,23 @@ async fn test_operations(vcrypto: &AsyncCryptoSystemGuard<'_>) {
}
pub fn test_public_key_ordering() {
let k1 = PublicKey::new([
let k1 = BarePublicKey::new([
128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
]);
let k2 = PublicKey::new([
let k2 = BarePublicKey::new([
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
]);
let k3 = PublicKey::new([
let k3 = BarePublicKey::new([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 128,
]);
let k4 = PublicKey::new([
let k4 = BarePublicKey::new([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1,
]);
let k5 = PublicKey::new([
let k5 = BarePublicKey::new([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
]);

View file

@ -291,83 +291,95 @@ macro_rules! byte_array_type {
/////////////////////////////////////////
byte_array_type!(PublicKey, PUBLIC_KEY_LENGTH, PUBLIC_KEY_LENGTH_ENCODED);
byte_array_type!(SecretKey, SECRET_KEY_LENGTH, SECRET_KEY_LENGTH_ENCODED);
byte_array_type!(Signature, SIGNATURE_LENGTH, SIGNATURE_LENGTH_ENCODED);
byte_array_type!(Nonce, NONCE_LENGTH, NONCE_LENGTH_ENCODED);
byte_array_type!(BarePublicKey, PUBLIC_KEY_LENGTH, PUBLIC_KEY_LENGTH_ENCODED);
byte_array_type!(BareSecretKey, SECRET_KEY_LENGTH, SECRET_KEY_LENGTH_ENCODED);
byte_array_type!(BareSignature, SIGNATURE_LENGTH, SIGNATURE_LENGTH_ENCODED);
byte_array_type!(BareNonce, NONCE_LENGTH, NONCE_LENGTH_ENCODED);
/*
Notes:
- These are actually HashDigest types, but not interchangable:
- RouteId (eventually will be a RecordKey type with DHT Routes)
- RecordKey
- SharedSecret
- These are actually BareHashDigest types, but not interchangable:
- BareRouteId (eventually will be a BareRecordKey type with DHT Routes)
- BareRecordKey
- BareSharedSecret
*/
// HashDigest sub-types
byte_array_type!(HashDigest, HASH_DIGEST_LENGTH, HASH_DIGEST_LENGTH_ENCODED);
// BareHashDigest sub-types
byte_array_type!(
SharedSecret,
BareHashDigest,
HASH_DIGEST_LENGTH,
HASH_DIGEST_LENGTH_ENCODED
);
byte_array_type!(
BareSharedSecret,
SHARED_SECRET_LENGTH,
SHARED_SECRET_LENGTH_ENCODED
);
byte_array_type!(RouteId, ROUTE_ID_LENGTH, ROUTE_ID_LENGTH_ENCODED);
byte_array_type!(RecordKey, HASH_DIGEST_LENGTH, HASH_DIGEST_LENGTH_ENCODED);
byte_array_type!(HashDistance, HASH_DIGEST_LENGTH, HASH_DIGEST_LENGTH_ENCODED);
byte_array_type!(BareRouteId, ROUTE_ID_LENGTH, ROUTE_ID_LENGTH_ENCODED);
byte_array_type!(
BareRecordKey,
HASH_DIGEST_LENGTH,
HASH_DIGEST_LENGTH_ENCODED
);
byte_array_type!(
BareHashDistance,
HASH_DIGEST_LENGTH,
HASH_DIGEST_LENGTH_ENCODED
);
// NodeId is currently the same as PublicKey, but will eventually be a sub-type of HashDigest.
byte_array_type!(NodeId, PUBLIC_KEY_LENGTH, PUBLIC_KEY_LENGTH_ENCODED);
// BareNodeId is currently the same as BarePublicKey, but will eventually be a sub-type of BareHashDigest.
byte_array_type!(BareNodeId, PUBLIC_KEY_LENGTH, PUBLIC_KEY_LENGTH_ENCODED);
#[expect(dead_code)]
trait HashCoordinate {
fn from_hash_coordinate(hash_digest: HashDigest) -> Self;
fn to_hash_coordinate(&self) -> HashDigest;
fn from_hash_coordinate(hash_digest: BareHashDigest) -> Self;
fn to_hash_coordinate(&self) -> BareHashDigest;
}
// Temporary adapters for converting to/from HashDigest types
// Temporary adapters for converting to/from BareHashDigest types
// Removing these will show where there's still issues.
impl From<HashDigest> for SharedSecret {
fn from(value: HashDigest) -> Self {
impl From<BareHashDigest> for BareSharedSecret {
fn from(value: BareHashDigest) -> Self {
Self::new(value.bytes)
}
}
impl From<HashDigest> for RecordKey {
fn from(value: HashDigest) -> Self {
impl From<BareHashDigest> for BareRecordKey {
fn from(value: BareHashDigest) -> Self {
Self::new(value.bytes)
}
}
impl From<RecordKey> for HashDigest {
fn from(value: RecordKey) -> Self {
impl From<BareRecordKey> for BareHashDigest {
fn from(value: BareRecordKey) -> Self {
Self::new(value.bytes)
}
}
impl From<NodeId> for HashDigest {
fn from(value: NodeId) -> Self {
impl From<BareNodeId> for BareHashDigest {
fn from(value: BareNodeId) -> Self {
Self::new(value.bytes)
}
}
impl From<HashDigest> for PublicKey {
fn from(value: HashDigest) -> Self {
impl From<BareHashDigest> for BarePublicKey {
fn from(value: BareHashDigest) -> Self {
Self::new(value.bytes)
}
}
/*
- NodeId currently equals PublicKey, but should be distinct from PublicKey.
- NodeId eventually should be a HashDigest type that's constructable from a PublicKey
- BareNodeId currently equals BarePublicKey, but should be distinct from BarePublicKey.
- BareNodeId eventually should be a BareHashDigest type that's constructable from a BarePublicKey
*/
impl From<PublicKey> for NodeId {
fn from(value: PublicKey) -> Self {
impl From<BarePublicKey> for BareNodeId {
fn from(value: BarePublicKey) -> Self {
Self::new(value.bytes)
}
}
impl From<NodeId> for PublicKey {
fn from(value: NodeId) -> Self {
impl From<BareNodeId> for BarePublicKey {
fn from(value: BareNodeId) -> Self {
Self::new(value.bytes)
}
}

View file

@ -2,89 +2,89 @@ use super::*;
#[derive(Clone, Copy, Default, PartialOrd, Ord, PartialEq, Eq, Hash)]
#[must_use]
pub struct KeyPair {
pub key: PublicKey,
pub secret: SecretKey,
pub struct BareKeyPair {
pub key: BarePublicKey,
pub secret: BareSecretKey,
}
cfg_if::cfg_if! {
if #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] {
#[wasm_bindgen(typescript_custom_section)]
const KEYPAIR_TYPE: &'static str = r#"
export type KeyPair = `${PublicKey}:${SecretKey}`;
export type BareKeyPair = `${BarePublicKey}:${BareSecretKey}`;
"#;
}
}
impl KeyPair {
pub fn new(key: PublicKey, secret: SecretKey) -> Self {
impl BareKeyPair {
pub fn new(key: BarePublicKey, secret: BareSecretKey) -> Self {
Self { key, secret }
}
pub fn split(&self) -> (PublicKey, SecretKey) {
pub fn split(&self) -> (BarePublicKey, BareSecretKey) {
(self.key, self.secret)
}
pub fn into_split(self) -> (PublicKey, SecretKey) {
pub fn into_split(self) -> (BarePublicKey, BareSecretKey) {
(self.key, self.secret)
}
}
impl Encodable for KeyPair {
impl Encodable for BareKeyPair {
fn encode(&self) -> String {
format!("{}:{}", self.key.encode(), self.secret.encode())
}
fn encoded_len() -> usize {
PublicKey::encoded_len() + 1 + SecretKey::encoded_len()
BarePublicKey::encoded_len() + 1 + BareSecretKey::encoded_len()
}
fn try_decode_bytes(b: &[u8]) -> VeilidAPIResult<Self> {
if b.len() != Self::encoded_len() {
apibail_parse_error!("input has wrong encoded length", format!("len={}", b.len()));
}
let key = PublicKey::try_decode_bytes(&b[0..PublicKey::encoded_len()])?;
let secret = SecretKey::try_decode_bytes(&b[(PublicKey::encoded_len() + 1)..])?;
Ok(KeyPair { key, secret })
let key = BarePublicKey::try_decode_bytes(&b[0..BarePublicKey::encoded_len()])?;
let secret = BareSecretKey::try_decode_bytes(&b[(BarePublicKey::encoded_len() + 1)..])?;
Ok(BareKeyPair { key, secret })
}
}
impl fmt::Display for KeyPair {
impl fmt::Display for BareKeyPair {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.encode())
}
}
impl fmt::Debug for KeyPair {
impl fmt::Debug for BareKeyPair {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "KeyPair({})", self.encode())
write!(f, "BareKeyPair({})", self.encode())
}
}
impl From<&KeyPair> for String {
fn from(value: &KeyPair) -> Self {
impl From<&BareKeyPair> for String {
fn from(value: &BareKeyPair) -> Self {
value.encode()
}
}
impl FromStr for KeyPair {
impl FromStr for BareKeyPair {
type Err = VeilidAPIError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
KeyPair::try_from(s)
BareKeyPair::try_from(s)
}
}
impl TryFrom<String> for KeyPair {
impl TryFrom<String> for BareKeyPair {
type Error = VeilidAPIError;
fn try_from(value: String) -> Result<Self, Self::Error> {
KeyPair::try_from(value.as_str())
BareKeyPair::try_from(value.as_str())
}
}
impl TryFrom<&str> for KeyPair {
impl TryFrom<&str> for BareKeyPair {
type Error = VeilidAPIError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::try_decode(value)
}
}
impl serde::Serialize for KeyPair {
impl serde::Serialize for BareKeyPair {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
@ -94,15 +94,15 @@ impl serde::Serialize for KeyPair {
}
}
impl<'de> serde::Deserialize<'de> for KeyPair {
impl<'de> serde::Deserialize<'de> for BareKeyPair {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = <String as serde::Deserialize>::deserialize(deserializer)?;
if s.is_empty() {
return Ok(KeyPair::default());
return Ok(BareKeyPair::default());
}
KeyPair::try_decode(s.as_str()).map_err(serde::de::Error::custom)
BareKeyPair::try_decode(s.as_str()).map_err(serde::de::Error::custom)
}
}

View file

@ -53,77 +53,77 @@ pub use crypto_typed_group::*;
pub use keypair::*;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedPublicKey = CryptoTyped<PublicKey>;
pub type PublicKey = CryptoTyped<BarePublicKey>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedSecretKey = CryptoTyped<SecretKey>;
pub type SecretKey = CryptoTyped<BareSecretKey>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedKeyPair = CryptoTyped<KeyPair>;
pub type KeyPair = CryptoTyped<BareKeyPair>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedSignature = CryptoTyped<Signature>;
pub type Signature = CryptoTyped<BareSignature>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedSharedSecret = CryptoTyped<SharedSecret>;
pub type SharedSecret = CryptoTyped<BareSharedSecret>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedRouteId = CryptoTyped<RouteId>;
pub type RouteId = CryptoTyped<BareRouteId>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedRecordKey = CryptoTyped<RecordKey>;
pub type RecordKey = CryptoTyped<BareRecordKey>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedNodeId = CryptoTyped<NodeId>;
pub type NodeId = CryptoTyped<BareNodeId>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedHashDigest = CryptoTyped<HashDigest>;
pub type HashDigest = CryptoTyped<BareHashDigest>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedPublicKeyGroup = CryptoTypedGroup<PublicKey>;
pub type PublicKeyGroup = CryptoTypedGroup<BarePublicKey>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedSecretKeyGroup = CryptoTypedGroup<SecretKey>;
pub type SecretKeyGroup = CryptoTypedGroup<BareSecretKey>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedKeyPairGroup = CryptoTypedGroup<KeyPair>;
pub type KeyPairGroup = CryptoTypedGroup<BareKeyPair>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedSignatureGroup = CryptoTypedGroup<Signature>;
pub type SignatureGroup = CryptoTypedGroup<BareSignature>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedSharedSecretGroup = CryptoTypedGroup<SharedSecret>;
pub type SharedSecretGroup = CryptoTypedGroup<BareSharedSecret>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedRouteIdGroup = CryptoTypedGroup<RouteId>;
pub type RouteIdGroup = CryptoTypedGroup<BareRouteId>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedRecordKeyGroup = CryptoTypedGroup<RecordKey>;
pub type RecordKeyGroup = CryptoTypedGroup<BareRecordKey>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedNodeIdGroup = CryptoTypedGroup<NodeId>;
pub type NodeIdGroup = CryptoTypedGroup<BareNodeId>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedHashDigestGroup = CryptoTypedGroup<HashDigest>;
pub type HashDigestGroup = CryptoTypedGroup<BareHashDigest>;
impl From<TypedNodeId> for TypedHashDigest {
fn from(value: TypedNodeId) -> Self {
TypedHashDigest::new(value.kind, value.value.into())
impl From<NodeId> for HashDigest {
fn from(value: NodeId) -> Self {
HashDigest::new(value.kind, value.value.into())
}
}
impl From<TypedRecordKey> for TypedHashDigest {
fn from(value: TypedRecordKey) -> Self {
TypedHashDigest::new(value.kind, value.value.into())
impl From<RecordKey> for HashDigest {
fn from(value: RecordKey) -> Self {
HashDigest::new(value.kind, value.value.into())
}
}
impl From<TypedNodeId> for TypedPublicKey {
fn from(value: TypedNodeId) -> Self {
TypedPublicKey::new(value.kind, value.value.into())
impl From<NodeId> for PublicKey {
fn from(value: NodeId) -> Self {
PublicKey::new(value.kind, value.value.into())
}
}
impl From<TypedPublicKey> for TypedNodeId {
fn from(value: TypedPublicKey) -> Self {
TypedNodeId::new(value.kind, value.value.into())
impl From<PublicKey> for NodeId {
fn from(value: PublicKey) -> Self {
NodeId::new(value.kind, value.value.into())
}
}
impl From<TypedNodeIdGroup> for TypedPublicKeyGroup {
fn from(value: TypedNodeIdGroup) -> Self {
let items: Vec<TypedPublicKey> = value.iter().map(|node_id| (*node_id).into()).collect();
TypedPublicKeyGroup::from(items)
impl From<NodeIdGroup> for PublicKeyGroup {
fn from(value: NodeIdGroup) -> Self {
let items: Vec<PublicKey> = value.iter().map(|node_id| (*node_id).into()).collect();
PublicKeyGroup::from(items)
}
}
impl From<TypedPublicKeyGroup> for TypedNodeIdGroup {
fn from(value: TypedPublicKeyGroup) -> Self {
let items: Vec<TypedNodeId> = value.iter().map(|node_id| (*node_id).into()).collect();
TypedNodeIdGroup::from(items)
impl From<PublicKeyGroup> for NodeIdGroup {
fn from(value: PublicKeyGroup) -> Self {
let items: Vec<NodeId> = value.iter().map(|node_id| (*node_id).into()).collect();
NodeIdGroup::from(items)
}
}

View file

@ -19,11 +19,11 @@ const VEILID_DOMAIN_CRYPT: &[u8] = b"VLD0_CRYPT";
const AEAD_OVERHEAD: usize = 16;
pub const CRYPTO_KIND_VLD0: CryptoKind = CryptoKind(*b"VLD0");
fn public_to_x25519_pk(public: &PublicKey) -> VeilidAPIResult<xd::PublicKey> {
fn public_to_x25519_pk(public: &BarePublicKey) -> VeilidAPIResult<xd::PublicKey> {
let pk_ed = ed::VerifyingKey::from_bytes(&public.bytes).map_err(VeilidAPIError::internal)?;
Ok(xd::PublicKey::from(*pk_ed.to_montgomery().as_bytes()))
}
fn secret_to_x25519_sk(secret: &SecretKey) -> VeilidAPIResult<xd::StaticSecret> {
fn secret_to_x25519_sk(secret: &BareSecretKey) -> VeilidAPIResult<xd::StaticSecret> {
// NOTE: ed::SigningKey.to_scalar() does not produce an unreduced scalar, we want the raw bytes here
// See https://github.com/dalek-cryptography/curve25519-dalek/issues/565
let hash: [u8; SIGNATURE_LENGTH] = ed::Sha512::default()
@ -36,14 +36,14 @@ fn secret_to_x25519_sk(secret: &SecretKey) -> VeilidAPIResult<xd::StaticSecret>
Ok(xd::StaticSecret::from(output))
}
pub(crate) fn vld0_generate_keypair() -> KeyPair {
pub(crate) fn vld0_generate_keypair() -> BareKeyPair {
let mut csprng = VeilidRng {};
let signing_key = ed::SigningKey::generate(&mut csprng);
let verifying_key = signing_key.verifying_key();
let public_key = PublicKey::new(verifying_key.to_bytes());
let secret_key = SecretKey::new(signing_key.to_bytes());
let public_key = BarePublicKey::new(verifying_key.to_bytes());
let secret_key = BareSecretKey::new(signing_key.to_bytes());
KeyPair::new(public_key, secret_key)
BareKeyPair::new(public_key, secret_key)
}
/// V0 CryptoSystem
@ -70,7 +70,11 @@ impl CryptoSystem for CryptoSystemVLD0 {
// Cached Operations
#[instrument(level = "trace", skip_all)]
fn cached_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult<SharedSecret> {
fn cached_dh(
&self,
key: &BarePublicKey,
secret: &BareSecretKey,
) -> VeilidAPIResult<BareSharedSecret> {
self.crypto()
.cached_dh_internal::<CryptoSystemVLD0>(self, key, secret)
}
@ -113,7 +117,11 @@ impl CryptoSystem for CryptoSystemVLD0 {
}
#[instrument(level = "trace", target = "crypto", skip_all)]
fn derive_shared_secret(&self, password: &[u8], salt: &[u8]) -> VeilidAPIResult<SharedSecret> {
fn derive_shared_secret(
&self,
password: &[u8],
salt: &[u8],
) -> VeilidAPIResult<BareSharedSecret> {
if salt.len() < Salt::MIN_LENGTH || salt.len() > Salt::MAX_LENGTH {
apibail_generic!("invalid salt length");
}
@ -125,25 +133,29 @@ impl CryptoSystem for CryptoSystemVLD0 {
argon2
.hash_password_into(password, salt, &mut output_key_material)
.map_err(VeilidAPIError::generic)?;
Ok(SharedSecret::new(output_key_material))
Ok(BareSharedSecret::new(output_key_material))
}
#[instrument(level = "trace", target = "crypto", skip_all)]
fn random_nonce(&self) -> Nonce {
fn random_nonce(&self) -> BareNonce {
let mut nonce = [0u8; NONCE_LENGTH];
random_bytes(&mut nonce);
Nonce::new(nonce)
BareNonce::new(nonce)
}
#[instrument(level = "trace", target = "crypto", skip_all)]
fn random_shared_secret(&self) -> SharedSecret {
fn random_shared_secret(&self) -> BareSharedSecret {
let mut s = [0u8; SHARED_SECRET_LENGTH];
random_bytes(&mut s);
SharedSecret::new(s)
BareSharedSecret::new(s)
}
#[instrument(level = "trace", target = "crypto", skip_all)]
fn compute_dh(&self, key: &PublicKey, secret: &SecretKey) -> VeilidAPIResult<SharedSecret> {
fn compute_dh(
&self,
key: &BarePublicKey,
secret: &BareSecretKey,
) -> VeilidAPIResult<BareSharedSecret> {
let pk_xd = public_to_x25519_pk(key)?;
let sk_xd = secret_to_x25519_sk(secret)?;
@ -154,29 +166,32 @@ impl CryptoSystem for CryptoSystemVLD0 {
hasher.update(&dh_bytes);
let output = hasher.finalize();
Ok(SharedSecret::new(*output.as_bytes()))
Ok(BareSharedSecret::new(*output.as_bytes()))
}
#[instrument(level = "trace", target = "crypto", skip_all)]
fn generate_keypair(&self) -> KeyPair {
fn generate_keypair(&self) -> BareKeyPair {
vld0_generate_keypair()
}
#[instrument(level = "trace", target = "crypto", skip_all)]
fn generate_hash(&self, data: &[u8]) -> HashDigest {
HashDigest::new(*blake3::hash(data).as_bytes())
fn generate_hash(&self, data: &[u8]) -> BareHashDigest {
BareHashDigest::new(*blake3::hash(data).as_bytes())
}
#[instrument(level = "trace", target = "crypto", skip_all)]
fn generate_hash_reader(&self, reader: &mut dyn std::io::Read) -> VeilidAPIResult<PublicKey> {
fn generate_hash_reader(
&self,
reader: &mut dyn std::io::Read,
) -> VeilidAPIResult<BarePublicKey> {
let mut hasher = blake3::Hasher::new();
std::io::copy(reader, &mut hasher).map_err(VeilidAPIError::generic)?;
Ok(PublicKey::new(*hasher.finalize().as_bytes()))
Ok(BarePublicKey::new(*hasher.finalize().as_bytes()))
}
// Validation
#[instrument(level = "trace", target = "crypto", skip_all)]
fn validate_keypair(&self, public_key: &PublicKey, secret_key: &SecretKey) -> bool {
fn validate_keypair(&self, public_key: &BarePublicKey, secret_key: &BareSecretKey) -> bool {
let data = vec![0u8; 512];
let Ok(sig) = self.sign(public_key, secret_key, &data) else {
return false;
@ -188,7 +203,7 @@ impl CryptoSystem for CryptoSystemVLD0 {
}
#[instrument(level = "trace", target = "crypto", skip_all)]
fn validate_hash(&self, data: &[u8], hash_digest: &HashDigest) -> bool {
fn validate_hash(&self, data: &[u8], hash_digest: &BareHashDigest) -> bool {
let bytes = *blake3::hash(data).as_bytes();
bytes == hash_digest.bytes
@ -198,7 +213,7 @@ impl CryptoSystem for CryptoSystemVLD0 {
fn validate_hash_reader(
&self,
reader: &mut dyn std::io::Read,
hash_digest: &HashDigest,
hash_digest: &BareHashDigest,
) -> VeilidAPIResult<bool> {
let mut hasher = blake3::Hasher::new();
std::io::copy(reader, &mut hasher).map_err(VeilidAPIError::generic)?;
@ -208,24 +223,24 @@ impl CryptoSystem for CryptoSystemVLD0 {
// Distance Metric
#[instrument(level = "trace", target = "crypto", skip_all)]
fn distance(&self, hash1: &HashDigest, hash2: &HashDigest) -> HashDistance {
fn distance(&self, hash1: &BareHashDigest, hash2: &BareHashDigest) -> BareHashDistance {
let mut bytes = [0u8; CRYPTO_KEY_LENGTH];
(0..CRYPTO_KEY_LENGTH).for_each(|n| {
bytes[n] = hash1.bytes[n] ^ hash2.bytes[n];
});
HashDistance::new(bytes)
BareHashDistance::new(bytes)
}
// Authentication
#[instrument(level = "trace", target = "crypto", skip_all)]
fn sign(
&self,
public_key: &PublicKey,
secret_key: &SecretKey,
public_key: &BarePublicKey,
secret_key: &BareSecretKey,
data: &[u8],
) -> VeilidAPIResult<Signature> {
) -> VeilidAPIResult<BareSignature> {
let mut kpb: [u8; SECRET_KEY_LENGTH + PUBLIC_KEY_LENGTH] =
[0u8; SECRET_KEY_LENGTH + PUBLIC_KEY_LENGTH];
@ -241,7 +256,7 @@ impl CryptoSystem for CryptoSystemVLD0 {
.sign_prehashed(dig, Some(VEILID_DOMAIN_SIGN))
.map_err(VeilidAPIError::internal)?;
let sig = Signature::new(sig_bytes.to_bytes());
let sig = BareSignature::new(sig_bytes.to_bytes());
if !self.verify(public_key, data, &sig)? {
apibail_internal!("newly created signature does not verify");
@ -252,9 +267,9 @@ impl CryptoSystem for CryptoSystemVLD0 {
#[instrument(level = "trace", target = "crypto", skip_all)]
fn verify(
&self,
public_key: &PublicKey,
public_key: &BarePublicKey,
data: &[u8],
signature: &Signature,
signature: &BareSignature,
) -> VeilidAPIResult<bool> {
let pk = ed::VerifyingKey::from_bytes(&public_key.bytes)
.map_err(|e| VeilidAPIError::parse_error("Public key is invalid", e))?;
@ -281,8 +296,8 @@ impl CryptoSystem for CryptoSystemVLD0 {
fn decrypt_in_place_aead(
&self,
body: &mut Vec<u8>,
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<()> {
let key = ch::Key::from(shared_secret.bytes);
@ -297,8 +312,8 @@ impl CryptoSystem for CryptoSystemVLD0 {
fn decrypt_aead(
&self,
body: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<Vec<u8>> {
let mut out = body.to_vec();
@ -312,8 +327,8 @@ impl CryptoSystem for CryptoSystemVLD0 {
fn encrypt_in_place_aead(
&self,
body: &mut Vec<u8>,
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<()> {
let key = ch::Key::from(shared_secret.bytes);
@ -329,8 +344,8 @@ impl CryptoSystem for CryptoSystemVLD0 {
fn encrypt_aead(
&self,
body: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
associated_data: Option<&[u8]>,
) -> VeilidAPIResult<Vec<u8>> {
let mut out = body.to_vec();
@ -342,7 +357,12 @@ impl CryptoSystem for CryptoSystemVLD0 {
// NoAuth Encrypt/Decrypt
#[instrument(level = "trace", target = "crypto", skip_all)]
fn crypt_in_place_no_auth(&self, body: &mut [u8], nonce: &Nonce, shared_secret: &SharedSecret) {
fn crypt_in_place_no_auth(
&self,
body: &mut [u8],
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) {
let mut cipher =
<XChaCha20 as KeyIvInit>::new(&shared_secret.bytes.into(), &nonce.bytes.into());
cipher.apply_keystream(body);
@ -353,8 +373,8 @@ impl CryptoSystem for CryptoSystemVLD0 {
&self,
in_buf: &[u8],
out_buf: &mut [u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) {
let mut cipher =
<XChaCha20 as KeyIvInit>::new(&shared_secret.bytes.into(), &nonce.bytes.into());
@ -365,8 +385,8 @@ impl CryptoSystem for CryptoSystemVLD0 {
fn crypt_no_auth_aligned_8(
&self,
in_buf: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) -> Vec<u8> {
let mut out_buf = unsafe { aligned_8_u8_vec_uninit(in_buf.len()) };
self.crypt_b2b_no_auth(in_buf, &mut out_buf, nonce, shared_secret);
@ -377,8 +397,8 @@ impl CryptoSystem for CryptoSystemVLD0 {
fn crypt_no_auth_unaligned(
&self,
in_buf: &[u8],
nonce: &Nonce,
shared_secret: &SharedSecret,
nonce: &BareNonce,
shared_secret: &BareSharedSecret,
) -> Vec<u8> {
let mut out_buf = unsafe { unaligned_u8_vec_uninit(in_buf.len()) };
self.crypt_b2b_no_auth(in_buf, &mut out_buf, nonce, shared_secret);

View file

@ -30,7 +30,7 @@ struct AddressFilterInner {
conn_timestamps_by_ip6_prefix: BTreeMap<Ipv6Addr, Vec<Timestamp>>,
punishments_by_ip4: BTreeMap<Ipv4Addr, Punishment>,
punishments_by_ip6_prefix: BTreeMap<Ipv6Addr, Punishment>,
punishments_by_node_id: BTreeMap<TypedNodeId, Punishment>,
punishments_by_node_id: BTreeMap<NodeId, Punishment>,
dial_info_failures: BTreeMap<DialInfo, Timestamp>,
}
@ -178,7 +178,7 @@ impl AddressFilter {
}
// node id
{
let mut dead_keys = Vec::<TypedNodeId>::new();
let mut dead_keys = Vec::<NodeId>::new();
for (key, value) in &mut inner.punishments_by_node_id {
// Drop punishments older than the punishment duration
if cur_ts.as_u64().saturating_sub(value.timestamp.as_u64())
@ -297,19 +297,19 @@ impl AddressFilter {
};
}
fn is_node_id_punished_inner(&self, inner: &AddressFilterInner, node_id: TypedNodeId) -> bool {
fn is_node_id_punished_inner(&self, inner: &AddressFilterInner, node_id: NodeId) -> bool {
if inner.punishments_by_node_id.contains_key(&node_id) {
return true;
}
false
}
pub fn is_node_id_punished(&self, node_id: TypedNodeId) -> bool {
pub fn is_node_id_punished(&self, node_id: NodeId) -> bool {
let inner = self.inner.lock();
self.is_node_id_punished_inner(&inner, node_id)
}
pub fn punish_node_id(&self, node_id: TypedNodeId, reason: PunishmentReason) {
pub fn punish_node_id(&self, node_id: NodeId, reason: PunishmentReason) {
if let Ok(Some(nr)) = self.routing_table().lookup_node_ref(node_id) {
// make the entry dead if it's punished
nr.operate_mut(|_rti, e| e.set_punished(Some(reason)));

View file

@ -4,7 +4,7 @@ impl_veilid_log_facility!("net");
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BootstrapRecord {
node_ids: TypedNodeIdGroup,
node_ids: NodeIdGroup,
envelope_support: Vec<u8>,
dial_info_details: Vec<DialInfoDetail>,
timestamp_secs: Option<u64>,
@ -13,7 +13,7 @@ pub struct BootstrapRecord {
impl BootstrapRecord {
pub fn new(
node_ids: TypedNodeIdGroup,
node_ids: NodeIdGroup,
mut envelope_support: Vec<u8>,
mut dial_info_details: Vec<DialInfoDetail>,
timestamp_secs: Option<u64>,
@ -31,7 +31,7 @@ impl BootstrapRecord {
}
}
pub fn node_ids(&self) -> &TypedNodeIdGroup {
pub fn node_ids(&self) -> &NodeIdGroup {
&self.node_ids
}
pub fn envelope_support(&self) -> &[u8] {
@ -143,7 +143,7 @@ impl BootstrapRecord {
&self,
network_manager: &NetworkManager,
dial_info_converter: &dyn DialInfoConverter,
signing_key_pair: TypedKeyPair,
signing_key_pair: KeyPair,
) -> EyreResult<String> {
let vcommon = self.to_vcommon_string(dial_info_converter).await?;
let ts = if let Some(ts) = self.timestamp_secs() {
@ -156,7 +156,7 @@ impl BootstrapRecord {
let crypto = network_manager.crypto();
let sig = match crypto.generate_signatures(v1.as_bytes(), &[signing_key_pair], |kp, sig| {
TypedSignature::new(kp.kind, sig).to_string()
Signature::new(kp.kind, sig).to_string()
}) {
Ok(v) => {
let Some(sig) = v.first().cloned() else {
@ -226,7 +226,7 @@ impl BootstrapRecord {
network_manager: &NetworkManager,
dial_info_converter: &dyn DialInfoConverter,
record_str: &str,
signing_keys: &[TypedPublicKey],
signing_keys: &[PublicKey],
) -> EyreResult<Option<BootstrapRecord>> {
// All formats split on '|' character
let fields: Vec<String> = record_str
@ -309,10 +309,10 @@ impl BootstrapRecord {
envelope_support.dedup();
// Node Id
let mut node_ids = TypedNodeIdGroup::new();
let mut node_ids = NodeIdGroup::new();
for node_id_str in fields[2].split(',') {
let node_id_str = node_id_str.trim();
let node_id = match TypedNodeId::from_str(node_id_str) {
let node_id = match NodeId::from_str(node_id_str) {
Ok(v) => v,
Err(e) => {
bail!(
@ -376,7 +376,7 @@ impl BootstrapRecord {
dial_info_converter: &dyn DialInfoConverter,
record_str: &str,
fields: &[String],
signing_keys: &[TypedPublicKey],
signing_keys: &[PublicKey],
) -> EyreResult<Option<BootstrapRecord>> {
if fields.len() < 7 {
bail!("invalid number of fields in bootstrap v1 txt record");
@ -384,8 +384,8 @@ impl BootstrapRecord {
// Get signature from last record
let sigstring = fields.last().unwrap();
let sig = TypedSignature::from_str(sigstring)
.wrap_err("invalid signature for bootstrap v1 record")?;
let sig =
Signature::from_str(sigstring).wrap_err("invalid signature for bootstrap v1 record")?;
// Get slice that was signed
let signed_str = &record_str[0..record_str.len() - sigstring.len()];
@ -432,10 +432,10 @@ impl BootstrapRecord {
envelope_support.dedup();
// Node Id
let mut node_ids = TypedNodeIdGroup::new();
let mut node_ids = NodeIdGroup::new();
for node_id_str in fields[2].split(',') {
let node_id_str = node_id_str.trim();
let node_id = match TypedNodeId::from_str(node_id_str) {
let node_id = match NodeId::from_str(node_id_str) {
Ok(v) => v,
Err(e) => {
bail!(

View file

@ -3,7 +3,7 @@ use super::*;
impl_veilid_log_facility!("net");
impl NetworkManager {
pub async fn debug_info_txtrecord(&self, signing_key_pair: TypedKeyPair) -> String {
pub async fn debug_info_txtrecord(&self, signing_key_pair: KeyPair) -> String {
let routing_table = self.routing_table();
let dial_info_details = routing_table.dial_info_details(RoutingDomain::PublicInternet);

View file

@ -193,7 +193,7 @@ impl Default for NetworkManagerStartupContext {
#[derive(Debug)]
struct NetworkManagerInner {
stats: NetworkManagerStats,
client_allowlist: LruCache<TypedNodeId, ClientAllowlistEntry>,
client_allowlist: LruCache<NodeId, ClientAllowlistEntry>,
node_contact_method_cache: NodeContactMethodCache,
address_check: Option<AddressCheck>,
peer_info_change_subscription: Option<EventBusSubscription>,
@ -223,7 +223,7 @@ pub(crate) struct NetworkManager {
address_filter_task: TickTask<EyreReport>,
// Network key
network_key: Option<SharedSecret>,
network_key: Option<BareSharedSecret>,
// Startup context
startup_context: NetworkManagerStartupContext,
@ -531,7 +531,7 @@ impl NetworkManager {
}
#[expect(dead_code)]
pub fn update_client_allowlist(&self, client: TypedNodeId) {
pub fn update_client_allowlist(&self, client: NodeId) {
let mut inner = self.inner.lock();
match inner.client_allowlist.entry(client) {
hashlink::lru_cache::Entry::Occupied(mut entry) => {
@ -546,7 +546,7 @@ impl NetworkManager {
}
#[instrument(level = "trace", skip(self), ret)]
pub fn check_client_allowlist(&self, client: TypedNodeId) -> bool {
pub fn check_client_allowlist(&self, client: NodeId) -> bool {
let mut inner = self.inner.lock();
match inner.client_allowlist.entry(client) {
@ -755,7 +755,7 @@ impl NetworkManager {
pub async fn handle_private_receipt<R: AsRef<[u8]>>(
&self,
receipt_data: R,
private_route: PublicKey,
private_route: BarePublicKey,
) -> NetworkResult<()> {
let Ok(_guard) = self.startup_context.startup_lock.enter() else {
return NetworkResult::service_unavailable("network is not started");
@ -874,7 +874,7 @@ impl NetworkManager {
#[instrument(level = "trace", target = "net", skip_all)]
fn build_envelope<B: AsRef<[u8]>>(
&self,
dest_node_id: TypedNodeId,
dest_node_id: NodeId,
version: u8,
body: B,
) -> EyreResult<Vec<u8>> {

View file

@ -4,7 +4,7 @@ pub const NODE_CONTACT_METHOD_CACHE_SIZE: usize = 1024;
#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct NodeContactMethodCacheKey {
pub node_ids: TypedNodeIdGroup,
pub node_ids: NodeIdGroup,
pub own_node_info_ts: Timestamp,
pub target_node_info_ts: Timestamp,
pub target_node_ref_filter: NodeRefFilter,

View file

@ -17,7 +17,7 @@ pub enum ReceiptEvent {
ReturnedSafety,
ReturnedPrivate {
#[expect(dead_code)]
private_route: PublicKey,
private_route: BarePublicKey,
},
Expired,
Cancelled,
@ -28,7 +28,7 @@ pub(super) enum ReceiptReturned {
OutOfBand,
InBand { inbound_noderef: FilteredNodeRef },
Safety,
Private { private_route: PublicKey },
Private { private_route: BarePublicKey },
}
pub trait ReceiptCallback: Send + 'static {
@ -145,7 +145,7 @@ impl PartialOrd for ReceiptRecordTimestampSort {
///////////////////////////////////
struct ReceiptManagerInner {
records_by_nonce: BTreeMap<Nonce, Arc<Mutex<ReceiptRecord>>>,
records_by_nonce: BTreeMap<BareNonce, Arc<Mutex<ReceiptRecord>>>,
next_oldest_ts: Option<Timestamp>,
stop_source: Option<StopSource>,
timeout_task: MustJoinSingleFuture<()>,
@ -405,7 +405,7 @@ impl ReceiptManager {
}
#[expect(dead_code)]
pub async fn cancel_receipt(&self, nonce: &Nonce) -> EyreResult<()> {
pub async fn cancel_receipt(&self, nonce: &BareNonce) -> EyreResult<()> {
event!(target: "receipt", Level::DEBUG, "== Cancel Receipt {}", nonce.encode());
let _guard = self.unlocked_inner.startup_lock.enter()?;

View file

@ -4,7 +4,7 @@ use crate::tests::mock_registry;
fn make_mock_bootstrap_record(include_timestamp: bool) -> BootstrapRecord {
let mut node_ids = CryptoTypedGroup::new();
node_ids.add(
TypedNodeId::from_str("VLD0:f8G4Ckr1UR8YXnmAllwfvBEvXGgfYicZllb7jEpJeSU")
NodeId::from_str("VLD0:f8G4Ckr1UR8YXnmAllwfvBEvXGgfYicZllb7jEpJeSU")
.expect("should parse key"),
);
let envelope_support = VALID_ENVELOPE_VERSIONS.to_vec();
@ -66,18 +66,18 @@ pub async fn test_bootstrap_v1() {
let bsrec = make_mock_bootstrap_record(true);
let signing_key_pairs = [
#[cfg(feature = "enable-crypto-vld0")]
TypedKeyPair::from_str("VLD0:W7ENB-SUWpPA7usY8ORVQf_si5QmFbD1Uqa89Jg2Uc0:hbdjau5sr3rBNwN68XeWLg3rfXnXLaLqfbbqhELqV1E").expect("should parse keypair"),
KeyPair::from_str("VLD0:W7ENB-SUWpPA7usY8ORVQf_si5QmFbD1Uqa89Jg2Uc0:hbdjau5sr3rBNwN68XeWLg3rfXnXLaLqfbbqhELqV1E").expect("should parse keypair"),
#[cfg(feature = "enable-crypto-vld0")]
TypedKeyPair::from_str("VLD0:v6XPfyOoCP_ZP-CWFNrf_pF_dpxsq74p2LW_Q5Q4yPQ:n-DhHtOU7KWQkdp5to8cpBa_u0RFt2IDZzXPqMTq4O0").expect("should parse keypair"),
KeyPair::from_str("VLD0:v6XPfyOoCP_ZP-CWFNrf_pF_dpxsq74p2LW_Q5Q4yPQ:n-DhHtOU7KWQkdp5to8cpBa_u0RFt2IDZzXPqMTq4O0").expect("should parse keypair"),
#[cfg(feature = "enable-crypto-none")]
TypedKeyPair::from_str("NONE:xMzvYmY1C0B-pUrB9V1pnUf6A1hSqNTOju39UaFxQoU:OzMQnZnK9L-BWrU-CqKWYrgF_KetVysxcRICrl6OvXo").expect("should parse keypair"),
KeyPair::from_str("NONE:xMzvYmY1C0B-pUrB9V1pnUf6A1hSqNTOju39UaFxQoU:OzMQnZnK9L-BWrU-CqKWYrgF_KetVysxcRICrl6OvXo").expect("should parse keypair"),
#[cfg(feature = "enable-crypto-none")]
TypedKeyPair::from_str("NONE:xuYisL8R7-qoUQiJtHVpvemzd1x3mH246cMJSkMp6BQ:ORndT0DuEBVXrvd2S4qWQhZMiKOIZ4JHFjz2tbzWF-s").expect("should parse keypair"),
KeyPair::from_str("NONE:xuYisL8R7-qoUQiJtHVpvemzd1x3mH246cMJSkMp6BQ:ORndT0DuEBVXrvd2S4qWQhZMiKOIZ4JHFjz2tbzWF-s").expect("should parse keypair"),
];
println!("signing_key_pairs: {:?}", signing_key_pairs);
let signing_keys = signing_key_pairs
.iter()
.map(|skp| TypedPublicKey::new(skp.kind, skp.value.key))
.map(|skp| PublicKey::new(skp.kind, skp.value.key))
.collect::<Vec<_>>();
let v1str = bsrec
.to_v1_string(&network_manager, &dial_info_converter, signing_key_pairs[0])

View file

@ -31,12 +31,12 @@ pub async fn test_signed_node_info() {
let keypair = vcrypto.generate_keypair();
let sni = SignedDirectNodeInfo::make_signatures(
&crypto,
vec![TypedKeyPair::new(ck, keypair)],
vec![KeyPair::new(ck, keypair)],
node_info.clone(),
)
.unwrap();
let tks: TypedPublicKeyGroup = TypedPublicKey::new(ck, keypair.key).into();
let tks_node_ids = TypedNodeIdGroup::from(tks.clone());
let tks: PublicKeyGroup = PublicKey::new(ck, keypair.key).into();
let tks_node_ids = NodeIdGroup::from(tks.clone());
let oldtkslen = tks.len();
let sdni = SignedDirectNodeInfo::new(
node_info.clone(),
@ -49,7 +49,7 @@ pub async fn test_signed_node_info() {
// Test incorrect validation
let keypair1 = vcrypto.generate_keypair();
let tks1: TypedPublicKeyGroup = TypedPublicKey::new(ck, keypair1.key).into();
let tks1: PublicKeyGroup = PublicKey::new(ck, keypair1.key).into();
let sdni = SignedDirectNodeInfo::new(
node_info.clone(),
sni.timestamp(),
@ -59,11 +59,11 @@ pub async fn test_signed_node_info() {
// Test unsupported cryptosystem validation
let fake_crypto_kind: CryptoKind = CryptoKind::from([0, 1, 2, 3]);
let mut tksfake: TypedPublicKeyGroup =
TypedPublicKey::new(fake_crypto_kind, PublicKey::default()).into();
let mut tksfake: PublicKeyGroup =
PublicKey::new(fake_crypto_kind, BarePublicKey::default()).into();
let mut sigsfake = sni.signatures().to_vec();
sigsfake.push(TypedSignature::new(fake_crypto_kind, Signature::default()));
tksfake.add(TypedPublicKey::new(ck, keypair.key));
sigsfake.push(Signature::new(fake_crypto_kind, BareSignature::default()));
tksfake.add(PublicKey::new(ck, keypair.key));
let sdnifake =
SignedDirectNodeInfo::new(node_info.clone(), sni.timestamp(), sigsfake.clone());
let tksfake_validated = sdnifake.validate(&tksfake.into(), &crypto).unwrap();
@ -86,12 +86,12 @@ pub async fn test_signed_node_info() {
// Test correct validation
let keypair2 = vcrypto.generate_keypair();
let tks2: TypedPublicKeyGroup = TypedPublicKey::new(ck, keypair2.key).into();
let tks2: PublicKeyGroup = PublicKey::new(ck, keypair2.key).into();
let oldtks2len = tks2.len();
let sni2 = SignedRelayedNodeInfo::make_signatures(
&crypto,
vec![TypedKeyPair::new(ck, keypair2)],
vec![KeyPair::new(ck, keypair2)],
node_info2.clone(),
tks_node_ids.clone(),
sni.clone(),
@ -111,7 +111,7 @@ pub async fn test_signed_node_info() {
// Test incorrect validation
let keypair3 = vcrypto.generate_keypair();
let tks3: TypedPublicKeyGroup = TypedPublicKey::new(ck, keypair3.key).into();
let tks3: PublicKeyGroup = PublicKey::new(ck, keypair3.key).into();
let srni = SignedRelayedNodeInfo::new(
node_info2.clone(),
@ -124,11 +124,11 @@ pub async fn test_signed_node_info() {
// Test unsupported cryptosystem validation
let fake_crypto_kind: CryptoKind = CryptoKind::from([0, 1, 2, 3]);
let mut tksfake3: TypedPublicKeyGroup =
TypedPublicKey::new(fake_crypto_kind, PublicKey::default()).into();
let mut tksfake3: PublicKeyGroup =
PublicKey::new(fake_crypto_kind, BarePublicKey::default()).into();
let mut sigsfake3 = sni2.signatures().to_vec();
sigsfake3.push(TypedSignature::new(fake_crypto_kind, Signature::default()));
tksfake3.add(TypedPublicKey::new(ck, keypair2.key));
sigsfake3.push(Signature::new(fake_crypto_kind, BareSignature::default()));
tksfake3.add(PublicKey::new(ck, keypair2.key));
let srnifake = SignedRelayedNodeInfo::new(
node_info2.clone(),
tks.clone().into(),

View file

@ -12,15 +12,16 @@ pub struct Bucket {
/// Component registryo accessor
registry: VeilidComponentRegistry,
/// Map of keys to entries for this bucket
entries: BTreeMap<NodeId, Arc<BucketEntry>>,
entries: BTreeMap<BareNodeId, Arc<BucketEntry>>,
/// The crypto kind in use for the public keys in this bucket
kind: CryptoKind,
}
pub(super) type EntriesIter<'a> = alloc::collections::btree_map::Iter<'a, NodeId, Arc<BucketEntry>>;
pub(super) type EntriesIter<'a> =
alloc::collections::btree_map::Iter<'a, BareNodeId, Arc<BucketEntry>>;
#[derive(Debug, Serialize, Deserialize)]
struct SerializedBucketEntryData {
key: NodeId,
key: BareNodeId,
value: u32, // index into serialized entries list
}
@ -78,11 +79,11 @@ impl Bucket {
}
/// Create a new entry with a node_id of this crypto kind and return it
pub(super) fn add_new_entry(&mut self, node_id_key: NodeId) -> Arc<BucketEntry> {
pub(super) fn add_new_entry(&mut self, node_id_key: BareNodeId) -> Arc<BucketEntry> {
veilid_log!(self trace "Node added: {}:{}", self.kind, node_id_key);
// Add new entry
let entry = Arc::new(BucketEntry::new(TypedNodeId::new(self.kind, node_id_key)));
let entry = Arc::new(BucketEntry::new(NodeId::new(self.kind, node_id_key)));
self.entries.insert(node_id_key, entry.clone());
// Return the new entry
@ -90,7 +91,7 @@ impl Bucket {
}
/// Add an existing entry with a new node_id for this crypto kind
pub(super) fn add_existing_entry(&mut self, node_id_key: NodeId, entry: Arc<BucketEntry>) {
pub(super) fn add_existing_entry(&mut self, node_id_key: BareNodeId, entry: Arc<BucketEntry>) {
veilid_log!(self trace "Existing node added: {}:{}", self.kind, node_id_key);
// Add existing entry
@ -98,14 +99,14 @@ impl Bucket {
}
/// Remove an entry with a node_id for this crypto kind from the bucket
pub(super) fn remove_entry(&mut self, node_id_key: &NodeId) {
pub(super) fn remove_entry(&mut self, node_id_key: &BareNodeId) {
veilid_log!(self trace "Node removed: {}:{}", self.kind, node_id_key);
// Remove the entry
self.entries.remove(node_id_key);
}
pub(super) fn entry(&self, key: &NodeId) -> Option<Arc<BucketEntry>> {
pub(super) fn entry(&self, key: &BareNodeId) -> Option<Arc<BucketEntry>> {
self.entries.get(key).cloned()
}
@ -116,8 +117,8 @@ impl Bucket {
pub(super) fn kick(
&mut self,
bucket_depth: usize,
exempt_peers: &BTreeSet<NodeId>,
) -> Option<BTreeSet<NodeId>> {
exempt_peers: &BTreeSet<BareNodeId>,
) -> Option<BTreeSet<BareNodeId>> {
// Get number of entries to attempt to purge from bucket
let bucket_len = self.entries.len();
@ -127,11 +128,11 @@ impl Bucket {
}
// Try to purge the newest entries that overflow the bucket
let mut dead_node_ids: BTreeSet<NodeId> = BTreeSet::new();
let mut dead_node_ids: BTreeSet<BareNodeId> = BTreeSet::new();
let mut extra_entries = bucket_len - bucket_depth;
// Get the sorted list of entries by their kick order
let mut sorted_entries: Vec<(NodeId, Arc<BucketEntry>)> =
let mut sorted_entries: Vec<(BareNodeId, Arc<BucketEntry>)> =
self.entries.iter().map(|(k, v)| (*k, v.clone())).collect();
let cur_ts = Timestamp::now();
sorted_entries.sort_by(|a, b| -> core::cmp::Ordering {

View file

@ -163,9 +163,9 @@ impl fmt::Display for BucketEntryLocalNetwork {
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct BucketEntryInner {
/// The node ids matching this bucket entry, with the cryptography versions supported by this node as the 'kind' field
validated_node_ids: TypedNodeIdGroup,
validated_node_ids: NodeIdGroup,
/// The node ids claimed by the remote node that use cryptography versions we do not support
unsupported_node_ids: TypedNodeIdGroup,
unsupported_node_ids: NodeIdGroup,
/// The set of envelope versions supported by the node inclusive of the requirements of any relay the node may be using
envelope_support: Vec<u8>,
/// If this node has updated it's SignedNodeInfo since our network
@ -283,7 +283,7 @@ impl BucketEntryInner {
}
/// Get all node ids
pub fn node_ids(&self) -> TypedNodeIdGroup {
pub fn node_ids(&self) -> NodeIdGroup {
let mut node_ids = self.validated_node_ids.clone();
node_ids.add_all(&self.unsupported_node_ids);
node_ids
@ -293,7 +293,7 @@ impl BucketEntryInner {
/// Returns Ok(Some(node)) any previous existing node id associated with that crypto kind
/// Returns Ok(None) if no previous existing node id was associated with that crypto kind, or one existed but nothing changed.
/// Results Err() if this operation would add more crypto kinds than we support
pub fn add_node_id(&mut self, node_id: TypedNodeId) -> EyreResult<Option<TypedNodeId>> {
pub fn add_node_id(&mut self, node_id: NodeId) -> EyreResult<Option<NodeId>> {
let total_node_id_count = self.validated_node_ids.len() + self.unsupported_node_ids.len();
let node_ids = if VALID_CRYPTO_KINDS.contains(&node_id.kind) {
&mut self.validated_node_ids
@ -331,7 +331,7 @@ impl BucketEntryInner {
/// Remove a node id for a particular crypto kind.
/// Returns Some(node) any previous existing node id associated with that crypto kind
/// Returns None if no previous existing node id was associated with that crypto kind
pub fn remove_node_id(&mut self, crypto_kind: CryptoKind) -> Option<TypedNodeId> {
pub fn remove_node_id(&mut self, crypto_kind: CryptoKind) -> Option<NodeId> {
let node_ids = if VALID_CRYPTO_KINDS.contains(&crypto_kind) {
&mut self.validated_node_ids
} else {
@ -348,7 +348,7 @@ impl BucketEntryInner {
opt_dead_id
}
pub fn best_node_id(&self) -> Option<TypedNodeId> {
pub fn best_node_id(&self) -> Option<NodeId> {
self.validated_node_ids.best()
}
@ -1221,14 +1221,14 @@ pub(crate) struct BucketEntry {
}
impl BucketEntry {
pub(super) fn new(first_node_id: TypedNodeId) -> Self {
pub(super) fn new(first_node_id: NodeId) -> Self {
// First node id should always be one we support since TypedKeySets are sorted and we must have at least one supported key
assert!(VALID_CRYPTO_KINDS.contains(&first_node_id.kind));
let now = Timestamp::now();
let inner = BucketEntryInner {
validated_node_ids: TypedNodeIdGroup::from(first_node_id),
unsupported_node_ids: TypedNodeIdGroup::new(),
validated_node_ids: NodeIdGroup::from(first_node_id),
unsupported_node_ids: NodeIdGroup::new(),
envelope_support: Vec::new(),
updated_since_last_network_change: false,
last_flows: BTreeMap::new(),

View file

@ -203,7 +203,7 @@ impl RoutingTable {
let mut b = 0;
let blen = inner.buckets[ck].len();
while b < blen {
let filtered_entries: Vec<(&NodeId, &Arc<BucketEntry>)> = inner.buckets[ck][b]
let filtered_entries: Vec<(&BareNodeId, &Arc<BucketEntry>)> = inner.buckets[ck][b]
.entries()
.filter(|e| {
let cap_match = e.1.with(inner, |_rti, e| {
@ -245,7 +245,7 @@ impl RoutingTable {
out += " ";
out += &e.1.with(inner, |_rti, e| {
let node_id_str = TypedNodeId::new(*ck, node).to_string();
let node_id_str = NodeId::new(*ck, node).to_string();
Self::format_entry(cur_ts, &node_id_str, e, &relay_tag)
});
out += "\n";

View file

@ -8,7 +8,7 @@ impl RoutingTable {
pub fn find_preferred_closest_peers(
&self,
routing_domain: RoutingDomain,
key: TypedNodeId,
key: NodeId,
capabilities: &[VeilidCapability],
) -> NetworkResult<Vec<Arc<PeerInfo>>> {
if Crypto::validate_crypto_kind(key.kind).is_err() {
@ -72,7 +72,7 @@ impl RoutingTable {
pub fn find_preferred_peers_closer_to_key(
&self,
routing_domain: RoutingDomain,
key: TypedRecordKey,
key: RecordKey,
required_capabilities: Vec<VeilidCapability>,
) -> NetworkResult<Vec<Arc<PeerInfo>>> {
// add node information for the requesting node to our routing table
@ -88,8 +88,8 @@ impl RoutingTable {
let vcrypto = &vcrypto;
let own_distance = vcrypto.distance(
&HashDigest::from(own_node_id.value),
&HashDigest::from(key.value),
&BareHashDigest::from(own_node_id.value),
&BareHashDigest::from(key.value),
);
let filter = Box::new(
@ -116,8 +116,8 @@ impl RoutingTable {
return false;
};
let entry_distance = vcrypto.distance(
&HashDigest::from(entry_node_id.value),
&HashDigest::from(key.value),
&BareHashDigest::from(entry_node_id.value),
&BareHashDigest::from(key.value),
);
if entry_distance >= own_distance {
return false;
@ -178,8 +178,8 @@ impl RoutingTable {
#[instrument(level = "trace", target = "rtab", skip_all, err)]
pub fn verify_peers_closer(
vcrypto: &crypto::CryptoSystemGuard<'_>,
key_far: TypedHashDigest,
key_near: TypedHashDigest,
key_far: HashDigest,
key_near: HashDigest,
peers: &[Arc<PeerInfo>],
) -> EyreResult<bool> {
let kind = vcrypto.kind();

View file

@ -304,34 +304,34 @@ impl RoutingTable {
///////////////////////////////////////////////////////////////////
pub fn node_id(&self, kind: CryptoKind) -> TypedNodeId {
pub fn node_id(&self, kind: CryptoKind) -> NodeId {
self.config()
.with(|c| c.network.routing_table.node_id.get(kind).unwrap())
}
pub fn node_id_secret_key(&self, kind: CryptoKind) -> SecretKey {
pub fn node_id_secret_key(&self, kind: CryptoKind) -> BareSecretKey {
self.config()
.with(|c| c.network.routing_table.node_id_secret.get(kind).unwrap())
.value
}
pub fn node_ids(&self) -> TypedNodeIdGroup {
pub fn node_ids(&self) -> NodeIdGroup {
self.config()
.with(|c| c.network.routing_table.node_id.clone())
}
pub fn node_id_typed_key_pairs(&self) -> Vec<TypedKeyPair> {
pub fn node_id_typed_key_pairs(&self) -> Vec<KeyPair> {
let mut tkps = Vec::new();
for ck in VALID_CRYPTO_KINDS {
tkps.push(TypedKeyPair::new(
tkps.push(KeyPair::new(
ck,
KeyPair::new(self.node_id(ck).value.into(), self.node_id_secret_key(ck)),
BareKeyPair::new(self.node_id(ck).value.into(), self.node_id_secret_key(ck)),
));
}
tkps
}
pub fn matches_own_node_id(&self, node_ids: &[TypedNodeId]) -> bool {
pub fn matches_own_node_id(&self, node_ids: &[NodeId]) -> bool {
for ni in node_ids {
if let Some(v) = self.node_ids().get(ni.kind) {
if v.value == ni.value {
@ -342,7 +342,7 @@ impl RoutingTable {
false
}
pub fn matches_own_node_id_key(&self, node_id_key: &NodeId) -> bool {
pub fn matches_own_node_id_key(&self, node_id_key: &BareNodeId) -> bool {
for tk in self.node_ids().iter() {
if tk.value == *node_id_key {
return true;
@ -351,7 +351,7 @@ impl RoutingTable {
false
}
pub fn calculate_bucket_index(&self, node_id: &TypedNodeId) -> BucketIndex {
pub fn calculate_bucket_index(&self, node_id: &NodeId) -> BucketIndex {
let crypto = self.crypto();
let self_node_id_key = self.node_id(node_id.kind).value;
let vcrypto = crypto.get(node_id.kind).unwrap();
@ -359,8 +359,8 @@ impl RoutingTable {
node_id.kind,
vcrypto
.distance(
&HashDigest::from(node_id.value),
&HashDigest::from(self_node_id_key),
&BareHashDigest::from(node_id.value),
&BareHashDigest::from(self_node_id_key),
)
.first_nonzero_bit()
.unwrap(),
@ -662,7 +662,7 @@ impl RoutingTable {
.get_nodes_needing_ping(routing_domain, cur_ts)
}
fn queue_bucket_kicks(&self, node_ids: TypedNodeIdGroup) {
fn queue_bucket_kicks(&self, node_ids: NodeIdGroup) {
for node_id in node_ids.iter() {
// Skip node ids we didn't add to buckets
if !VALID_CRYPTO_KINDS.contains(&node_id.kind) {
@ -676,12 +676,12 @@ impl RoutingTable {
}
/// Resolve an existing routing table entry using any crypto kind and return a reference to it
pub fn lookup_any_node_ref(&self, node_id_key: NodeId) -> EyreResult<Option<NodeRef>> {
pub fn lookup_any_node_ref(&self, node_id_key: BareNodeId) -> EyreResult<Option<NodeRef>> {
self.inner.read().lookup_any_node_ref(node_id_key)
}
/// Resolve an existing routing table entry and return a reference to it
pub fn lookup_node_ref(&self, node_id: TypedNodeId) -> EyreResult<Option<NodeRef>> {
pub fn lookup_node_ref(&self, node_id: NodeId) -> EyreResult<Option<NodeRef>> {
self.inner.read().lookup_node_ref(node_id)
}
@ -689,7 +689,7 @@ impl RoutingTable {
#[instrument(level = "trace", skip_all)]
pub fn lookup_and_filter_noderef(
&self,
node_id: TypedNodeId,
node_id: NodeId,
routing_domain_set: RoutingDomainSet,
dial_info_filter: DialInfoFilter,
) -> EyreResult<Option<FilteredNodeRef>> {
@ -719,7 +719,7 @@ impl RoutingTable {
pub fn register_node_with_id(
&self,
routing_domain: RoutingDomain,
node_id: TypedNodeId,
node_id: NodeId,
timestamp: Timestamp,
) -> EyreResult<FilteredNodeRef> {
self.inner
@ -739,7 +739,7 @@ impl RoutingTable {
}
#[instrument(level = "trace", skip_all)]
pub fn get_recent_peers(&self) -> Vec<(TypedNodeId, RecentPeersEntry)> {
pub fn get_recent_peers(&self) -> Vec<(NodeId, RecentPeersEntry)> {
let mut recent_peers = Vec::new();
let mut dead_peers = Vec::new();
let mut out = Vec::new();
@ -911,7 +911,7 @@ impl RoutingTable {
pub fn find_preferred_closest_nodes<'a, T, O>(
&self,
node_count: usize,
node_id: TypedHashDigest,
node_id: HashDigest,
filters: VecDeque<RoutingTableEntryFilter>,
transform: T,
) -> VeilidAPIResult<Vec<O>>
@ -925,7 +925,7 @@ impl RoutingTable {
pub fn sort_and_clean_closest_noderefs(
&self,
node_id: TypedHashDigest,
node_id: HashDigest,
closest_nodes: &[NodeRef],
) -> Vec<NodeRef> {
self.inner
@ -963,7 +963,7 @@ impl RoutingTable {
pub async fn find_nodes_close_to_node_id(
&self,
node_ref: FilteredNodeRef,
node_id: TypedNodeId,
node_id: NodeId,
capabilities: Vec<VeilidCapability>,
) -> EyreResult<NetworkResult<Vec<NodeRef>>> {
let rpc_processor = self.rpc_processor();
@ -1080,7 +1080,7 @@ impl RoutingTable {
#[instrument(level = "trace", skip(self, filter, metric), ret)]
pub fn get_node_speed_percentile(
&self,
node_id: TypedNodeId,
node_id: NodeId,
cur_ts: Timestamp,
filter: impl Fn(&BucketEntryInner) -> bool,
metric: impl Fn(&LatencyStats) -> TimestampDuration,

View file

@ -39,10 +39,10 @@ pub(crate) trait NodeRefCommonTrait: NodeRefAccessorsTrait + NodeRefOperateTrait
Arc::ptr_eq(&self.entry(), entry)
}
fn node_ids(&self) -> TypedNodeIdGroup {
fn node_ids(&self) -> NodeIdGroup {
self.operate(|_rti, e| e.node_ids())
}
fn best_node_id(&self) -> Option<TypedNodeId> {
fn best_node_id(&self) -> Option<NodeId> {
self.operate(|_rti, e| e.best_node_id())
}

View file

@ -8,7 +8,7 @@ impl_veilid_log_facility!("rtab");
#[derive(Clone)]
pub(crate) struct RouteHopData {
/// The nonce used in the encryption ENC(Xn,DH(PKn,SKapr))
pub nonce: Nonce,
pub nonce: BareNonce,
/// The encrypted blob
pub blob: Vec<u8>,
}
@ -26,7 +26,7 @@ impl fmt::Debug for RouteHopData {
#[derive(Clone, Debug)]
pub(crate) enum RouteNode {
/// Route node is optimized, no contact method information as this node id has been seen before
NodeId(NodeId),
BareNodeId(BareNodeId),
/// Route node with full contact method information to ensure the peer is reachable
PeerInfo(Arc<PeerInfo>),
}
@ -34,7 +34,7 @@ pub(crate) enum RouteNode {
impl RouteNode {
pub fn validate(&self, crypto: &Crypto) -> VeilidAPIResult<()> {
match self {
RouteNode::NodeId(_) => Ok(()),
RouteNode::BareNodeId(_) => Ok(()),
RouteNode::PeerInfo(pi) => pi.validate(crypto),
}
}
@ -45,9 +45,9 @@ impl RouteNode {
crypto_kind: CryptoKind,
) -> Option<NodeRef> {
match self {
RouteNode::NodeId(id) => {
RouteNode::BareNodeId(id) => {
//
match routing_table.lookup_node_ref(TypedNodeId::new(crypto_kind, *id)) {
match routing_table.lookup_node_ref(NodeId::new(crypto_kind, *id)) {
Ok(nr) => nr,
Err(e) => {
veilid_log!(routing_table debug "failed to look up route node: {}", e);
@ -70,8 +70,8 @@ impl RouteNode {
pub fn describe(&self, crypto_kind: CryptoKind) -> String {
match self {
RouteNode::NodeId(id) => {
format!("{}", TypedNodeId::new(crypto_kind, *id))
RouteNode::BareNodeId(id) => {
format!("{}", NodeId::new(crypto_kind, *id))
}
RouteNode::PeerInfo(pi) => match pi.node_ids().get(crypto_kind) {
Some(id) => format!("{}", id),
@ -121,14 +121,14 @@ impl PrivateRouteHops {
#[derive(Clone, Debug)]
pub(crate) struct PrivateRoute {
/// The public key used for the entire route
pub public_key: TypedPublicKey,
pub public_key: PublicKey,
pub hop_count: u8,
pub hops: PrivateRouteHops,
}
impl PrivateRoute {
/// Stub route is the form used when no privacy is required, but you need to specify the destination for a safety route
pub fn new_stub(public_key: TypedPublicKey, node: RouteNode) -> Self {
pub fn new_stub(public_key: PublicKey, node: RouteNode) -> Self {
Self {
public_key,
hop_count: 1,
@ -182,14 +182,14 @@ impl PrivateRoute {
}
}
pub fn first_hop_node_id(&self) -> Option<TypedNodeId> {
pub fn first_hop_node_id(&self) -> Option<NodeId> {
let PrivateRouteHops::FirstHop(pr_first_hop) = &self.hops else {
return None;
};
// Get the safety route to use from the spec
Some(match &pr_first_hop.node {
RouteNode::NodeId(n) => TypedNodeId::new(self.public_key.kind, *n),
RouteNode::BareNodeId(n) => NodeId::new(self.public_key.kind, *n),
RouteNode::PeerInfo(p) => p.node_ids().get(self.public_key.kind).unwrap(),
})
}
@ -232,14 +232,14 @@ pub(crate) enum SafetyRouteHops {
#[derive(Clone, Debug)]
pub(crate) struct SafetyRoute {
pub public_key: TypedPublicKey,
pub public_key: PublicKey,
pub hop_count: u8,
pub hops: SafetyRouteHops,
}
impl SafetyRoute {
/// Stub route is the form used when no privacy is required, but you need to directly contact a private route
pub fn new_stub(public_key: TypedPublicKey, private_route: PrivateRoute) -> Self {
pub fn new_stub(public_key: PublicKey, private_route: PrivateRoute) -> Self {
// First hop should have already been popped off for stubbed safety routes since
// we are sending directly to the first hop
assert!(matches!(private_route.hops, PrivateRouteHops::Data(_)));

View file

@ -166,9 +166,9 @@ impl RouteSpecStore {
crypto_kinds: &[CryptoKind],
safety_spec: &SafetySpec,
directions: DirectionSet,
avoid_nodes: &[TypedNodeId],
avoid_nodes: &[NodeId],
automatic: bool,
) -> VeilidAPIResult<RouteId> {
) -> VeilidAPIResult<BareRouteId> {
let inner = &mut *self.inner.lock();
let routing_table = self.routing_table();
let rti = &mut *routing_table.inner.write();
@ -193,9 +193,9 @@ impl RouteSpecStore {
crypto_kinds: &[CryptoKind],
safety_spec: &SafetySpec,
directions: DirectionSet,
avoid_nodes: &[TypedNodeId],
avoid_nodes: &[NodeId],
automatic: bool,
) -> VeilidAPIResult<RouteId> {
) -> VeilidAPIResult<BareRouteId> {
use core::cmp::Ordering;
if safety_spec.preferred_route.is_some() {
@ -636,12 +636,12 @@ impl RouteSpecStore {
// Got a unique route, lets build the details, register it, and return it
let hop_node_refs: Vec<NodeRef> = route_nodes.iter().map(|k| nodes[*k].clone()).collect();
let mut route_set = BTreeMap::<PublicKey, RouteSpecDetail>::new();
let mut route_set = BTreeMap::<BarePublicKey, RouteSpecDetail>::new();
let crypto = self.crypto();
for crypto_kind in crypto_kinds.iter().copied() {
let vcrypto = crypto.get(crypto_kind).unwrap();
let keypair = vcrypto.generate_keypair();
let hops: Vec<NodeId> = route_nodes
let hops: Vec<BareNodeId> = route_nodes
.iter()
.map(|v| {
nodes[*v]
@ -689,10 +689,10 @@ impl RouteSpecStore {
#[instrument(level = "trace", target = "route", skip(self, data, callback), ret)]
pub fn with_signature_validated_route<F, R>(
&self,
public_key: &TypedPublicKey,
signatures: &[Signature],
public_key: &PublicKey,
signatures: &[BareSignature],
data: &[u8],
last_hop_id: NodeId,
last_hop_id: BareNodeId,
callback: F,
) -> Option<R>
where
@ -757,7 +757,7 @@ impl RouteSpecStore {
#[instrument(level = "trace", target = "route", skip(self), ret, err)]
async fn test_allocated_route(
&self,
private_route_id: RouteId,
private_route_id: BareRouteId,
) -> VeilidAPIResult<Option<bool>> {
// Make loopback route to test with
let (dest, hops) = {
@ -836,7 +836,10 @@ impl RouteSpecStore {
}
#[instrument(level = "trace", target = "route", skip(self), ret, err)]
async fn test_remote_route(&self, private_route_id: RouteId) -> VeilidAPIResult<Option<bool>> {
async fn test_remote_route(
&self,
private_route_id: BareRouteId,
) -> VeilidAPIResult<Option<bool>> {
// Make private route test
let dest = {
// Get the route to test
@ -879,7 +882,7 @@ impl RouteSpecStore {
/// Release an allocated route that is no longer in use
#[instrument(level = "trace", target = "route", skip(self), ret)]
fn release_allocated_route(&self, id: RouteId) -> bool {
fn release_allocated_route(&self, id: BareRouteId) -> bool {
let mut inner = self.inner.lock();
let Some(rssd) = inner.content.remove_detail(&id) else {
return false;
@ -896,7 +899,7 @@ impl RouteSpecStore {
}
/// Check if a route id is remote or not
pub fn is_route_id_remote(&self, id: &RouteId) -> bool {
pub fn is_route_id_remote(&self, id: &BareRouteId) -> bool {
let inner = &mut *self.inner.lock();
let cur_ts = Timestamp::now();
inner
@ -907,7 +910,7 @@ impl RouteSpecStore {
/// Test an allocated route for continuity
#[instrument(level = "trace", target = "route", skip(self), ret, err)]
pub async fn test_route(&self, id: RouteId) -> VeilidAPIResult<Option<bool>> {
pub async fn test_route(&self, id: BareRouteId) -> VeilidAPIResult<Option<bool>> {
let is_remote = self.is_route_id_remote(&id);
if is_remote {
self.test_remote_route(id).await
@ -918,7 +921,7 @@ impl RouteSpecStore {
/// Release an allocated or remote route that is no longer in use
#[instrument(level = "trace", target = "route", skip(self), ret)]
pub fn release_route(&self, id: RouteId) -> bool {
pub fn release_route(&self, id: BareRouteId) -> bool {
let is_remote = self.is_route_id_remote(&id);
if is_remote {
self.release_remote_private_route(id)
@ -939,8 +942,8 @@ impl RouteSpecStore {
stability: Stability,
sequencing: Sequencing,
directions: DirectionSet,
avoid_nodes: &[TypedNodeId],
) -> Option<RouteId> {
avoid_nodes: &[NodeId],
) -> Option<BareRouteId> {
let cur_ts = Timestamp::now();
let mut routes = Vec::new();
@ -996,7 +999,7 @@ impl RouteSpecStore {
/// List all allocated routes
pub fn list_allocated_routes<F, R>(&self, mut filter: F) -> Vec<R>
where
F: FnMut(&RouteId, &RouteSetSpecDetail) -> Option<R>,
F: FnMut(&BareRouteId, &RouteSetSpecDetail) -> Option<R>,
{
let inner = self.inner.lock();
let mut out = Vec::with_capacity(inner.content.get_detail_count());
@ -1011,7 +1014,7 @@ impl RouteSpecStore {
/// List all allocated routes
pub fn list_remote_routes<F, R>(&self, mut filter: F) -> Vec<R>
where
F: FnMut(&RouteId, &RemotePrivateRouteInfo) -> Option<R>,
F: FnMut(&BareRouteId, &RemotePrivateRouteInfo) -> Option<R>,
{
let inner = self.inner.lock();
let cur_ts = Timestamp::now();
@ -1028,7 +1031,7 @@ impl RouteSpecStore {
}
/// Get the debug description of a route
pub fn debug_route(&self, id: &RouteId) -> Option<String> {
pub fn debug_route(&self, id: &BareRouteId) -> Option<String> {
let inner = &mut *self.inner.lock();
let cur_ts = Timestamp::now();
if let Some(rpri) = inner.cache.peek_remote_private_route(cur_ts, id) {
@ -1043,7 +1046,7 @@ impl RouteSpecStore {
//////////////////////////////////////////////////////////////////////
/// Choose the best private route from a private route set to communicate with
pub fn best_remote_private_route(&self, id: &RouteId) -> Option<PrivateRoute> {
pub fn best_remote_private_route(&self, id: &BareRouteId) -> Option<PrivateRoute> {
let inner = &mut *self.inner.lock();
let cur_ts = Timestamp::now();
let rpri = inner.cache.get_remote_private_route(cur_ts, id)?;
@ -1095,8 +1098,8 @@ impl RouteSpecStore {
};
let opt_first_hop = match pr_first_hop_node {
RouteNode::NodeId(id) => rti
.lookup_node_ref(TypedNodeId::new(crypto_kind, id))
RouteNode::BareNodeId(id) => rti
.lookup_node_ref(NodeId::new(crypto_kind, id))
.map_err(VeilidAPIError::internal)?,
RouteNode::PeerInfo(pi) => Some(
rti.register_node_with_peer_info(pi, false)
@ -1240,11 +1243,10 @@ impl RouteSpecStore {
let route_hop = RouteHop {
node: if optimize {
// Optimized, no peer info, just the dht key
RouteNode::NodeId(safety_rsd.hops[h])
RouteNode::BareNodeId(safety_rsd.hops[h])
} else {
// Full peer info, required until we are sure the route has been fully established
let node_id =
TypedNodeId::new(safety_rsd.crypto_kind, safety_rsd.hops[h]);
let node_id = NodeId::new(safety_rsd.crypto_kind, safety_rsd.hops[h]);
let pi = rti
.with_node_entry(node_id, |entry| {
entry.with(rti, |_rti, e| {
@ -1293,7 +1295,7 @@ impl RouteSpecStore {
// Build safety route
let safety_route = SafetyRoute {
public_key: TypedPublicKey::new(crypto_kind, sr_pubkey),
public_key: PublicKey::new(crypto_kind, sr_pubkey),
hop_count: safety_spec.hop_count as u8,
hops,
};
@ -1326,8 +1328,8 @@ impl RouteSpecStore {
crypto_kind: CryptoKind,
safety_spec: &SafetySpec,
direction: DirectionSet,
avoid_nodes: &[TypedNodeId],
) -> VeilidAPIResult<PublicKey> {
avoid_nodes: &[NodeId],
) -> VeilidAPIResult<BarePublicKey> {
// Ensure the total hop count isn't too long for our config
let max_route_hop_count = self.max_route_hop_count;
if safety_spec.hop_count == 0 {
@ -1402,8 +1404,8 @@ impl RouteSpecStore {
&self,
crypto_kind: CryptoKind,
safety_spec: &SafetySpec,
avoid_nodes: &[TypedNodeId],
) -> VeilidAPIResult<PublicKey> {
avoid_nodes: &[NodeId],
) -> VeilidAPIResult<BarePublicKey> {
let inner = &mut *self.inner.lock();
let routing_table = self.routing_table();
let rti = &mut *routing_table.inner.write();
@ -1420,7 +1422,7 @@ impl RouteSpecStore {
fn assemble_private_route_inner(
&self,
key: &PublicKey,
key: &BarePublicKey,
rsd: &RouteSpecDetail,
optimized: bool,
) -> VeilidAPIResult<PrivateRoute> {
@ -1453,7 +1455,7 @@ impl RouteSpecStore {
rsd.crypto_kind
);
};
RouteNode::NodeId(node_id.value)
RouteNode::BareNodeId(node_id.value)
} else {
RouteNode::PeerInfo(published_peer_info)
},
@ -1485,10 +1487,10 @@ impl RouteSpecStore {
route_hop = RouteHop {
node: if optimized {
// Optimized, no peer info, just the dht key
RouteNode::NodeId(rsd.hops[h])
RouteNode::BareNodeId(rsd.hops[h])
} else {
// Full peer info, required until we are sure the route has been fully established
let node_id = TypedNodeId::new(rsd.crypto_kind, rsd.hops[h]);
let node_id = NodeId::new(rsd.crypto_kind, rsd.hops[h]);
let pi = rti
.with_node_entry(node_id, |entry| {
entry.with(rti, |_rti, e| {
@ -1506,7 +1508,7 @@ impl RouteSpecStore {
}
let private_route = PrivateRoute {
public_key: TypedPublicKey::new(rsd.crypto_kind, *key),
public_key: PublicKey::new(rsd.crypto_kind, *key),
// add hop for 'FirstHop'
hop_count: (hop_count + 1).try_into().unwrap(),
hops: PrivateRouteHops::FirstHop(Box::new(route_hop)),
@ -1519,7 +1521,7 @@ impl RouteSpecStore {
#[instrument(level = "trace", target = "route", skip_all)]
pub fn assemble_private_route(
&self,
key: &PublicKey,
key: &BarePublicKey,
optimized: Option<bool>,
) -> VeilidAPIResult<PrivateRoute> {
let inner: &RouteSpecStoreInner = &self.inner.lock();
@ -1547,7 +1549,7 @@ impl RouteSpecStore {
#[instrument(level = "trace", target = "route", skip_all)]
pub fn assemble_private_routes(
&self,
id: &RouteId,
id: &BareRouteId,
optimized: Option<bool>,
) -> VeilidAPIResult<Vec<PrivateRoute>> {
let inner = &*self.inner.lock();
@ -1570,7 +1572,7 @@ impl RouteSpecStore {
/// It is safe to import the same route more than once and it will return the same route id
/// Returns a route set id
#[instrument(level = "trace", target = "route", skip_all)]
pub fn import_remote_private_route_blob(&self, blob: Vec<u8>) -> VeilidAPIResult<RouteId> {
pub fn import_remote_private_route_blob(&self, blob: Vec<u8>) -> VeilidAPIResult<BareRouteId> {
let cur_ts = Timestamp::now();
// decode the pr blob
@ -1607,7 +1609,7 @@ impl RouteSpecStore {
pub fn add_remote_private_route(
&self,
private_route: PrivateRoute,
) -> VeilidAPIResult<RouteId> {
) -> VeilidAPIResult<BareRouteId> {
let cur_ts = Timestamp::now();
// Make a single route set
@ -1639,13 +1641,13 @@ impl RouteSpecStore {
/// Release a remote private route that is no longer in use
#[instrument(level = "trace", target = "route", skip_all)]
pub fn release_remote_private_route(&self, id: RouteId) -> bool {
pub fn release_remote_private_route(&self, id: BareRouteId) -> bool {
let inner = &mut *self.inner.lock();
inner.cache.remove_remote_private_route(id)
}
/// Get a route id for a route's public key
pub fn get_route_id_for_key(&self, key: &PublicKey) -> Option<RouteId> {
pub fn get_route_id_for_key(&self, key: &BarePublicKey) -> Option<BareRouteId> {
let inner = &mut *self.inner.lock();
// Check for local route
if let Some(id) = inner.content.get_id_by_key(key) {
@ -1664,7 +1666,7 @@ impl RouteSpecStore {
/// This happens when you communicate with a private route without a safety route
pub fn has_remote_private_route_seen_our_node_info(
&self,
key: &PublicKey,
key: &BarePublicKey,
published_peer_info: &PeerInfo,
) -> bool {
let inner = &*self.inner.lock();
@ -1695,7 +1697,7 @@ impl RouteSpecStore {
/// was that node that had the private route.
pub fn mark_remote_private_route_seen_our_node_info(
&self,
key: &PublicKey,
key: &BarePublicKey,
cur_ts: Timestamp,
) -> VeilidAPIResult<()> {
let Some(our_node_info_ts) = self
@ -1726,7 +1728,12 @@ impl RouteSpecStore {
}
/// Get the route statistics for any route we know about, local or remote
pub fn with_route_stats_mut<F, R>(&self, cur_ts: Timestamp, key: &PublicKey, f: F) -> Option<R>
pub fn with_route_stats_mut<F, R>(
&self,
cur_ts: Timestamp,
key: &BarePublicKey,
f: F,
) -> Option<R>
where
F: FnOnce(&mut RouteStats) -> R,
{
@ -1771,7 +1778,7 @@ impl RouteSpecStore {
/// Mark route as published
/// When first deserialized, routes must be re-published in order to ensure they remain
/// in the RouteSpecStore.
pub fn mark_route_published(&self, id: &RouteId, published: bool) -> VeilidAPIResult<()> {
pub fn mark_route_published(&self, id: &BareRouteId, published: bool) -> VeilidAPIResult<()> {
let inner = &mut *self.inner.lock();
let Some(rssd) = inner.content.get_detail_mut(id) else {
apibail_invalid_target!("route does not exist");
@ -1879,8 +1886,11 @@ impl RouteSpecStore {
Ok(out)
}
/// Generate RouteId from typed key set of route public keys
fn generate_allocated_route_id(&self, rssd: &RouteSetSpecDetail) -> VeilidAPIResult<RouteId> {
/// Generate BareRouteId from typed key set of route public keys
fn generate_allocated_route_id(
&self,
rssd: &RouteSetSpecDetail,
) -> VeilidAPIResult<BareRouteId> {
let route_set_keys = rssd.get_route_set_keys();
let crypto = self.crypto();
@ -1899,14 +1909,14 @@ impl RouteSpecStore {
};
let vcrypto = crypto.get(best_kind).unwrap();
Ok(RouteId::new(vcrypto.generate_hash(&idbytes).bytes))
Ok(BareRouteId::new(vcrypto.generate_hash(&idbytes).bytes))
}
/// Generate RouteId from set of private routes
/// Generate BareRouteId from set of private routes
fn generate_remote_route_id(
&self,
private_routes: &[PrivateRoute],
) -> VeilidAPIResult<RouteId> {
) -> VeilidAPIResult<BareRouteId> {
let crypto = self.crypto();
let mut idbytes = Vec::with_capacity(PUBLIC_KEY_LENGTH * private_routes.len());
@ -1925,6 +1935,6 @@ impl RouteSpecStore {
};
let vcrypto = crypto.get(best_kind).unwrap();
Ok(RouteId::new(vcrypto.generate_hash(&idbytes).bytes))
Ok(BareRouteId::new(vcrypto.generate_hash(&idbytes).bytes))
}
}

View file

@ -5,15 +5,15 @@ pub struct RouteSpecDetail {
/// Crypto kind
pub crypto_kind: CryptoKind,
/// Secret key
pub secret_key: SecretKey,
pub secret_key: BareSecretKey,
/// Route hops (node id keys)
pub hops: Vec<NodeId>,
pub hops: Vec<BareNodeId>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RouteSetSpecDetail {
/// Route set per crypto kind
route_set: BTreeMap<PublicKey, RouteSpecDetail>,
route_set: BTreeMap<BarePublicKey, RouteSpecDetail>,
/// Route noderefs
#[serde(skip)]
hop_node_refs: Vec<NodeRef>,
@ -36,7 +36,7 @@ pub struct RouteSetSpecDetail {
impl RouteSetSpecDetail {
pub fn new(
cur_ts: Timestamp,
route_set: BTreeMap<PublicKey, RouteSpecDetail>,
route_set: BTreeMap<BarePublicKey, RouteSpecDetail>,
hop_node_refs: Vec<NodeRef>,
directions: DirectionSet,
stability: Stability,
@ -54,17 +54,17 @@ impl RouteSetSpecDetail {
automatic,
}
}
pub fn get_route_by_key(&self, key: &PublicKey) -> Option<&RouteSpecDetail> {
pub fn get_route_by_key(&self, key: &BarePublicKey) -> Option<&RouteSpecDetail> {
self.route_set.get(key)
}
pub fn get_route_set_keys(&self) -> TypedPublicKeyGroup {
let mut tks = TypedPublicKeyGroup::new();
pub fn get_route_set_keys(&self) -> PublicKeyGroup {
let mut tks = PublicKeyGroup::new();
for (k, v) in &self.route_set {
tks.add(TypedPublicKey::new(v.crypto_kind, *k));
tks.add(PublicKey::new(v.crypto_kind, *k));
}
tks
}
pub fn get_best_route_set_key(&self) -> Option<PublicKey> {
pub fn get_best_route_set_key(&self) -> Option<BarePublicKey> {
self.get_route_set_keys().best().map(|k| k.value)
}
pub fn set_hop_node_refs(&mut self, node_refs: Vec<NodeRef>) {
@ -72,7 +72,7 @@ impl RouteSetSpecDetail {
}
pub fn iter_route_set(
&self,
) -> alloc::collections::btree_map::Iter<PublicKey, RouteSpecDetail> {
) -> alloc::collections::btree_map::Iter<BarePublicKey, RouteSpecDetail> {
self.route_set.iter()
}
pub fn get_stats(&self) -> &RouteStats {
@ -109,7 +109,7 @@ impl RouteSetSpecDetail {
Sequencing::EnsureOrdered => self.can_do_sequenced,
}
}
pub fn contains_nodes(&self, nodes: &[TypedNodeId]) -> bool {
pub fn contains_nodes(&self, nodes: &[NodeId]) -> bool {
for tk in nodes {
for rsd in self.route_set.values() {
if rsd.crypto_kind == tk.kind && rsd.hops.contains(&tk.value) {

View file

@ -4,8 +4,8 @@ impl_veilid_log_facility!("rtab");
// Compiled route key for caching
#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
struct CompiledRouteCacheKey {
sr_pubkey: PublicKey,
pr_pubkey: PublicKey,
sr_pubkey: BarePublicKey,
pr_pubkey: BarePublicKey,
}
/// Compiled route (safety route + private route)
@ -14,7 +14,7 @@ pub struct CompiledRoute {
/// The safety route attached to the private route
pub safety_route: SafetyRoute,
/// The secret used to encrypt the message payload
pub secret: SecretKey,
pub secret: BareSecretKey,
/// The node ref to the first hop in the compiled route
/// filtered to the safetyselection it was compiled with
pub first_hop: FilteredNodeRef,
@ -26,21 +26,21 @@ pub struct RouteSpecStoreCache {
/// Registry accessor
registry: VeilidComponentRegistry,
/// How many times nodes have been used
used_nodes: HashMap<NodeId, usize>,
used_nodes: HashMap<BareNodeId, usize>,
/// How many times nodes have been used at the terminal point of a route
used_end_nodes: HashMap<NodeId, usize>,
used_end_nodes: HashMap<BareNodeId, usize>,
/// Route spec hop cache, used to quickly disqualify routes
hop_cache: HashSet<Vec<u8>>,
/// Remote private routes we've imported and statistics
remote_private_route_set_cache: LruCache<RouteId, RemotePrivateRouteInfo>,
remote_private_route_set_cache: LruCache<BareRouteId, RemotePrivateRouteInfo>,
/// Remote private route ids indexed by route's public key
remote_private_routes_by_key: HashMap<PublicKey, RouteId>,
remote_private_routes_by_key: HashMap<BarePublicKey, BareRouteId>,
/// Compiled route cache
compiled_route_cache: LruCache<CompiledRouteCacheKey, SafetyRoute>,
/// List of dead allocated routes
dead_routes: Vec<RouteId>,
dead_routes: Vec<BareRouteId>,
/// List of dead remote routes
dead_remote_routes: Vec<RouteId>,
dead_remote_routes: Vec<BareRouteId>,
}
impl_veilid_component_registry_accessor!(RouteSpecStoreCache);
@ -89,7 +89,7 @@ impl RouteSpecStoreCache {
pub fn remove_from_cache(
&mut self,
rti: &RoutingTableInner,
id: RouteId,
id: BareRouteId,
rssd: &RouteSetSpecDetail,
) -> bool {
let cache_key = rssd.make_cache_key(rti);
@ -139,14 +139,14 @@ impl RouteSpecStoreCache {
}
/// calculate how many times a node with a particular node id set has been used anywhere in the path of our allocated routes
pub fn get_used_node_count(&self, node_ids: &TypedNodeIdGroup) -> usize {
pub fn get_used_node_count(&self, node_ids: &NodeIdGroup) -> usize {
node_ids.iter().fold(0usize, |acc, k| {
acc + self.used_nodes.get(&k.value).cloned().unwrap_or_default()
})
}
/// calculate how many times a node with a particular node id set has been used at the end of the path of our allocated routes
pub fn get_used_end_node_count(&self, node_ids: &TypedNodeIdGroup) -> usize {
pub fn get_used_end_node_count(&self, node_ids: &NodeIdGroup) -> usize {
node_ids.iter().fold(0usize, |acc, k| {
acc + self
.used_end_nodes
@ -157,7 +157,7 @@ impl RouteSpecStoreCache {
}
/// add remote private route to caches
fn add_remote_private_route(&mut self, id: RouteId, rprinfo: RemotePrivateRouteInfo) {
fn add_remote_private_route(&mut self, id: BareRouteId, rprinfo: RemotePrivateRouteInfo) {
// also store in id by key table
for private_route in rprinfo.get_private_routes() {
self.remote_private_routes_by_key
@ -188,7 +188,7 @@ impl RouteSpecStoreCache {
}
/// iterate all of the remote private routes we have in the cache
pub fn get_remote_private_route_ids(&self, cur_ts: Timestamp) -> Vec<RouteId> {
pub fn get_remote_private_route_ids(&self, cur_ts: Timestamp) -> Vec<BareRouteId> {
self.remote_private_route_set_cache
.iter()
.filter_map(|(id, rpri)| {
@ -206,7 +206,7 @@ impl RouteSpecStoreCache {
pub fn get_remote_private_route(
&mut self,
cur_ts: Timestamp,
id: &RouteId,
id: &BareRouteId,
) -> Option<&RemotePrivateRouteInfo> {
if let Some(rpri) = self.remote_private_route_set_cache.get_mut(id) {
if !rpri.did_expire(cur_ts) {
@ -222,7 +222,7 @@ impl RouteSpecStoreCache {
pub fn get_remote_private_route_mut(
&mut self,
cur_ts: Timestamp,
id: &RouteId,
id: &BareRouteId,
) -> Option<&mut RemotePrivateRouteInfo> {
if let Some(rpri) = self.remote_private_route_set_cache.get_mut(id) {
if !rpri.did_expire(cur_ts) {
@ -238,7 +238,7 @@ impl RouteSpecStoreCache {
pub fn peek_remote_private_route(
&self,
cur_ts: Timestamp,
id: &RouteId,
id: &BareRouteId,
) -> Option<&RemotePrivateRouteInfo> {
if let Some(rpri) = self.remote_private_route_set_cache.peek(id) {
if !rpri.did_expire(cur_ts) {
@ -253,7 +253,7 @@ impl RouteSpecStoreCache {
pub fn peek_remote_private_route_mut(
&mut self,
cur_ts: Timestamp,
id: &RouteId,
id: &BareRouteId,
) -> Option<&mut RemotePrivateRouteInfo> {
if let Some(rpri) = self.remote_private_route_set_cache.peek_mut(id) {
if !rpri.did_expire(cur_ts) {
@ -265,7 +265,7 @@ impl RouteSpecStoreCache {
}
/// look up a remote private route id by one of the route public keys
pub fn get_remote_private_route_id_by_key(&self, key: &PublicKey) -> Option<RouteId> {
pub fn get_remote_private_route_id_by_key(&self, key: &BarePublicKey) -> Option<BareRouteId> {
self.remote_private_routes_by_key.get(key).cloned()
}
@ -276,7 +276,7 @@ impl RouteSpecStoreCache {
pub fn cache_remote_private_route(
&mut self,
cur_ts: Timestamp,
id: RouteId,
id: BareRouteId,
private_routes: Vec<PrivateRoute>,
) {
// get id for this route set
@ -300,7 +300,7 @@ impl RouteSpecStoreCache {
}
/// remove a remote private route from the cache
pub fn remove_remote_private_route(&mut self, id: RouteId) -> bool {
pub fn remove_remote_private_route(&mut self, id: BareRouteId) -> bool {
let Some(rprinfo) = self.remote_private_route_set_cache.remove(&id) else {
return false;
};
@ -316,7 +316,11 @@ impl RouteSpecStoreCache {
}
/// Stores a compiled 'safety + private' route so we don't have to compile it again later
pub fn add_to_compiled_route_cache(&mut self, pr_pubkey: PublicKey, safety_route: SafetyRoute) {
pub fn add_to_compiled_route_cache(
&mut self,
pr_pubkey: BarePublicKey,
safety_route: SafetyRoute,
) {
let key = CompiledRouteCacheKey {
sr_pubkey: safety_route.public_key.value,
pr_pubkey,
@ -330,8 +334,8 @@ impl RouteSpecStoreCache {
/// Looks up an existing compiled route from the safety and private route components
pub fn lookup_compiled_route_cache(
&mut self,
sr_pubkey: PublicKey,
pr_pubkey: PublicKey,
sr_pubkey: BarePublicKey,
pr_pubkey: BarePublicKey,
) -> Option<SafetyRoute> {
let key = CompiledRouteCacheKey {
sr_pubkey,
@ -341,7 +345,7 @@ impl RouteSpecStoreCache {
}
/// When routes are dropped, they should be removed from the compiled route cache
fn invalidate_compiled_route_cache(&mut self, dead_key: &PublicKey) {
fn invalidate_compiled_route_cache(&mut self, dead_key: &BarePublicKey) {
let mut dead_entries = Vec::new();
for (k, _v) in self.compiled_route_cache.iter() {
if k.sr_pubkey == *dead_key || k.pr_pubkey == *dead_key {
@ -354,7 +358,7 @@ impl RouteSpecStoreCache {
}
/// Take the dead local and remote routes so we can update clients
pub fn take_dead_routes(&mut self) -> Option<(Vec<RouteId>, Vec<RouteId>)> {
pub fn take_dead_routes(&mut self) -> Option<(Vec<BareRouteId>, Vec<BareRouteId>)> {
if self.dead_routes.is_empty() && self.dead_remote_routes.is_empty() {
// Nothing to do
return None;

View file

@ -4,9 +4,9 @@ use super::*;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub(super) struct RouteSpecStoreContent {
/// All of the route sets we have allocated so far indexed by key (many to one)
id_by_key: HashMap<PublicKey, RouteId>,
id_by_key: HashMap<BarePublicKey, BareRouteId>,
/// All of the route sets we have allocated so far
details: HashMap<RouteId, RouteSetSpecDetail>,
details: HashMap<BareRouteId, RouteSetSpecDetail>,
}
impl RouteSpecStoreContent {
@ -34,8 +34,7 @@ impl RouteSpecStoreContent {
// Go through best route and resolve noderefs
let mut hop_node_refs = Vec::with_capacity(rsd.hops.len());
for h in &rsd.hops {
let Ok(Some(nr)) =
routing_table.lookup_node_ref(TypedNodeId::new(rsd.crypto_kind, *h))
let Ok(Some(nr)) = routing_table.lookup_node_ref(NodeId::new(rsd.crypto_kind, *h))
else {
dead_ids.push(*rsid);
break;
@ -63,7 +62,7 @@ impl RouteSpecStoreContent {
Ok(())
}
pub fn add_detail(&mut self, id: RouteId, detail: RouteSetSpecDetail) {
pub fn add_detail(&mut self, id: BareRouteId, detail: RouteSetSpecDetail) {
assert!(!self.details.contains_key(&id));
// also store in id by key table
@ -72,7 +71,7 @@ impl RouteSpecStoreContent {
}
self.details.insert(id, detail);
}
pub fn remove_detail(&mut self, id: &RouteId) -> Option<RouteSetSpecDetail> {
pub fn remove_detail(&mut self, id: &BareRouteId) -> Option<RouteSetSpecDetail> {
let detail = self.details.remove(id)?;
for (pk, _) in detail.iter_route_set() {
let _ = self.id_by_key.remove(pk).unwrap();
@ -82,19 +81,21 @@ impl RouteSpecStoreContent {
pub fn get_detail_count(&self) -> usize {
self.details.len()
}
pub fn get_detail(&self, id: &RouteId) -> Option<&RouteSetSpecDetail> {
pub fn get_detail(&self, id: &BareRouteId) -> Option<&RouteSetSpecDetail> {
self.details.get(id)
}
pub fn get_detail_mut(&mut self, id: &RouteId) -> Option<&mut RouteSetSpecDetail> {
pub fn get_detail_mut(&mut self, id: &BareRouteId) -> Option<&mut RouteSetSpecDetail> {
self.details.get_mut(id)
}
pub fn get_id_by_key(&self, key: &PublicKey) -> Option<RouteId> {
pub fn get_id_by_key(&self, key: &BarePublicKey) -> Option<BareRouteId> {
self.id_by_key.get(key).cloned()
}
// pub fn iter_ids(&self) -> std::collections::hash_map::Keys<RouteId, RouteSetSpecDetail> {
// pub fn iter_ids(&self) -> std::collections::hash_map::Keys<BareRouteId, RouteSetSpecDetail> {
// self.details.keys()
// }
pub fn iter_details(&self) -> std::collections::hash_map::Iter<RouteId, RouteSetSpecDetail> {
pub fn iter_details(
&self,
) -> std::collections::hash_map::Iter<BareRouteId, RouteSetSpecDetail> {
self.details.iter()
}

View file

@ -55,7 +55,7 @@ pub struct RoutingTableInner {
/// Statistics about the total bandwidth to/from this node
pub(super) self_transfer_stats: TransferStatsDownUp,
/// Peers we have recently communicated with
pub(super) recent_peers: LruCache<TypedNodeId, RecentPeersEntry>,
pub(super) recent_peers: LruCache<NodeId, RecentPeersEntry>,
/// Async tagged critical sections table
/// Tag: "tick" -> in ticker
pub(super) critical_sections: AsyncTagLockTable<&'static str>,
@ -389,7 +389,7 @@ impl RoutingTableInner {
/// Attempt to settle buckets and remove entries down to the desired number
/// which may not be possible due extant NodeRefs
pub fn kick_bucket(&mut self, bucket_index: BucketIndex, exempt_peers: &BTreeSet<NodeId>) {
pub fn kick_bucket(&mut self, bucket_index: BucketIndex, exempt_peers: &BTreeSet<BareNodeId>) {
let bucket = self.get_bucket_mut(bucket_index);
let bucket_depth = Self::bucket_depth(bucket_index);
@ -655,7 +655,7 @@ impl RoutingTableInner {
fn update_bucket_entry_node_ids(
&mut self,
entry: Arc<BucketEntry>,
node_ids: &[TypedNodeId],
node_ids: &[NodeId],
) -> EyreResult<()> {
let routing_table = self.routing_table();
@ -743,11 +743,7 @@ impl RoutingTableInner {
/// the 'update_func' closure is called on the node, and, if created,
/// in a locked fashion as to ensure the bucket entry state is always valid
#[instrument(level = "trace", skip_all, err)]
fn create_node_ref<F>(
&mut self,
node_ids: &TypedNodeIdGroup,
update_func: F,
) -> EyreResult<NodeRef>
fn create_node_ref<F>(&mut self, node_ids: &NodeIdGroup, update_func: F) -> EyreResult<NodeRef>
where
F: FnOnce(&mut RoutingTableInner, &mut BucketEntryInner),
{
@ -764,7 +760,7 @@ impl RoutingTableInner {
// Look up all bucket entries and make sure we only have zero or one
// If we have more than one, pick the one with the best cryptokind to add node ids to
let mut best_entry: Option<Arc<BucketEntry>> = None;
let mut supported_node_ids = TypedNodeIdGroup::new();
let mut supported_node_ids = NodeIdGroup::new();
for node_id in node_ids.iter() {
// Ignore node ids we don't support
if !VALID_CRYPTO_KINDS.contains(&node_id.kind) {
@ -836,9 +832,9 @@ impl RoutingTableInner {
/// Resolve an existing routing table entry using any crypto kind and return a reference to it
#[instrument(level = "trace", skip_all, err)]
pub fn lookup_any_node_ref(&self, node_id_key: NodeId) -> EyreResult<Option<NodeRef>> {
pub fn lookup_any_node_ref(&self, node_id_key: BareNodeId) -> EyreResult<Option<NodeRef>> {
for ck in VALID_CRYPTO_KINDS {
if let Some(nr) = self.lookup_node_ref(TypedNodeId::new(ck, node_id_key))? {
if let Some(nr) = self.lookup_node_ref(NodeId::new(ck, node_id_key))? {
return Ok(Some(nr));
}
}
@ -847,7 +843,7 @@ impl RoutingTableInner {
/// Resolve an existing routing table entry and return a reference to it
#[instrument(level = "trace", skip_all, err)]
pub fn lookup_node_ref(&self, node_id: TypedNodeId) -> EyreResult<Option<NodeRef>> {
pub fn lookup_node_ref(&self, node_id: NodeId) -> EyreResult<Option<NodeRef>> {
if self.routing_table().matches_own_node_id(&[node_id]) {
bail!("can't look up own node id in routing table");
}
@ -866,7 +862,7 @@ impl RoutingTableInner {
#[instrument(level = "trace", skip_all, err)]
pub fn lookup_and_filter_noderef(
&self,
node_id: TypedNodeId,
node_id: NodeId,
routing_domain_set: RoutingDomainSet,
dial_info_filter: DialInfoFilter,
) -> EyreResult<Option<FilteredNodeRef>> {
@ -881,7 +877,7 @@ impl RoutingTableInner {
}
/// Resolve an existing routing table entry and call a function on its entry without using a noderef
pub fn with_node_entry<F, R>(&self, node_id: TypedNodeId, f: F) -> Option<R>
pub fn with_node_entry<F, R>(&self, node_id: NodeId, f: F) -> Option<R>
where
F: FnOnce(Arc<BucketEntry>) -> R,
{
@ -981,10 +977,10 @@ impl RoutingTableInner {
pub fn register_node_with_id(
&mut self,
routing_domain: RoutingDomain,
node_id: TypedNodeId,
node_id: NodeId,
timestamp: Timestamp,
) -> EyreResult<FilteredNodeRef> {
let nr = self.create_node_ref(&TypedNodeIdGroup::from(node_id), |_rti, e| {
let nr = self.create_node_ref(&NodeIdGroup::from(node_id), |_rti, e| {
//e.make_not_dead(timestamp);
e.touch_last_seen(timestamp);
})?;
@ -1102,7 +1098,7 @@ impl RoutingTableInner {
}
}
pub fn touch_recent_peer(&mut self, node_id: TypedNodeId, last_connection: Flow) {
pub fn touch_recent_peer(&mut self, node_id: NodeId, last_connection: Flow) {
self.recent_peers
.insert(node_id, RecentPeersEntry { last_connection });
}
@ -1330,7 +1326,7 @@ impl RoutingTableInner {
pub fn find_preferred_closest_nodes<T, O>(
&self,
node_count: usize,
node_id: TypedHashDigest,
node_id: HashDigest,
mut filters: VecDeque<RoutingTableEntryFilter>,
transform: T,
) -> VeilidAPIResult<Vec<O>>
@ -1404,8 +1400,8 @@ impl RoutingTableInner {
};
// distance is the next metric, closer nodes first
let da = vcrypto.distance(&HashDigest::from(a_key.value), &node_id.value);
let db = vcrypto.distance(&HashDigest::from(b_key.value), &node_id.value);
let da = vcrypto.distance(&BareHashDigest::from(a_key.value), &node_id.value);
let db = vcrypto.distance(&BareHashDigest::from(b_key.value), &node_id.value);
da.cmp(&db)
};
@ -1418,7 +1414,7 @@ impl RoutingTableInner {
#[instrument(level = "trace", skip_all)]
pub fn sort_and_clean_closest_noderefs(
&self,
node_id: TypedHashDigest,
node_id: HashDigest,
closest_nodes: &[NodeRef],
) -> Vec<NodeRef> {
// Lock all noderefs
@ -1536,7 +1532,7 @@ impl RoutingTableInner {
#[instrument(level = "trace", skip(self, filter, metric), ret)]
pub fn get_node_relative_performance(
&self,
node_id: TypedNodeId,
node_id: NodeId,
cur_ts: Timestamp,
filter: impl Fn(&BucketEntryInner) -> bool,
metric: impl Fn(&LatencyStats) -> TimestampDuration,
@ -1597,7 +1593,7 @@ impl RoutingTableInner {
#[instrument(level = "trace", skip_all)]
pub fn make_closest_noderef_sort<'a>(
crypto: &'a Crypto,
node_id: TypedHashDigest,
node_id: HashDigest,
) -> impl Fn(&LockedNodeRef, &LockedNodeRef) -> core::cmp::Ordering + 'a {
let kind = node_id.kind;
// Get cryptoversion to check distance with
@ -1616,8 +1612,8 @@ pub fn make_closest_noderef_sort<'a>(
let b_key = b_entry.node_ids().get(kind).unwrap();
// distance is the next metric, closer nodes first
let da = vcrypto.distance(&HashDigest::from(a_key.value), &node_id.value);
let db = vcrypto.distance(&HashDigest::from(b_key.value), &node_id.value);
let da = vcrypto.distance(&BareHashDigest::from(a_key.value), &node_id.value);
let db = vcrypto.distance(&BareHashDigest::from(b_key.value), &node_id.value);
da.cmp(&db)
})
})
@ -1626,16 +1622,22 @@ pub fn make_closest_noderef_sort<'a>(
pub fn make_closest_node_id_sort(
crypto: &Crypto,
node_id: TypedNodeId,
) -> impl Fn(&NodeId, &NodeId) -> core::cmp::Ordering + '_ {
node_id: NodeId,
) -> impl Fn(&BareNodeId, &BareNodeId) -> core::cmp::Ordering + '_ {
let kind = node_id.kind;
// Get cryptoversion to check distance with
let vcrypto = crypto.get(kind).unwrap();
move |a: &NodeId, b: &NodeId| -> core::cmp::Ordering {
move |a: &BareNodeId, b: &BareNodeId| -> core::cmp::Ordering {
// distance is the next metric, closer nodes first
let da = vcrypto.distance(&HashDigest::from(*a), &HashDigest::from(node_id.value));
let db = vcrypto.distance(&HashDigest::from(*b), &HashDigest::from(node_id.value));
let da = vcrypto.distance(
&BareHashDigest::from(*a),
&BareHashDigest::from(node_id.value),
);
let db = vcrypto.distance(
&BareHashDigest::from(*b),
&BareHashDigest::from(node_id.value),
);
da.cmp(&db)
}
}

View file

@ -62,7 +62,7 @@ impl RoutingTable {
}));
}
let mut bootstrapped_peer_id_set = HashSet::<TypedNodeId>::new();
let mut bootstrapped_peer_id_set = HashSet::<NodeId>::new();
let mut bootstrapped_peers = vec![];
loop {
match unord.next().timeout_at(stop_token.clone()).await {

View file

@ -23,7 +23,7 @@ impl RoutingTable {
let mut inner = self.inner.write();
// Get our exempt nodes for each crypto kind
let mut exempt_peers_by_kind = BTreeMap::<CryptoKind, BTreeSet<NodeId>>::new();
let mut exempt_peers_by_kind = BTreeMap::<CryptoKind, BTreeSet<BareNodeId>>::new();
for kind in VALID_CRYPTO_KINDS {
let our_node_id = self.node_id(kind);
@ -32,7 +32,7 @@ impl RoutingTable {
};
let sort = make_closest_node_id_sort(&crypto, our_node_id);
let mut closest_peers = BTreeSet::<NodeId>::new();
let mut closest_peers = BTreeSet::<BareNodeId>::new();
let mut closest_unreliable_count = 0usize;
let mut closest_reliable_count = 0usize;

View file

@ -19,7 +19,7 @@ impl RoutingTable {
})
}
/// Fastest routes sort
fn route_sort_latency_fn(a: &(RouteId, u64), b: &(RouteId, u64)) -> cmp::Ordering {
fn route_sort_latency_fn(a: &(BareRouteId, u64), b: &(BareRouteId, u64)) -> cmp::Ordering {
let mut al = a.1;
let mut bl = b.1;
// Treat zero latency as uncalculated
@ -46,14 +46,14 @@ impl RoutingTable {
///
/// If a route doesn't 'need_testing', then we neither test nor drop it
#[instrument(level = "trace", skip(self))]
fn get_allocated_routes_to_test(&self, cur_ts: Timestamp) -> Vec<RouteId> {
fn get_allocated_routes_to_test(&self, cur_ts: Timestamp) -> Vec<BareRouteId> {
let default_route_hop_count = self
.config()
.with(|c| c.network.rpc.default_route_hop_count as usize);
let mut must_test_routes = Vec::<RouteId>::new();
let mut unpublished_routes = Vec::<(RouteId, u64)>::new();
let mut expired_routes = Vec::<RouteId>::new();
let mut must_test_routes = Vec::<BareRouteId>::new();
let mut unpublished_routes = Vec::<(BareRouteId, u64)>::new();
let mut expired_routes = Vec::<BareRouteId>::new();
self.route_spec_store().list_allocated_routes(|k, v| {
let stats = v.get_stats();
// Ignore nodes that don't need testing
@ -110,7 +110,7 @@ impl RoutingTable {
async fn test_route_set(
&self,
stop_token: StopToken,
routes_needing_testing: Vec<RouteId>,
routes_needing_testing: Vec<BareRouteId>,
) -> EyreResult<()> {
if routes_needing_testing.is_empty() {
return Ok(());
@ -119,7 +119,7 @@ impl RoutingTable {
#[derive(Default, Debug)]
struct TestRouteContext {
dead_routes: Vec<RouteId>,
dead_routes: Vec<BareRouteId>,
}
let ctx = Arc::new(Mutex::new(TestRouteContext::default()));

View file

@ -1,18 +1,18 @@
use super::*;
use crate::{routing_table::*, RegisteredComponents, VALID_CRYPTO_KINDS};
fn make_mock_typed_node_id(kind: CryptoKind, idx: u8) -> TypedNodeId {
TypedNodeId::new(
fn make_mock_typed_node_id(kind: CryptoKind, idx: u8) -> NodeId {
NodeId::new(
kind,
NodeId::new([
BareNodeId::new([
idx, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
]),
)
}
fn make_mock_typed_node_id_group(valid_kinds: bool, unknown: bool) -> TypedNodeIdGroup {
let mut tks = TypedNodeIdGroup::new();
fn make_mock_typed_node_id_group(valid_kinds: bool, unknown: bool) -> NodeIdGroup {
let mut tks = NodeIdGroup::new();
if valid_kinds {
VALID_CRYPTO_KINDS.iter().for_each(|k| {
tks.add(make_mock_typed_node_id(*k, 0));
@ -24,7 +24,7 @@ fn make_mock_typed_node_id_group(valid_kinds: bool, unknown: bool) -> TypedNodeI
tks
}
fn make_mock_peer_info(node_ids: TypedNodeIdGroup) -> EyreResult<PeerInfo> {
fn make_mock_peer_info(node_ids: NodeIdGroup) -> EyreResult<PeerInfo> {
PeerInfo::new(
RoutingDomain::PublicInternet,
node_ids,

View file

@ -10,11 +10,11 @@ pub enum ContactMethod {
/// Contact the node directly
Direct(DialInfo),
/// Request via signal the node connect back directly (relay, target)
SignalReverse(TypedNodeId, TypedNodeId),
SignalReverse(NodeId, NodeId),
/// Request via signal the node negotiate a hole punch (relay, target)
SignalHolePunch(TypedNodeId, TypedNodeId),
SignalHolePunch(NodeId, NodeId),
/// Must use an inbound relay to reach the node
InboundRelay(TypedNodeId),
InboundRelay(NodeId),
/// Must use outbound relay to reach the node
OutboundRelay(TypedNodeId),
OutboundRelay(NodeId),
}

View file

@ -7,7 +7,7 @@ pub struct PeerInfo {
skip_serializing_if = "is_default_routing_domain"
)]
routing_domain: RoutingDomain,
node_ids: TypedNodeIdGroup,
node_ids: NodeIdGroup,
signed_node_info: SignedNodeInfo,
}
@ -32,7 +32,7 @@ impl fmt::Display for PeerInfo {
impl PeerInfo {
pub fn new(
routing_domain: RoutingDomain,
node_ids: TypedNodeIdGroup,
node_ids: NodeIdGroup,
signed_node_info: SignedNodeInfo,
) -> EyreResult<Self> {
if node_ids.is_empty() {
@ -68,13 +68,13 @@ impl PeerInfo {
pub fn routing_domain(&self) -> RoutingDomain {
self.routing_domain
}
pub fn node_ids(&self) -> &TypedNodeIdGroup {
pub fn node_ids(&self) -> &NodeIdGroup {
&self.node_ids
}
pub fn signed_node_info(&self) -> &SignedNodeInfo {
&self.signed_node_info
}
pub fn destructure(self) -> (RoutingDomain, TypedNodeIdGroup, SignedNodeInfo) {
pub fn destructure(self) -> (RoutingDomain, NodeIdGroup, SignedNodeInfo) {
(self.routing_domain, self.node_ids, self.signed_node_info)
}

View file

@ -5,7 +5,7 @@ use super::*;
pub struct SignedDirectNodeInfo {
node_info: NodeInfo,
timestamp: Timestamp,
signatures: Vec<TypedSignature>,
signatures: Vec<Signature>,
}
impl fmt::Display for SignedDirectNodeInfo {
@ -25,7 +25,7 @@ impl SignedDirectNodeInfo {
/// Returns a new SignedDirectNodeInfo that has its signatures validated.
/// On success, this will modify the node_ids set to only include node_ids whose signatures validate.
/// All signatures are stored however, as this can be passed to other nodes that may be able to validate those signatures.
pub fn new(node_info: NodeInfo, timestamp: Timestamp, signatures: Vec<TypedSignature>) -> Self {
pub fn new(node_info: NodeInfo, timestamp: Timestamp, signatures: Vec<Signature>) -> Self {
Self {
node_info,
timestamp,
@ -35,12 +35,12 @@ impl SignedDirectNodeInfo {
pub fn validate(
&self,
node_ids: &TypedNodeIdGroup,
node_ids: &NodeIdGroup,
crypto: &Crypto,
) -> VeilidAPIResult<TypedNodeIdGroup> {
) -> VeilidAPIResult<NodeIdGroup> {
let node_info_bytes = Self::make_signature_bytes(&self.node_info, self.timestamp)?;
let public_keys = TypedPublicKeyGroup::from(node_ids.clone());
let public_keys = PublicKeyGroup::from(node_ids.clone());
// Verify the signatures that we can
let opt_validated_node_ids =
crypto.verify_signatures(&public_keys, &node_info_bytes, &self.signatures)?;
@ -56,14 +56,14 @@ impl SignedDirectNodeInfo {
pub fn make_signatures(
crypto: &Crypto,
typed_key_pairs: Vec<TypedKeyPair>,
typed_key_pairs: Vec<KeyPair>,
node_info: NodeInfo,
) -> VeilidAPIResult<Self> {
let timestamp = Timestamp::now();
let node_info_bytes = Self::make_signature_bytes(&node_info, timestamp)?;
let typed_signatures =
crypto.generate_signatures(&node_info_bytes, &typed_key_pairs, |kp, s| {
TypedSignature::new(kp.kind, s)
Signature::new(kp.kind, s)
})?;
Ok(Self {
node_info,
@ -108,7 +108,7 @@ impl SignedDirectNodeInfo {
pub fn timestamp(&self) -> Timestamp {
self.timestamp
}
pub fn signatures(&self) -> &[TypedSignature] {
pub fn signatures(&self) -> &[Signature] {
&self.signatures
}

View file

@ -26,9 +26,9 @@ impl fmt::Display for SignedNodeInfo {
impl SignedNodeInfo {
pub fn validate(
&self,
node_ids: &TypedNodeIdGroup,
node_ids: &NodeIdGroup,
crypto: &Crypto,
) -> VeilidAPIResult<TypedNodeIdGroup> {
) -> VeilidAPIResult<NodeIdGroup> {
match self {
SignedNodeInfo::Direct(d) => d.validate(node_ids, crypto),
SignedNodeInfo::Relayed(r) => r.validate(node_ids, crypto),
@ -54,9 +54,9 @@ impl SignedNodeInfo {
SignedNodeInfo::Relayed(r) => r.node_info(),
}
}
pub fn relay_ids(&self) -> TypedNodeIdGroup {
pub fn relay_ids(&self) -> NodeIdGroup {
match self {
SignedNodeInfo::Direct(_) => TypedNodeIdGroup::new(),
SignedNodeInfo::Direct(_) => NodeIdGroup::new(),
SignedNodeInfo::Relayed(r) => r.relay_ids().clone(),
}
}

View file

@ -4,10 +4,10 @@ use super::*;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SignedRelayedNodeInfo {
node_info: NodeInfo,
relay_ids: TypedNodeIdGroup,
relay_ids: NodeIdGroup,
relay_info: SignedDirectNodeInfo,
timestamp: Timestamp,
signatures: Vec<TypedSignature>,
signatures: Vec<Signature>,
}
impl fmt::Display for SignedRelayedNodeInfo {
@ -32,10 +32,10 @@ impl SignedRelayedNodeInfo {
/// All signatures are stored however, as this can be passed to other nodes that may be able to validate those signatures.
pub fn new(
node_info: NodeInfo,
relay_ids: TypedNodeIdGroup,
relay_ids: NodeIdGroup,
relay_info: SignedDirectNodeInfo,
timestamp: Timestamp,
signatures: Vec<TypedSignature>,
signatures: Vec<Signature>,
) -> Self {
Self {
node_info,
@ -48,9 +48,9 @@ impl SignedRelayedNodeInfo {
pub fn validate(
&self,
node_ids: &TypedNodeIdGroup,
node_ids: &NodeIdGroup,
crypto: &Crypto,
) -> VeilidAPIResult<TypedNodeIdGroup> {
) -> VeilidAPIResult<NodeIdGroup> {
// 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(),
@ -69,7 +69,7 @@ impl SignedRelayedNodeInfo {
&self.relay_info,
self.timestamp,
)?;
let public_keys = TypedPublicKeyGroup::from(node_ids.clone());
let public_keys = PublicKeyGroup::from(node_ids.clone());
let opt_validated_node_ids =
crypto.verify_signatures(&public_keys, &node_info_bytes, &self.signatures)?;
let Some(validated_node_ids) = opt_validated_node_ids else {
@ -78,14 +78,14 @@ impl SignedRelayedNodeInfo {
if validated_node_ids.is_empty() {
apibail_generic!("no valid node ids in relayed node info");
}
Ok(TypedNodeIdGroup::from(validated_node_ids))
Ok(NodeIdGroup::from(validated_node_ids))
}
pub fn make_signatures(
crypto: &Crypto,
typed_key_pairs: Vec<TypedKeyPair>,
typed_key_pairs: Vec<KeyPair>,
node_info: NodeInfo,
relay_ids: TypedNodeIdGroup,
relay_ids: NodeIdGroup,
relay_info: SignedDirectNodeInfo,
) -> VeilidAPIResult<Self> {
let timestamp = Timestamp::now();
@ -93,7 +93,7 @@ impl SignedRelayedNodeInfo {
Self::make_signature_bytes(&node_info, &relay_ids, &relay_info, timestamp)?;
let typed_signatures =
crypto.generate_signatures(&node_info_bytes, &typed_key_pairs, |kp, s| {
TypedSignature::new(kp.kind, s)
Signature::new(kp.kind, s)
})?;
Ok(Self {
node_info,
@ -106,7 +106,7 @@ impl SignedRelayedNodeInfo {
fn make_signature_bytes(
node_info: &NodeInfo,
relay_ids: &[TypedNodeId],
relay_ids: &[NodeId],
relay_info: &SignedDirectNodeInfo,
timestamp: Timestamp,
) -> VeilidAPIResult<Vec<u8>> {
@ -149,13 +149,13 @@ impl SignedRelayedNodeInfo {
pub fn timestamp(&self) -> Timestamp {
self.timestamp
}
pub fn relay_ids(&self) -> &TypedNodeIdGroup {
pub fn relay_ids(&self) -> &NodeIdGroup {
&self.relay_ids
}
pub fn relay_info(&self) -> &SignedDirectNodeInfo {
&self.relay_info
}
pub fn signatures(&self) -> &[TypedSignature] {
pub fn signatures(&self) -> &[Signature] {
&self.signatures
}

View file

@ -5,14 +5,14 @@ pub struct Answer<T> {
/// Hpw long it took to get this answer
pub _latency: TimestampDuration,
/// The private route requested to receive the reply
pub reply_private_route: Option<PublicKey>,
pub reply_private_route: Option<BarePublicKey>,
/// The answer itself
pub answer: T,
}
impl<T> Answer<T> {
pub fn new(
latency: TimestampDuration,
reply_private_route: Option<PublicKey>,
reply_private_route: Option<BarePublicKey>,
answer: T,
) -> Self {
Self {

View file

@ -1,7 +1,7 @@
use super::*;
use core::convert::TryInto;
pub fn decode_key256(public_key: &veilid_capnp::key256::Reader) -> PublicKey {
pub fn decode_key256(public_key: &veilid_capnp::key256::Reader) -> BarePublicKey {
let u0 = public_key.get_u0().to_be_bytes();
let u1 = public_key.get_u1().to_be_bytes();
let u2 = public_key.get_u2().to_be_bytes();
@ -13,10 +13,10 @@ pub fn decode_key256(public_key: &veilid_capnp::key256::Reader) -> PublicKey {
x[16..24].copy_from_slice(&u2);
x[24..32].copy_from_slice(&u3);
PublicKey::new(x)
BarePublicKey::new(x)
}
pub fn encode_key256(key: &PublicKey, builder: &mut veilid_capnp::key256::Builder) {
pub fn encode_key256(key: &BarePublicKey, builder: &mut veilid_capnp::key256::Builder) {
builder.set_u0(u64::from_be_bytes(
key.bytes[0..8]
.try_into()

View file

@ -1,6 +1,6 @@
use super::*;
pub fn encode_nonce(nonce: &Nonce, builder: &mut veilid_capnp::nonce24::Builder) {
pub fn encode_nonce(nonce: &BareNonce, builder: &mut veilid_capnp::nonce24::Builder) {
builder.set_u0(u64::from_be_bytes(
nonce.bytes[0..8]
.try_into()
@ -18,12 +18,12 @@ pub fn encode_nonce(nonce: &Nonce, builder: &mut veilid_capnp::nonce24::Builder)
));
}
pub fn decode_nonce(reader: &veilid_capnp::nonce24::Reader) -> Nonce {
pub fn decode_nonce(reader: &veilid_capnp::nonce24::Reader) -> BareNonce {
let u0 = reader.get_u0().to_be_bytes();
let u1 = reader.get_u1().to_be_bytes();
let u2 = reader.get_u2().to_be_bytes();
Nonce::new([
BareNonce::new([
u0[0], u0[1], u0[2], u0[3], u0[4], u0[5], u0[6], u0[7], // u0
u1[0], u1[1], u1[2], u1[3], u1[4], u1[5], u1[6], u1[7], // u1
u2[0], u2[1], u2[2], u2[3], u2[4], u2[5], u2[6], u2[7], // u2

View file

@ -6,22 +6,22 @@ const MAX_FIND_BLOCK_A_PEERS_LEN: usize = 10;
#[derive(Debug, Clone)]
pub(in crate::rpc_processor) struct RPCOperationFindBlockQ {
block_id: TypedPublicKey,
block_id: PublicKey,
}
impl RPCOperationFindBlockQ {
pub fn new(block_id: TypedPublicKey) -> Self {
pub fn new(block_id: PublicKey) -> Self {
Self { block_id }
}
pub fn validate(&mut self, _validate_context: &RPCValidateContext) -> Result<(), RPCError> {
Ok(())
}
pub fn block_id(&self) -> TypedPublicKey {
pub fn block_id(&self) -> PublicKey {
self.block_id
}
pub fn destructure(self) -> TypedPublicKey {
pub fn destructure(self) -> PublicKey {
self.block_id
}

View file

@ -4,12 +4,12 @@ const MAX_FIND_NODE_A_PEERS_LEN: usize = 20;
#[derive(Debug, Clone)]
pub(in crate::rpc_processor) struct RPCOperationFindNodeQ {
node_id: TypedNodeId,
node_id: NodeId,
capabilities: Vec<VeilidCapability>,
}
impl RPCOperationFindNodeQ {
pub fn new(node_id: TypedNodeId, capabilities: Vec<VeilidCapability>) -> Self {
pub fn new(node_id: NodeId, capabilities: Vec<VeilidCapability>) -> Self {
Self {
node_id,
capabilities,
@ -19,14 +19,14 @@ impl RPCOperationFindNodeQ {
Ok(())
}
// pub fn node_id(&self) -> &TypedKey {
// pub fn node_id(&self) -> &PublicKey {
// &self.node_id
// }
// pub fn capabilities(&self) -> &[VeilidCapability] {
// &self.capabilities
// }
pub fn destructure(self) -> (TypedNodeId, Vec<VeilidCapability>) {
pub fn destructure(self) -> (NodeId, Vec<VeilidCapability>) {
(self.node_id, self.capabilities)
}

View file

@ -22,13 +22,13 @@ impl fmt::Debug for ValidateGetValueContext {
#[derive(Debug, Clone)]
pub(in crate::rpc_processor) struct RPCOperationGetValueQ {
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
want_descriptor: bool,
}
impl RPCOperationGetValueQ {
pub fn new(key: TypedRecordKey, subkey: ValueSubkey, want_descriptor: bool) -> Self {
pub fn new(key: RecordKey, subkey: ValueSubkey, want_descriptor: bool) -> Self {
Self {
key,
subkey,
@ -39,7 +39,7 @@ impl RPCOperationGetValueQ {
Ok(())
}
// pub fn key(&self) -> &TypedKey {
// pub fn key(&self) -> &PublicKey {
// &self.key
// }
// pub fn subkey(&self) -> ValueSubkey {
@ -48,7 +48,7 @@ impl RPCOperationGetValueQ {
// pub fn want_descriptor(&self) -> bool {
// self.want_descriptor
// }
pub fn destructure(self) -> (TypedRecordKey, ValueSubkey, bool) {
pub fn destructure(self) -> (RecordKey, ValueSubkey, bool) {
(self.key, self.subkey, self.want_descriptor)
}

View file

@ -14,14 +14,14 @@ pub(in crate::rpc_processor) struct ValidateInspectValueContext {
#[derive(Debug, Clone)]
pub(in crate::rpc_processor) struct RPCOperationInspectValueQ {
key: TypedRecordKey,
key: RecordKey,
subkeys: ValueSubkeyRangeSet,
want_descriptor: bool,
}
impl RPCOperationInspectValueQ {
pub fn new(
key: TypedRecordKey,
key: RecordKey,
subkeys: ValueSubkeyRangeSet,
want_descriptor: bool,
) -> Result<Self, RPCError> {
@ -35,7 +35,7 @@ impl RPCOperationInspectValueQ {
Ok(())
}
// pub fn key(&self) -> &TypedKey {
// pub fn key(&self) -> &PublicKey {
// &self.key
// }
// pub fn subkeys(&self) -> &ValueSubkeyRangeSet {
@ -44,7 +44,7 @@ impl RPCOperationInspectValueQ {
// pub fn want_descriptor(&self) -> bool {
// self.want_descriptor
// }
pub fn destructure(self) -> (TypedRecordKey, ValueSubkeyRangeSet, bool) {
pub fn destructure(self) -> (RecordKey, ValueSubkeyRangeSet, bool) {
(self.key, self.subkeys, self.want_descriptor)
}

View file

@ -4,8 +4,8 @@ use super::*;
pub(in crate::rpc_processor) struct RoutedOperation {
routing_domain: RoutingDomain,
sequencing: Sequencing,
signatures: Vec<Signature>,
nonce: Nonce,
signatures: Vec<BareSignature>,
nonce: BareNonce,
data: Vec<u8>,
}
@ -25,7 +25,7 @@ impl RoutedOperation {
pub fn new(
routing_domain: RoutingDomain,
sequencing: Sequencing,
nonce: Nonce,
nonce: BareNonce,
data: Vec<u8>,
) -> Self {
Self {
@ -46,22 +46,22 @@ impl RoutedOperation {
pub fn sequencing(&self) -> Sequencing {
self.sequencing
}
pub fn signatures(&self) -> &[Signature] {
pub fn signatures(&self) -> &[BareSignature] {
&self.signatures
}
pub fn add_signature(&mut self, signature: Signature) {
pub fn add_signature(&mut self, signature: BareSignature) {
self.signatures.push(signature);
}
pub fn nonce(&self) -> &Nonce {
pub fn nonce(&self) -> &BareNonce {
&self.nonce
}
pub fn data(&self) -> &[u8] {
&self.data
}
// pub fn destructure(self) -> (Sequencing, Vec<Signature>, Nonce, Vec<u8>) {
// pub fn destructure(self) -> (Sequencing, Vec<BareSignature>, BareNonce, Vec<u8>) {
// (self.sequencing, self.signatures, self.nonce, self.data)
// }
@ -70,7 +70,7 @@ impl RoutedOperation {
reader: &veilid_capnp::routed_operation::Reader,
) -> Result<Self, RPCError> {
let sigs_reader = reader.get_signatures().map_err(RPCError::protocol)?;
let mut signatures = Vec::<Signature>::with_capacity(
let mut signatures = Vec::<BareSignature>::with_capacity(
sigs_reader
.len()
.try_into()

View file

@ -22,7 +22,7 @@ impl fmt::Debug for ValidateSetValueContext {
#[derive(Debug, Clone)]
pub(in crate::rpc_processor) struct RPCOperationSetValueQ {
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
value: SignedValueData,
descriptor: Option<SignedValueDescriptor>,
@ -30,7 +30,7 @@ pub(in crate::rpc_processor) struct RPCOperationSetValueQ {
impl RPCOperationSetValueQ {
pub fn new(
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
value: SignedValueData,
descriptor: Option<SignedValueDescriptor>,
@ -46,7 +46,7 @@ impl RPCOperationSetValueQ {
Ok(())
}
// pub fn key(&self) -> &TypedKey {
// pub fn key(&self) -> &PublicKey {
// &self.key
// }
@ -64,7 +64,7 @@ impl RPCOperationSetValueQ {
pub fn destructure(
self,
) -> (
TypedRecordKey,
RecordKey,
ValueSubkey,
SignedValueData,
Option<SignedValueDescriptor>,

View file

@ -4,22 +4,22 @@ const MAX_SUPPLY_BLOCK_A_PEERS_LEN: usize = 20;
#[derive(Debug, Clone)]
pub(in crate::rpc_processor) struct RPCOperationSupplyBlockQ {
block_id: TypedPublicKey,
block_id: PublicKey,
}
impl RPCOperationSupplyBlockQ {
pub fn new(block_id: TypedPublicKey) -> Self {
pub fn new(block_id: PublicKey) -> Self {
Self { block_id }
}
pub fn validate(&mut self, _validate_context: &RPCValidateContext) -> Result<(), RPCError> {
Ok(())
}
pub fn block_id(&self) -> &TypedPublicKey {
pub fn block_id(&self) -> &PublicKey {
&self.block_id
}
pub fn destructure(self) -> TypedPublicKey {
pub fn destructure(self) -> PublicKey {
self.block_id
}

View file

@ -5,7 +5,7 @@ const MAX_VALUE_CHANGED_SUBKEY_RANGES_LEN: usize = 512;
#[derive(Debug, Clone)]
pub(in crate::rpc_processor) struct RPCOperationValueChanged {
key: TypedRecordKey,
key: RecordKey,
subkeys: ValueSubkeyRangeSet,
count: u32,
watch_id: u64,
@ -14,7 +14,7 @@ pub(in crate::rpc_processor) struct RPCOperationValueChanged {
impl RPCOperationValueChanged {
pub fn new(
key: TypedRecordKey,
key: RecordKey,
subkeys: ValueSubkeyRangeSet,
count: u32,
watch_id: u64,
@ -58,7 +58,7 @@ impl RPCOperationValueChanged {
}
#[expect(dead_code)]
pub fn key(&self) -> &TypedRecordKey {
pub fn key(&self) -> &RecordKey {
&self.key
}
@ -85,7 +85,7 @@ impl RPCOperationValueChanged {
pub fn destructure(
self,
) -> (
TypedRecordKey,
RecordKey,
ValueSubkeyRangeSet,
u32,
u64,

View file

@ -5,23 +5,23 @@ const MAX_WATCH_VALUE_A_PEERS_LEN: usize = 20;
#[derive(Debug, Clone)]
pub(in crate::rpc_processor) struct RPCOperationWatchValueQ {
key: TypedRecordKey,
key: RecordKey,
subkeys: ValueSubkeyRangeSet,
expiration: u64,
count: u32,
watch_id: Option<u64>,
watcher: PublicKey,
signature: Signature,
watcher: BarePublicKey,
signature: BareSignature,
}
impl RPCOperationWatchValueQ {
pub fn new(
key: TypedRecordKey,
key: RecordKey,
subkeys: ValueSubkeyRangeSet,
expiration: u64,
count: u32,
watch_id: Option<u64>,
watcher: KeyPair,
watcher: BareKeyPair,
vcrypto: &CryptoSystemGuard<'_>,
) -> Result<Self, RPCError> {
if subkeys.ranges_len() > MAX_WATCH_VALUE_Q_SUBKEY_RANGES_LEN {
@ -51,7 +51,7 @@ impl RPCOperationWatchValueQ {
// signature covers: key, subkeys, expiration, count, using watcher key
fn make_signature_data(
key: &TypedRecordKey,
key: &RecordKey,
subkeys: &ValueSubkeyRangeSet,
expiration: u64,
count: u32,
@ -104,7 +104,7 @@ impl RPCOperationWatchValueQ {
}
#[expect(dead_code)]
pub fn key(&self) -> &TypedRecordKey {
pub fn key(&self) -> &RecordKey {
&self.key
}
@ -129,23 +129,23 @@ impl RPCOperationWatchValueQ {
}
#[expect(dead_code)]
pub fn watcher(&self) -> &PublicKey {
pub fn watcher(&self) -> &BarePublicKey {
&self.watcher
}
#[expect(dead_code)]
pub fn signature(&self) -> &Signature {
pub fn signature(&self) -> &BareSignature {
&self.signature
}
pub fn destructure(
self,
) -> (
TypedRecordKey,
RecordKey,
ValueSubkeyRangeSet,
u64,
u32,
Option<u64>,
PublicKey,
Signature,
BarePublicKey,
BareSignature,
) {
(
self.key,

View file

@ -39,7 +39,7 @@ pub fn decode_peer_info(
.reborrow()
.get_signed_node_info()
.map_err(RPCError::protocol)?;
let mut node_ids = TypedNodeIdGroup::with_capacity(nids_reader.len() as usize);
let mut node_ids = NodeIdGroup::with_capacity(nids_reader.len() as usize);
for nid_reader in nids_reader.iter() {
node_ids.add(decode_typed_node_id(&nid_reader)?);
}

View file

@ -51,7 +51,7 @@ pub fn encode_route_hop(
) -> Result<(), RPCError> {
let node_builder = builder.reborrow().init_node();
match &route_hop.node {
RouteNode::NodeId(ni) => {
RouteNode::BareNodeId(ni) => {
let mut ni_builder = node_builder.init_node_id();
encode_key256(&(*ni).into(), &mut ni_builder);
}
@ -75,7 +75,7 @@ pub fn decode_route_hop(
let node = match n_reader.which().map_err(RPCError::protocol)? {
veilid_capnp::route_hop::node::Which::NodeId(ni) => {
let ni_reader = ni.map_err(RPCError::protocol)?;
RouteNode::NodeId(decode_key256(&ni_reader).into())
RouteNode::BareNodeId(decode_key256(&ni_reader).into())
}
veilid_capnp::route_hop::node::Which::PeerInfo(pi) => {
let pi_reader = pi.map_err(RPCError::protocol)?;

View file

@ -1,6 +1,6 @@
use super::*;
pub fn encode_signature512(sig: &Signature, builder: &mut veilid_capnp::signature512::Builder) {
pub fn encode_signature512(sig: &BareSignature, builder: &mut veilid_capnp::signature512::Builder) {
let sig = &sig.bytes;
builder.set_u0(u64::from_be_bytes(
@ -29,7 +29,7 @@ pub fn encode_signature512(sig: &Signature, builder: &mut veilid_capnp::signatur
));
}
pub fn decode_signature512(reader: &veilid_capnp::signature512::Reader) -> Signature {
pub fn decode_signature512(reader: &veilid_capnp::signature512::Reader) -> BareSignature {
let u0 = reader.get_u0().to_be_bytes();
let u1 = reader.get_u1().to_be_bytes();
let u2 = reader.get_u2().to_be_bytes();
@ -39,7 +39,7 @@ pub fn decode_signature512(reader: &veilid_capnp::signature512::Reader) -> Signa
let u6 = reader.get_u6().to_be_bytes();
let u7 = reader.get_u7().to_be_bytes();
Signature::new([
BareSignature::new([
u0[0], u0[1], u0[2], u0[3], u0[4], u0[5], u0[6], u0[7], // u0
u1[0], u1[1], u1[2], u1[3], u1[4], u1[5], u1[6], u1[7], // u1
u2[0], u2[1], u2[2], u2[3], u2[4], u2[5], u2[6], u2[7], // u2

View file

@ -69,7 +69,7 @@ pub fn decode_signed_relayed_node_info(
if rid_count > MAX_CRYPTO_KINDS {
return Err(RPCError::protocol("too many relay ids"));
}
let mut relay_ids = TypedNodeIdGroup::with_capacity(rid_count);
let mut relay_ids = NodeIdGroup::with_capacity(rid_count);
for rid_reader in rids_reader {
let relay_id = decode_typed_node_id(&rid_reader)?;
relay_ids.add(relay_id);

View file

@ -2,20 +2,20 @@ use super::*;
pub fn decode_typed_public_key(
typed_key: &veilid_capnp::typed_key::Reader,
) -> Result<TypedPublicKey, RPCError> {
) -> Result<PublicKey, RPCError> {
let key_reader = typed_key
.get_key()
.map_err(RPCError::map_invalid_format("invalid typed key"))?;
let kind = typed_key.get_kind();
Ok(TypedPublicKey::new(
Ok(PublicKey::new(
CryptoKind::from(kind.to_be_bytes()),
decode_key256(&key_reader),
))
}
pub fn encode_typed_public_key(
typed_key: &TypedPublicKey,
typed_key: &PublicKey,
builder: &mut veilid_capnp::typed_key::Builder,
) {
builder.set_kind(u32::from_be_bytes(typed_key.kind.0));
@ -25,46 +25,43 @@ pub fn encode_typed_public_key(
pub fn decode_typed_node_id(
typed_key: &veilid_capnp::typed_key::Reader,
) -> Result<TypedNodeId, RPCError> {
) -> Result<NodeId, RPCError> {
let key_reader = typed_key
.get_key()
.map_err(RPCError::map_invalid_format("invalid typed key"))?;
let kind = typed_key.get_kind();
Ok(TypedNodeId::new(
Ok(NodeId::new(
CryptoKind::from(kind.to_be_bytes()),
NodeId::new(decode_key256(&key_reader).bytes),
BareNodeId::new(decode_key256(&key_reader).bytes),
))
}
pub fn encode_typed_node_id(
typed_key: &TypedNodeId,
builder: &mut veilid_capnp::typed_key::Builder,
) {
pub fn encode_typed_node_id(typed_key: &NodeId, builder: &mut veilid_capnp::typed_key::Builder) {
builder.set_kind(u32::from_be_bytes(typed_key.kind.0));
let mut key_builder = builder.reborrow().init_key();
encode_key256(&PublicKey::new(typed_key.value.bytes), &mut key_builder);
encode_key256(&BarePublicKey::new(typed_key.value.bytes), &mut key_builder);
}
pub fn decode_typed_record_key(
typed_key: &veilid_capnp::typed_key::Reader,
) -> Result<TypedRecordKey, RPCError> {
) -> Result<RecordKey, RPCError> {
let key_reader = typed_key
.get_key()
.map_err(RPCError::map_invalid_format("invalid typed key"))?;
let kind = typed_key.get_kind();
Ok(TypedRecordKey::new(
Ok(RecordKey::new(
CryptoKind::from(kind.to_be_bytes()),
RecordKey::new(decode_key256(&key_reader).bytes),
BareRecordKey::new(decode_key256(&key_reader).bytes),
))
}
pub fn encode_typed_record_key(
typed_key: &TypedRecordKey,
typed_key: &RecordKey,
builder: &mut veilid_capnp::typed_key::Builder,
) {
builder.set_kind(u32::from_be_bytes(typed_key.kind.0));
let mut key_builder = builder.reborrow().init_key();
encode_key256(&PublicKey::new(typed_key.value.bytes), &mut key_builder);
encode_key256(&BarePublicKey::new(typed_key.value.bytes), &mut key_builder);
}

View file

@ -2,20 +2,20 @@ use super::*;
pub fn decode_typed_signature(
typed_signature: &veilid_capnp::typed_signature::Reader,
) -> Result<TypedSignature, RPCError> {
) -> Result<Signature, RPCError> {
let sig_reader = typed_signature
.get_signature()
.map_err(RPCError::map_invalid_format("invalid typed signature"))?;
let kind = typed_signature.get_kind();
Ok(TypedSignature::new(
Ok(Signature::new(
CryptoKind::from(kind.to_be_bytes()),
decode_signature512(&sig_reader),
))
}
pub fn encode_typed_signature(
typed_signature: &TypedSignature,
typed_signature: &Signature,
builder: &mut veilid_capnp::typed_signature::Builder,
) {
builder.set_kind(u32::from_be_bytes(typed_signature.kind.0));

View file

@ -107,7 +107,7 @@ impl Destination {
}
}
pub fn get_target_node_ids(&self) -> Option<TypedNodeIdGroup> {
pub fn get_target_node_ids(&self) -> Option<NodeIdGroup> {
match self {
Destination::Direct {
node,
@ -130,20 +130,18 @@ impl Destination {
Destination::Direct {
node,
safety_selection: _,
} => {
Ok(Target::NodeId(node.best_node_id().ok_or_else(|| {
RPCError::protocol("no supported node id")
})?))
}
} => Ok(Target::BareNodeId(
node.best_node_id()
.ok_or_else(|| RPCError::protocol("no supported node id"))?,
)),
Destination::Relay {
relay: _,
node,
safety_selection: _,
} => {
Ok(Target::NodeId(node.best_node_id().ok_or_else(|| {
RPCError::protocol("no supported node id")
})?))
}
} => Ok(Target::BareNodeId(
node.best_node_id()
.ok_or_else(|| RPCError::protocol("no supported node id"))?,
)),
Destination::PrivateRoute {
private_route,
safety_selection: _,
@ -291,7 +289,7 @@ impl RPCProcessor {
safety_selection: SafetySelection,
) -> Result<rpc_processor::Destination, RPCError> {
match target {
Target::NodeId(node_id) => {
Target::BareNodeId(node_id) => {
// Resolve node
let nr = match self.resolve_node(node_id, safety_selection).await? {
Some(nr) => nr,
@ -423,7 +421,7 @@ impl RPCProcessor {
&private_route.public_key.value,
&published_peer_info,
) {
RouteNode::NodeId(routing_table.node_id(crypto_kind).value)
RouteNode::BareNodeId(routing_table.node_id(crypto_kind).value)
} else {
RouteNode::PeerInfo(published_peer_info)
};

View file

@ -112,7 +112,7 @@ pub enum FanoutCallDisposition {
}
pub type FanoutCallResult = Result<FanoutCallOutput, RPCError>;
pub type FanoutNodeInfoFilter = Arc<dyn (Fn(&[TypedNodeId], &NodeInfo) -> bool) + Send + Sync>;
pub type FanoutNodeInfoFilter = Arc<dyn (Fn(&[NodeId], &NodeInfo) -> bool) + Send + Sync>;
pub type FanoutCheckDone = Arc<dyn (Fn(&FanoutResult) -> bool) + Send + Sync>;
pub type FanoutCallRoutine =
Arc<dyn (Fn(NodeRef) -> PinBoxFutureStatic<FanoutCallResult>) + Send + Sync>;
@ -146,7 +146,7 @@ pub fn capability_fanout_node_info_filter(caps: Vec<VeilidCapability>) -> Fanout
/// in the given time
pub(crate) struct FanoutCall<'a> {
routing_table: &'a RoutingTable,
hash_coordinate: TypedHashDigest,
hash_coordinate: HashDigest,
node_count: usize,
fanout_tasks: usize,
consensus_count: usize,
@ -166,7 +166,7 @@ impl<'a> FanoutCall<'a> {
#[allow(clippy::too_many_arguments)]
pub fn new(
routing_table: &'a RoutingTable,
hash_coordinate: TypedHashDigest,
hash_coordinate: HashDigest,
node_count: usize,
fanout_tasks: usize,
consensus_count: usize,
@ -421,11 +421,17 @@ impl<'a> FanoutCall<'a> {
));
};
let node_sort = Box::new(
|a_key: &CryptoTyped<NodeId>, b_key: &CryptoTyped<NodeId>| -> core::cmp::Ordering {
let da =
vcrypto.distance(&HashDigest::from(a_key.value), &self.hash_coordinate.value);
let db =
vcrypto.distance(&HashDigest::from(b_key.value), &self.hash_coordinate.value);
|a_key: &CryptoTyped<BareNodeId>,
b_key: &CryptoTyped<BareNodeId>|
-> core::cmp::Ordering {
let da = vcrypto.distance(
&BareHashDigest::from(a_key.value),
&self.hash_coordinate.value,
);
let db = vcrypto.distance(
&BareHashDigest::from(b_key.value),
&self.hash_coordinate.value,
);
da.cmp(&db)
},
);

View file

@ -32,8 +32,7 @@ pub struct FanoutNode {
pub status: FanoutNodeStatus,
}
pub type FanoutQueueSort<'a> =
Box<dyn Fn(&TypedNodeId, &TypedNodeId) -> core::cmp::Ordering + Send + 'a>;
pub type FanoutQueueSort<'a> = Box<dyn Fn(&NodeId, &NodeId) -> core::cmp::Ordering + Send + 'a>;
pub struct FanoutQueue<'a> {
/// Link back to veilid component registry for logging
@ -41,9 +40,9 @@ pub struct FanoutQueue<'a> {
/// Crypto kind in use for this queue
crypto_kind: CryptoKind,
/// The status of all the nodes we have added so far
nodes: HashMap<TypedNodeId, FanoutNode>,
nodes: HashMap<NodeId, FanoutNode>,
/// Closer nodes to the record key are at the front of the list
sorted_nodes: Vec<TypedNodeId>,
sorted_nodes: Vec<NodeId>,
/// The sort function to use for the nodes
node_sort: FanoutQueueSort<'a>,
/// The channel to receive work requests to process
@ -265,7 +264,7 @@ impl<'a> FanoutQueue<'a> {
}
/// Review the nodes in the queue
pub fn with_nodes<R, F: FnOnce(&HashMap<TypedNodeId, FanoutNode>, &[TypedNodeId]) -> R>(
pub fn with_nodes<R, F: FnOnce(&HashMap<NodeId, FanoutNode>, &[NodeId]) -> R>(
&self,
func: F,
) -> R {

View file

@ -20,7 +20,7 @@ pub(in crate::rpc_processor) struct RPCMessageHeaderDetailSafetyRouted {
/// Direct header
pub direct: RPCMessageHeaderDetailDirect,
/// Remote safety route used
pub remote_safety_route: PublicKey,
pub remote_safety_route: BarePublicKey,
/// The sequencing used for this route
pub sequencing: Sequencing,
}
@ -31,9 +31,9 @@ pub(in crate::rpc_processor) struct RPCMessageHeaderDetailPrivateRouted {
/// Direct header
pub direct: RPCMessageHeaderDetailDirect,
/// Remote safety route used (or possibly node id the case of no safety route)
pub remote_safety_route: PublicKey,
pub remote_safety_route: BarePublicKey,
/// The private route we received the rpc over
pub private_route: PublicKey,
pub private_route: BarePublicKey,
// The safety spec for replying to this private routed rpc
pub safety_spec: SafetySpec,
}
@ -72,7 +72,7 @@ impl MessageHeader {
RPCMessageHeaderDetail::PrivateRouted(p) => p.direct.routing_domain,
}
}
pub fn direct_sender_node_id(&self) -> TypedNodeId {
pub fn direct_sender_node_id(&self) -> NodeId {
match &self.detail {
RPCMessageHeaderDetail::Direct(d) => d.envelope.get_sender_typed_id(),
RPCMessageHeaderDetail::SafetyRouted(s) => s.direct.envelope.get_sender_typed_id(),

View file

@ -81,9 +81,9 @@ struct WaitableReplyContext {
node_ref: NodeRef,
send_ts: Timestamp,
send_data_result: SendDataResult,
safety_route: Option<PublicKey>,
remote_private_route: Option<PublicKey>,
reply_private_route: Option<PublicKey>,
safety_route: Option<BarePublicKey>,
remote_private_route: Option<BarePublicKey>,
reply_private_route: Option<BarePublicKey>,
}
#[derive(Debug)]
@ -303,7 +303,7 @@ impl RPCProcessor {
fn process_sender_peer_info(
&self,
routing_domain: RoutingDomain,
sender_node_id: TypedNodeId,
sender_node_id: NodeId,
sender_peer_info: &SenderPeerInfo,
) -> RPCNetworkResult<Option<NodeRef>> {
let Some(peer_info) = sender_peer_info.opt_peer_info.clone() else {
@ -364,7 +364,7 @@ impl RPCProcessor {
#[instrument(level = "trace", target = "rpc", skip_all)]
async fn public_internet_peer_search(
&self,
node_id: TypedNodeId,
node_id: NodeId,
count: usize,
fanout: usize,
timeout_us: TimestampDuration,
@ -464,7 +464,7 @@ impl RPCProcessor {
#[instrument(level = "trace", target = "rpc", skip_all)]
pub fn resolve_node(
&self,
node_id: TypedNodeId,
node_id: NodeId,
safety_selection: SafetySelection,
) -> PinBoxFuture<Result<Option<NodeRef>, RPCError>> {
let registry = self.registry();
@ -602,7 +602,7 @@ impl RPCProcessor {
routing_domain: RoutingDomain,
safety_selection: SafetySelection,
remote_private_route: PrivateRoute,
reply_private_route: Option<PublicKey>,
reply_private_route: Option<BarePublicKey>,
message_data: Vec<u8>,
) -> RPCNetworkResult<RenderedOperation> {
let routing_table = self.routing_table();
@ -872,8 +872,8 @@ impl RPCProcessor {
rpc_kind: RPCKind,
send_ts: Timestamp,
node_ref: NodeRef,
safety_route: Option<PublicKey>,
remote_private_route: Option<PublicKey>,
safety_route: Option<BarePublicKey>,
remote_private_route: Option<BarePublicKey>,
) {
let wants_answer = matches!(rpc_kind, RPCKind::Question);
@ -949,8 +949,8 @@ impl RPCProcessor {
send_ts: Timestamp,
bytes: ByteCount,
node_ref: NodeRef,
safety_route: Option<PublicKey>,
remote_private_route: Option<PublicKey>,
safety_route: Option<BarePublicKey>,
remote_private_route: Option<BarePublicKey>,
ordered: bool,
) {
// Record for node if this was not sent via a route

View file

@ -11,11 +11,11 @@ pub struct RenderedOperation {
/// Total safety + private route hop count + 1 hop for the initial send
pub hop_count: usize,
/// The safety route used to send the message
pub safety_route: Option<PublicKey>,
pub safety_route: Option<BarePublicKey>,
/// The private route used to send the message
pub remote_private_route: Option<PublicKey>,
pub remote_private_route: Option<BarePublicKey>,
/// The private route requested to receive the reply
pub reply_private_route: Option<PublicKey>,
pub reply_private_route: Option<BarePublicKey>,
}
impl fmt::Debug for RenderedOperation {

View file

@ -122,7 +122,7 @@ impl RPCProcessor {
{
if sender.is_some() {
return Ok(NetworkResult::invalid_message(
"Direct NodeId senders are not allowed for AppCall when footgun is disabled",
"Direct BareNodeId senders are not allowed for AppCall when footgun is disabled",
));
}
}

View file

@ -85,7 +85,7 @@ impl RPCProcessor {
{
if sender.is_some() {
return Ok(NetworkResult::invalid_message(
"Direct NodeId senders are not allowed for AppMessage when footgun is disabled",
"Direct BareNodeId senders are not allowed for AppMessage when footgun is disabled",
));
}
}

View file

@ -13,7 +13,7 @@ impl RPCProcessor {
pub async fn rpc_call_find_node(
&self,
dest: Destination,
node_id: TypedNodeId,
node_id: NodeId,
capabilities: Vec<VeilidCapability>,
) -> RPCNetworkResult<Answer<Vec<Arc<PeerInfo>>>> {
let _guard = self

View file

@ -28,7 +28,7 @@ impl RPCProcessor {
pub async fn rpc_call_get_value(
&self,
dest: Destination,
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
last_descriptor: Option<SignedValueDescriptor>,
) -> RPCNetworkResult<Answer<GetValueAnswer>> {

View file

@ -30,7 +30,7 @@ impl RPCProcessor {
pub async fn rpc_call_inspect_value(
&self,
dest: Destination,
key: TypedRecordKey,
key: RecordKey,
subkeys: ValueSubkeyRangeSet,
last_descriptor: Option<SignedValueDescriptor>,
) -> RPCNetworkResult<Answer<InspectValueAnswer>> {

View file

@ -64,7 +64,7 @@ impl RPCProcessor {
&self,
routed_operation: RoutedOperation,
next_route_node: RouteNode,
safety_route_public_key: TypedPublicKey,
safety_route_public_key: PublicKey,
next_private_route: PrivateRoute,
) -> RPCNetworkResult<()> {
// Make sure hop count makes sense
@ -116,7 +116,7 @@ impl RPCProcessor {
detail: RPCMessageHeaderDetailDirect,
vcrypto: &CryptoSystemGuard<'_>,
routed_operation: RoutedOperation,
remote_sr_pubkey: TypedPublicKey,
remote_sr_pubkey: PublicKey,
) -> RPCNetworkResult<()> {
// Now that things are valid, decrypt the routed operation with DEC(nonce, DH(the SR's public key, the PR's (or node's) secret)
// xxx: punish nodes that send messages that fail to decrypt eventually? How to do this for safety routes?
@ -162,8 +162,8 @@ impl RPCProcessor {
detail: RPCMessageHeaderDetailDirect,
vcrypto: &CryptoSystemGuard<'_>,
routed_operation: RoutedOperation,
remote_sr_pubkey: TypedPublicKey,
pr_pubkey: TypedPublicKey,
remote_sr_pubkey: PublicKey,
pr_pubkey: PublicKey,
) -> RPCNetworkResult<()> {
// Get sender id of the peer with the crypto kind of the route
let Some(sender_id) = detail.sender_noderef.node_ids().get(pr_pubkey.kind) else {
@ -237,8 +237,8 @@ impl RPCProcessor {
detail: RPCMessageHeaderDetailDirect,
vcrypto: &CryptoSystemGuard<'_>,
routed_operation: RoutedOperation,
remote_sr_pubkey: TypedPublicKey,
pr_pubkey: TypedPublicKey,
remote_sr_pubkey: PublicKey,
pr_pubkey: PublicKey,
) -> RPCNetworkResult<()> {
// If the private route public key is our node id, then this was sent via safety route to our node directly
// so there will be no signatures to validate
@ -266,7 +266,7 @@ impl RPCProcessor {
async fn process_private_route_first_hop(
&self,
mut routed_operation: RoutedOperation,
sr_pubkey: TypedPublicKey,
sr_pubkey: PublicKey,
mut private_route: PrivateRoute,
) -> RPCNetworkResult<()> {
let Some(pr_first_hop) = private_route.pop_first_hop() else {
@ -331,7 +331,7 @@ impl RPCProcessor {
fn decrypt_private_route_hop_data(
&self,
route_hop_data: &RouteHopData,
pr_pubkey: &TypedPublicKey,
pr_pubkey: &PublicKey,
routed_operation: &mut RoutedOperation,
) -> RPCNetworkResult<RouteHop> {
// Get crypto kind

View file

@ -30,7 +30,7 @@ impl RPCProcessor {
pub async fn rpc_call_set_value(
&self,
dest: Destination,
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
value: SignedValueData,
descriptor: SignedValueDescriptor,

View file

@ -9,7 +9,7 @@ impl RPCProcessor {
pub async fn rpc_call_value_changed(
&self,
dest: Destination,
key: TypedRecordKey,
key: RecordKey,
subkeys: ValueSubkeyRangeSet,
count: u32,
watch_id: u64,
@ -62,7 +62,7 @@ impl RPCProcessor {
"not processing value change over safety route",
));
}
RPCMessageHeaderDetail::PrivateRouted(p) => TypedNodeId::new(
RPCMessageHeaderDetail::PrivateRouted(p) => NodeId::new(
p.direct.envelope.get_crypto_kind(),
p.remote_safety_route.into(),
),

View file

@ -27,11 +27,11 @@ impl RPCProcessor {
pub async fn rpc_call_watch_value(
&self,
dest: Destination,
key: TypedRecordKey,
key: RecordKey,
subkeys: ValueSubkeyRangeSet,
expiration: Timestamp,
count: u32,
watcher: KeyPair,
watcher: BareKeyPair,
watch_id: Option<u64>,
) -> RPCNetworkResult<Answer<WatchValueAnswer>> {
let _guard = self

View file

@ -158,7 +158,7 @@ impl RPCProcessor {
pub(super) fn enqueue_safety_routed_message(
&self,
direct: RPCMessageHeaderDetailDirect,
remote_safety_route: PublicKey,
remote_safety_route: BarePublicKey,
sequencing: Sequencing,
body: Vec<u8>,
) -> EyreResult<()> {
@ -203,8 +203,8 @@ impl RPCProcessor {
pub(super) fn enqueue_private_routed_message(
&self,
direct: RPCMessageHeaderDetailDirect,
remote_safety_route: PublicKey,
private_route: PublicKey,
remote_safety_route: BarePublicKey,
private_route: BarePublicKey,
safety_spec: SafetySpec,
body: Vec<u8>,
) -> EyreResult<()> {

View file

@ -5,7 +5,7 @@ impl_veilid_log_facility!("stor");
pub(super) struct ActiveSubkeyWriteGuard {
registry: VeilidComponentRegistry,
done: bool,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
}
@ -31,7 +31,7 @@ impl StorageManager {
pub(super) fn mark_active_subkey_write_inner(
&self,
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
) -> Option<ActiveSubkeyWriteGuard> {
let asw = inner.active_subkey_writes.entry(record_key).or_default();

View file

@ -79,7 +79,7 @@ impl StorageManager {
pub async fn debug_local_record_subkey_info(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
) -> String {
let inner = self.inner.lock().await;
@ -92,7 +92,7 @@ impl StorageManager {
}
pub async fn debug_remote_record_subkey_info(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
) -> String {
let inner = self.inner.lock().await;
@ -103,7 +103,7 @@ impl StorageManager {
.debug_record_subkey_info(record_key, subkey)
.await
}
pub async fn debug_local_record_info(&self, record_key: TypedRecordKey) -> String {
pub async fn debug_local_record_info(&self, record_key: RecordKey) -> String {
let inner = self.inner.lock().await;
let Some(local_record_store) = &inner.local_record_store else {
return "not initialized".to_owned();
@ -119,7 +119,7 @@ impl StorageManager {
format!("{}\n{}", local_debug, opened_debug)
}
pub async fn debug_remote_record_info(&self, record_key: TypedRecordKey) -> String {
pub async fn debug_remote_record_info(&self, record_key: RecordKey) -> String {
let inner = self.inner.lock().await;
let Some(remote_record_store) = &inner.remote_record_store else {
return "not initialized".to_owned();

View file

@ -28,7 +28,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "dht", skip_all, err)]
pub(super) async fn outbound_get_value(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
safety_selection: SafetySelection,
last_get_result: GetResult,
@ -306,7 +306,7 @@ impl StorageManager {
pub(super) fn process_deferred_outbound_get_value_result(
&self,
res_rx: flume::Receiver<Result<get_value::OutboundGetValueResult, VeilidAPIError>>,
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
last_seq: ValueSeqNum,
) {
@ -358,7 +358,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "dht", skip_all)]
pub(super) async fn process_outbound_get_value_result(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
opt_last_seq: Option<u32>,
result: get_value::OutboundGetValueResult,
@ -406,7 +406,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "dht", skip_all)]
pub async fn inbound_get_value(
&self,
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
want_descriptor: bool,
) -> VeilidAPIResult<NetworkResult<GetResult>> {

View file

@ -57,7 +57,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "dht", skip_all, err)]
pub(super) async fn outbound_inspect_value(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
safety_selection: SafetySelection,
local_inspect_result: InspectResult,
@ -358,7 +358,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "dht", skip_all)]
pub async fn inbound_inspect_value(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
want_descriptor: bool,
) -> VeilidAPIResult<NetworkResult<InspectResult>> {

View file

@ -69,7 +69,7 @@ const REHYDRATION_REQUESTS: &[u8] = b"rehydration_requests";
/// A single 'value changed' message to send
struct ValueChangedInfo {
target: Target,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
count: u32,
watch_id: u64,
@ -80,18 +80,18 @@ struct ValueChangedInfo {
#[derive(Default)]
struct StorageManagerInner {
/// Records that have been 'opened' and are not yet closed
pub opened_records: HashMap<TypedRecordKey, OpenedRecord>,
pub opened_records: HashMap<RecordKey, OpenedRecord>,
/// Records that have ever been 'created' or 'opened' by this node, things we care about that we must republish to keep alive
pub local_record_store: Option<RecordStore<LocalRecordDetail>>,
/// Records that have been pushed to this node for distribution by other nodes, that we make an effort to republish
pub remote_record_store: Option<RecordStore<RemoteRecordDetail>>,
/// Record subkeys to commit to the network in the background,
/// either because they were written to offline, or due to a rehydration action
pub offline_subkey_writes: LinkedHashMap<TypedRecordKey, OfflineSubkeyWrite>,
pub offline_subkey_writes: LinkedHashMap<RecordKey, OfflineSubkeyWrite>,
/// Record subkeys that are currently being written to in the foreground
pub active_subkey_writes: HashMap<TypedRecordKey, ValueSubkeyRangeSet>,
pub active_subkey_writes: HashMap<RecordKey, ValueSubkeyRangeSet>,
/// Records that have pending rehydration requests
pub rehydration_requests: HashMap<TypedRecordKey, RehydrationRequest>,
pub rehydration_requests: HashMap<RecordKey, RehydrationRequest>,
/// State management for outbound watches
pub outbound_watch_manager: OutboundWatchManager,
/// Storage manager metadata that is persistent, including copy of offline subkey writes
@ -138,11 +138,11 @@ pub(crate) struct StorageManager {
rehydrate_records_task: TickTask<EyreReport>,
// Anonymous watch keys
anonymous_watch_keys: TypedKeyPairGroup,
anonymous_watch_keys: KeyPairGroup,
// Outbound watch operation lock
// Keeps changes to watches to one-at-a-time per record
outbound_watch_lock_table: AsyncTagLockTable<TypedRecordKey>,
outbound_watch_lock_table: AsyncTagLockTable<RecordKey>,
// Background operation processor
// for offline subkey writes, watch changes, and any other
@ -191,11 +191,11 @@ impl StorageManager {
let crypto = registry.crypto();
// Generate keys to use for anonymous watches
let mut anonymous_watch_keys = TypedKeyPairGroup::new();
let mut anonymous_watch_keys = KeyPairGroup::new();
for ck in VALID_CRYPTO_KINDS {
let vcrypto = crypto.get(ck).unwrap();
let kp = vcrypto.generate_keypair();
anonymous_watch_keys.add(TypedKeyPair::new(ck, kp));
anonymous_watch_keys.add(KeyPair::new(ck, kp));
}
let inner = Self::new_inner();
@ -503,8 +503,8 @@ impl StorageManager {
&self,
kind: CryptoKind,
schema: DHTSchema,
owner_key: &PublicKey,
) -> VeilidAPIResult<TypedRecordKey> {
owner_key: &BarePublicKey,
) -> VeilidAPIResult<RecordKey> {
// Get cryptosystem
let crypto = self.crypto();
let Some(vcrypto) = crypto.get(kind) else {
@ -523,7 +523,7 @@ impl StorageManager {
&self,
kind: CryptoKind,
schema: DHTSchema,
owner: Option<KeyPair>,
owner: Option<BareKeyPair>,
safety_selection: SafetySelection,
) -> VeilidAPIResult<DHTRecordDescriptor> {
let Ok(_guard) = self.startup_lock.enter() else {
@ -552,8 +552,8 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all)]
pub async fn open_record(
&self,
record_key: TypedRecordKey,
writer: Option<KeyPair>,
record_key: RecordKey,
writer: Option<BareKeyPair>,
safety_selection: SafetySelection,
) -> VeilidAPIResult<DHTRecordDescriptor> {
let Ok(_guard) = self.startup_lock.enter() else {
@ -635,7 +635,7 @@ impl StorageManager {
/// Close an opened local record
#[instrument(level = "trace", target = "stor", skip_all)]
pub async fn close_record(&self, record_key: TypedRecordKey) -> VeilidAPIResult<()> {
pub async fn close_record(&self, record_key: RecordKey) -> VeilidAPIResult<()> {
let Ok(_guard) = self.startup_lock.enter() else {
apibail_not_initialized!();
};
@ -665,7 +665,7 @@ impl StorageManager {
/// Delete a local record
#[instrument(level = "trace", target = "stor", skip_all)]
pub async fn delete_record(&self, record_key: TypedRecordKey) -> VeilidAPIResult<()> {
pub async fn delete_record(&self, record_key: RecordKey) -> VeilidAPIResult<()> {
let Ok(_guard) = self.startup_lock.enter() else {
apibail_not_initialized!();
};
@ -687,7 +687,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all)]
pub async fn get_value(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
force_refresh: bool,
) -> VeilidAPIResult<Option<ValueData>> {
@ -768,7 +768,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all)]
pub async fn set_value(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
data: Vec<u8>,
options: Option<SetDHTValueOptions>,
@ -975,7 +975,7 @@ impl StorageManager {
async fn background_process_set_value_results(
&self,
res_rx: flume::Receiver<VeilidAPIResult<set_value::OutboundSetValueResult>>,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
signed_value_data: Arc<SignedValueData>,
safety_selection: SafetySelection,
@ -1016,7 +1016,7 @@ impl StorageManager {
async fn foreground_process_set_value_results(
&self,
res_rx: flume::Receiver<VeilidAPIResult<set_value::OutboundSetValueResult>>,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
signed_value_data: Arc<SignedValueData>,
safety_selection: SafetySelection,
@ -1055,7 +1055,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all)]
pub async fn watch_values(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
expiration: Timestamp,
count: u32,
@ -1075,7 +1075,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all)]
async fn watch_values_inner(
&self,
watch_lock: AsyncTagLockGuard<TypedRecordKey>,
watch_lock: AsyncTagLockGuard<RecordKey>,
subkeys: ValueSubkeyRangeSet,
expiration: Timestamp,
count: u32,
@ -1159,7 +1159,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all)]
pub async fn cancel_watch_values(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
) -> VeilidAPIResult<bool> {
let Ok(_guard) = self.startup_lock.enter() else {
@ -1231,7 +1231,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all)]
pub async fn inspect_record(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
scope: DHTReportScope,
) -> VeilidAPIResult<DHTRecordReport> {
@ -1396,7 +1396,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip(self, value))]
fn update_callback_value_change(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
count: u32,
value: Option<ValueData>,
@ -1413,7 +1413,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all)]
fn check_fanout_set_offline(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
fanout_result: &FanoutResult,
) -> bool {
@ -1464,9 +1464,9 @@ impl StorageManager {
inner: &mut StorageManagerInner,
kind: CryptoKind,
schema: DHTSchema,
owner: Option<KeyPair>,
owner: Option<BareKeyPair>,
safety_selection: SafetySelection,
) -> VeilidAPIResult<(TypedRecordKey, KeyPair)> {
) -> VeilidAPIResult<(RecordKey, BareKeyPair)> {
// Get cryptosystem
let crypto = self.crypto();
let Some(vcrypto) = crypto.get(kind) else {
@ -1525,9 +1525,9 @@ impl StorageManager {
async fn move_remote_record_to_local_inner(
&self,
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
safety_selection: SafetySelection,
) -> VeilidAPIResult<Option<(PublicKey, DHTSchema)>> {
) -> VeilidAPIResult<Option<(BarePublicKey, DHTSchema)>> {
// Get local record store
let Some(local_record_store) = inner.local_record_store.as_mut() else {
apibail_not_initialized!();
@ -1600,8 +1600,8 @@ impl StorageManager {
async fn open_existing_record_inner(
&self,
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
writer: Option<KeyPair>,
record_key: RecordKey,
writer: Option<BareKeyPair>,
safety_selection: SafetySelection,
) -> VeilidAPIResult<Option<DHTRecordDescriptor>> {
// Get local record store
@ -1667,8 +1667,8 @@ impl StorageManager {
async fn open_new_record_inner(
&self,
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
writer: Option<KeyPair>,
record_key: RecordKey,
writer: Option<BareKeyPair>,
inspect_result: InspectResult,
safety_selection: SafetySelection,
) -> VeilidAPIResult<DHTRecordDescriptor> {
@ -1724,7 +1724,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all, err)]
async fn get_value_nodes(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
) -> VeilidAPIResult<Option<Vec<NodeRef>>> {
let inner = self.inner.lock().await;
// Get local record store
@ -1742,7 +1742,7 @@ impl StorageManager {
.copied()
.filter_map(|x| {
routing_table
.lookup_node_ref(TypedNodeId::new(record_key.kind, x))
.lookup_node_ref(NodeId::new(record_key.kind, x))
.ok()
.flatten()
})
@ -1756,7 +1756,7 @@ impl StorageManager {
fn process_fanout_results_inner<I: IntoIterator<Item = (ValueSubkeyRangeSet, FanoutResult)>>(
inner: &mut StorageManagerInner,
vcrypto: &CryptoSystemGuard<'_>,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey_results_iter: I,
is_set: bool,
consensus_count: usize,
@ -1796,10 +1796,14 @@ impl StorageManager {
return res;
}
// Distance is the next metric, closer nodes first
let da =
vcrypto.distance(&HashDigest::from(a.0), &HashDigest::from(record_key.value));
let db =
vcrypto.distance(&HashDigest::from(b.0), &HashDigest::from(record_key.value));
let da = vcrypto.distance(
&BareHashDigest::from(a.0),
&BareHashDigest::from(record_key.value),
);
let db = vcrypto.distance(
&BareHashDigest::from(b.0),
&BareHashDigest::from(record_key.value),
);
da.cmp(&db)
});
@ -1811,7 +1815,7 @@ impl StorageManager {
fn close_record_inner(
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
) -> VeilidAPIResult<()> {
let Some(local_record_store) = inner.local_record_store.as_mut() else {
apibail_not_initialized!();
@ -1835,7 +1839,7 @@ impl StorageManager {
async fn handle_get_local_value_inner(
&self,
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
want_descriptor: bool,
) -> VeilidAPIResult<GetResult> {
@ -1868,7 +1872,7 @@ impl StorageManager {
async fn handle_set_local_value_inner(
&self,
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
signed_value_data: Arc<SignedValueData>,
watch_update_mode: InboundWatchUpdateMode,
@ -1898,7 +1902,7 @@ impl StorageManager {
pub(super) async fn handle_inspect_local_value_inner(
&self,
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
want_descriptor: bool,
) -> VeilidAPIResult<InspectResult> {
@ -1926,7 +1930,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all, err)]
pub(super) async fn handle_get_remote_value_inner(
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
want_descriptor: bool,
) -> VeilidAPIResult<GetResult> {
@ -1950,7 +1954,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all, err)]
async fn handle_set_remote_value_inner(
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
signed_value_data: Arc<SignedValueData>,
signed_value_descriptor: Arc<SignedValueDescriptor>,
@ -1989,7 +1993,7 @@ impl StorageManager {
async fn handle_inspect_remote_value_inner(
&self,
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
want_descriptor: bool,
) -> VeilidAPIResult<InspectResult> {
@ -2016,15 +2020,15 @@ impl StorageManager {
fn get_key(
vcrypto: &CryptoSystemGuard<'_>,
owner_key: &PublicKey,
owner_key: &BarePublicKey,
schema_data: &[u8],
) -> TypedRecordKey {
) -> RecordKey {
let mut hash_data = Vec::<u8>::with_capacity(PUBLIC_KEY_LENGTH + 4 + schema_data.len());
hash_data.extend_from_slice(&vcrypto.kind().0);
hash_data.extend_from_slice(&owner_key.bytes);
hash_data.extend_from_slice(schema_data);
let hash = vcrypto.generate_hash(&hash_data);
TypedRecordKey::new(vcrypto.kind(), RecordKey::from(hash))
RecordKey::new(vcrypto.kind(), BareRecordKey::from(hash))
}
#[instrument(level = "trace", target = "stor", skip_all)]

View file

@ -21,7 +21,7 @@ impl StorageManager {
pub(super) fn add_offline_subkey_write_inner(
&self,
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
safety_selection: SafetySelection,
signed_value_data: Arc<SignedValueData>,
@ -49,7 +49,7 @@ impl StorageManager {
pub(super) fn get_offline_subkey_writes_subkey(
&self,
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
want_descriptor: bool,
) -> VeilidAPIResult<Option<GetResult>> {
@ -88,7 +88,7 @@ impl StorageManager {
pub(super) fn remove_old_offline_subkey_writes_inner(
&self,
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
signed_value_data: Arc<SignedValueData>,
) {
@ -144,7 +144,7 @@ impl StorageManager {
pub(super) fn finish_offline_subkey_writes_inner(
&self,
inner: &mut StorageManagerInner,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys_written: ValueSubkeyRangeSet,
subkeys_still_offline: ValueSubkeyRangeSet,
) {

View file

@ -19,13 +19,13 @@ impl_veilid_log_facility!("stor");
pub(in crate::storage_manager) struct OutboundWatchManager {
/// Each watch per record key
#[serde(skip)]
pub outbound_watches: HashMap<TypedRecordKey, OutboundWatch>,
pub outbound_watches: HashMap<RecordKey, OutboundWatch>,
/// Last known active watch per node+record
#[serde_as(as = "Vec<(_, _)>")]
pub per_node_states: HashMap<PerNodeKey, PerNodeState>,
/// Value changed updates that need inpection to determine if they should be reported
#[serde(skip)]
pub needs_change_inspection: HashMap<TypedRecordKey, ValueSubkeyRangeSet>,
pub needs_change_inspection: HashMap<RecordKey, ValueSubkeyRangeSet>,
}
impl fmt::Display for OutboundWatchManager {
@ -116,7 +116,7 @@ impl OutboundWatchManager {
pub fn set_desired_watch(
&mut self,
record_key: TypedRecordKey,
record_key: RecordKey,
desired_watch: Option<OutboundWatchParameters>,
) {
match self.outbound_watches.get_mut(&record_key) {
@ -139,7 +139,7 @@ impl OutboundWatchManager {
}
}
pub fn set_next_reconcile_ts(&mut self, record_key: TypedRecordKey, next_ts: Timestamp) {
pub fn set_next_reconcile_ts(&mut self, record_key: RecordKey, next_ts: Timestamp) {
if let Some(outbound_watch) = self.outbound_watches.get_mut(&record_key) {
if let Some(state) = outbound_watch.state_mut() {
state.edit(&self.per_node_states, |editor| {
@ -204,11 +204,7 @@ impl OutboundWatchManager {
}
/// Set a record up to be inspected for changed subkeys
pub fn enqueue_change_inspect(
&mut self,
record_key: TypedRecordKey,
subkeys: ValueSubkeyRangeSet,
) {
pub fn enqueue_change_inspect(&mut self, record_key: RecordKey, subkeys: ValueSubkeyRangeSet) {
self.needs_change_inspection
.entry(record_key)
.and_modify(|x| *x = x.union(&subkeys))

View file

@ -5,7 +5,7 @@ impl_veilid_log_facility!("stor");
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(in crate::storage_manager) struct OutboundWatch {
/// Record key being watched
record_key: TypedRecordKey,
record_key: RecordKey,
/// Current state
/// None means inactive/cancelled
@ -37,7 +37,7 @@ impl fmt::Display for OutboundWatch {
impl OutboundWatch {
/// Create new outbound watch with desired parameters
pub fn new(record_key: TypedRecordKey, desired: OutboundWatchParameters) -> Self {
pub fn new(record_key: RecordKey, desired: OutboundWatchParameters) -> Self {
Self {
record_key,
state: None,

View file

@ -13,7 +13,7 @@ pub struct OutboundWatchParameters {
/// Subkeys requested for this watch
pub subkeys: ValueSubkeyRangeSet,
/// What key to use to perform the watch
pub opt_watcher: Option<KeyPair>,
pub opt_watcher: Option<BareKeyPair>,
/// What safety selection to use on the network
pub safety_selection: SafetySelection,
}

View file

@ -15,7 +15,7 @@ pub(in crate::storage_manager) struct OutboundWatchState {
/// Calculated field: minimum expiration time for all our nodes
min_expiration_ts: Timestamp,
/// Calculated field: the set of value changed routes for this watch from all per node watches
value_changed_routes: BTreeSet<PublicKey>,
value_changed_routes: BTreeSet<BarePublicKey>,
}
impl fmt::Display for OutboundWatchState {
@ -122,7 +122,7 @@ impl OutboundWatchState {
pub fn min_expiration_ts(&self) -> Timestamp {
self.min_expiration_ts
}
pub fn value_changed_routes(&self) -> &BTreeSet<PublicKey> {
pub fn value_changed_routes(&self) -> &BTreeSet<BarePublicKey> {
&self.value_changed_routes
}

View file

@ -5,9 +5,9 @@ impl_veilid_log_facility!("stor");
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub(in crate::storage_manager) struct PerNodeKey {
/// Watched record key
pub record_key: TypedRecordKey,
pub record_key: RecordKey,
/// Watching node id
pub node_id: TypedNodeId,
pub node_id: NodeId,
}
impl fmt::Display for PerNodeKey {
@ -23,8 +23,8 @@ impl FromStr for PerNodeKey {
.split_once('@')
.ok_or_else(|| VeilidAPIError::parse_error("invalid per-node key", s))?;
Ok(PerNodeKey {
record_key: TypedRecordKey::from_str(rkey)?,
node_id: TypedNodeId::from_str(nid)?,
record_key: RecordKey::from_str(rkey)?,
node_id: NodeId::from_str(nid)?,
})
}
}
@ -36,7 +36,7 @@ pub(in crate::storage_manager) struct PerNodeState {
/// SafetySelection used to contact the node
pub safety_selection: SafetySelection,
/// What key was used to perform the watch
pub opt_watcher: Option<KeyPair>,
pub opt_watcher: Option<BareKeyPair>,
/// The expiration of a successful watch
pub expiration_ts: Timestamp,
/// How many value change notifications are left
@ -45,7 +45,7 @@ pub(in crate::storage_manager) struct PerNodeState {
#[serde(skip)]
pub watch_node_ref: Option<NodeRef>,
/// Which private route is responsible for receiving ValueChanged notifications
pub opt_value_changed_route: Option<PublicKey>,
pub opt_value_changed_route: Option<BarePublicKey>,
}
impl fmt::Display for PerNodeState {

View file

@ -10,7 +10,7 @@ pub struct InboundWatchParameters {
/// How many updates are left before forced expiration
pub count: u32,
/// The watching schema member key, or an anonymous key
pub watcher: PublicKey,
pub watcher: BarePublicKey,
/// The place where updates are sent
pub target: Target,
}

View file

@ -22,7 +22,7 @@ impl InspectCacheL2 {
#[derive(Debug)]
pub struct InspectCache {
cache: LruCache<TypedRecordKey, InspectCacheL2>,
cache: LruCache<RecordKey, InspectCacheL2>,
}
impl InspectCache {
@ -34,7 +34,7 @@ impl InspectCache {
pub fn get(
&mut self,
key: &TypedRecordKey,
key: &RecordKey,
subkeys: &ValueSubkeyRangeSet,
) -> Option<InspectCacheL2Value> {
if let Some(l2c) = self.cache.get_mut(key) {
@ -47,7 +47,7 @@ impl InspectCache {
pub fn put(
&mut self,
key: TypedRecordKey,
key: RecordKey,
subkeys: ValueSubkeyRangeSet,
value: InspectCacheL2Value,
) {
@ -58,16 +58,11 @@ impl InspectCache {
.insert(subkeys, value);
}
pub fn invalidate(&mut self, key: &TypedRecordKey) {
pub fn invalidate(&mut self, key: &RecordKey) {
self.cache.remove(key);
}
pub fn replace_subkey_seq(
&mut self,
key: &TypedRecordKey,
subkey: ValueSubkey,
seq: ValueSeqNum,
) {
pub fn replace_subkey_seq(&mut self, key: &RecordKey, subkey: ValueSubkey, seq: ValueSeqNum) {
let Some(l2) = self.cache.get_mut(key) else {
return;
};

View file

@ -2,7 +2,7 @@ use super::*;
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct RecordTableKey {
pub key: TypedRecordKey,
pub key: RecordKey,
}
impl RecordTableKey {
pub fn bytes(&self) -> [u8; HASH_DIGEST_LENGTH + 4] {
@ -21,15 +21,15 @@ impl TryFrom<&[u8]> for RecordTableKey {
}
let kind = CryptoKind::try_from(&bytes[0..4]).wrap_err("invalid kind")?;
let value =
RecordKey::try_from(&bytes[4..HASH_DIGEST_LENGTH + 4]).wrap_err("invalid value")?;
let key = TypedRecordKey::new(kind, value);
BareRecordKey::try_from(&bytes[4..HASH_DIGEST_LENGTH + 4]).wrap_err("invalid value")?;
let key = RecordKey::new(kind, value);
Ok(RecordTableKey { key })
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct SubkeyTableKey {
pub key: TypedRecordKey,
pub key: RecordKey,
pub subkey: ValueSubkey,
}
impl SubkeyTableKey {
@ -50,14 +50,14 @@ impl TryFrom<&[u8]> for SubkeyTableKey {
}
let kind = CryptoKind::try_from(&bytes[0..4]).wrap_err("invalid kind")?;
let value =
RecordKey::try_from(&bytes[4..HASH_DIGEST_LENGTH + 4]).wrap_err("invalid value")?;
BareRecordKey::try_from(&bytes[4..HASH_DIGEST_LENGTH + 4]).wrap_err("invalid value")?;
let subkey = ValueSubkey::from_le_bytes(
bytes[HASH_DIGEST_LENGTH + 4..HASH_DIGEST_LENGTH + 4 + 4]
.try_into()
.wrap_err("invalid subkey")?,
);
let key = TypedRecordKey::new(kind, value);
let key = RecordKey::new(kind, value);
Ok(SubkeyTableKey { key, subkey })
}
}

View file

@ -16,7 +16,7 @@ pub(in crate::storage_manager) struct LocalRecordDetail {
pub safety_selection: SafetySelection,
/// The nodes that we have seen this record cached on recently
#[serde(default)]
pub nodes: HashMap<NodeId, PerNodeRecordDetail>,
pub nodes: HashMap<BareNodeId, PerNodeRecordDetail>,
}
impl LocalRecordDetail {

View file

@ -469,11 +469,7 @@ where
}
#[instrument(level = "trace", target = "stor", skip_all, err)]
pub async fn new_record(
&mut self,
key: TypedRecordKey,
record: Record<D>,
) -> VeilidAPIResult<()> {
pub async fn new_record(&mut self, key: RecordKey, record: Record<D>) -> VeilidAPIResult<()> {
let rtk = RecordTableKey { key };
if self.record_index.contains_key(&rtk) {
apibail_internal!("record already exists");
@ -514,7 +510,7 @@ where
}
#[instrument(level = "trace", target = "stor", skip_all, err)]
pub async fn delete_record(&mut self, key: TypedRecordKey) -> VeilidAPIResult<()> {
pub async fn delete_record(&mut self, key: RecordKey) -> VeilidAPIResult<()> {
// Get the record table key
let rtk = RecordTableKey { key };
@ -540,13 +536,13 @@ where
}
#[instrument(level = "trace", target = "stor", skip_all)]
pub(super) fn contains_record(&mut self, key: TypedRecordKey) -> bool {
pub(super) fn contains_record(&mut self, key: RecordKey) -> bool {
let rtk = RecordTableKey { key };
self.record_index.contains_key(&rtk)
}
#[instrument(level = "trace", target = "stor", skip_all)]
pub(super) fn with_record<R, F>(&mut self, key: TypedRecordKey, f: F) -> Option<R>
pub(super) fn with_record<R, F>(&mut self, key: RecordKey, f: F) -> Option<R>
where
F: FnOnce(&Record<D>) -> R,
{
@ -570,7 +566,7 @@ where
}
#[instrument(level = "trace", target = "stor", skip_all)]
pub(super) fn peek_record<R, F>(&self, key: TypedRecordKey, f: F) -> Option<R>
pub(super) fn peek_record<R, F>(&self, key: RecordKey, f: F) -> Option<R>
where
F: FnOnce(&Record<D>) -> R,
{
@ -585,7 +581,7 @@ where
}
#[instrument(level = "trace", target = "stor", skip_all)]
pub(super) fn with_record_mut<R, F>(&mut self, key: TypedRecordKey, f: F) -> Option<R>
pub(super) fn with_record_mut<R, F>(&mut self, key: RecordKey, f: F) -> Option<R>
where
F: FnOnce(&mut Record<D>) -> R,
{
@ -611,7 +607,7 @@ where
#[instrument(level = "trace", target = "stor", skip_all, err)]
pub async fn get_subkey(
&mut self,
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
want_descriptor: bool,
) -> VeilidAPIResult<Option<GetResult>> {
@ -679,7 +675,7 @@ where
#[instrument(level = "trace", target = "stor", skip_all, err)]
pub async fn peek_subkey(
&self,
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
want_descriptor: bool,
) -> VeilidAPIResult<Option<GetResult>> {
@ -744,7 +740,7 @@ where
#[instrument(level = "trace", target = "stor", skip_all)]
async fn update_watched_value(
&mut self,
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
watch_update_mode: InboundWatchUpdateMode,
) {
@ -783,7 +779,7 @@ where
#[instrument(level = "trace", target = "stor", skip_all, err)]
pub async fn set_subkey(
&mut self,
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
signed_value_data: Arc<SignedValueData>,
watch_update_mode: InboundWatchUpdateMode,
@ -887,7 +883,7 @@ where
#[instrument(level = "trace", target = "stor", skip_all, err)]
pub async fn inspect_record(
&mut self,
key: TypedRecordKey,
key: RecordKey,
subkeys: &ValueSubkeyRangeSet,
want_descriptor: bool,
) -> VeilidAPIResult<Option<InspectResult>> {
@ -971,7 +967,7 @@ where
#[instrument(level = "trace", target = "stor", skip_all, err)]
pub async fn _change_existing_watch(
&mut self,
key: TypedRecordKey,
key: RecordKey,
params: InboundWatchParameters,
watch_id: u64,
) -> VeilidAPIResult<InboundWatchResult> {
@ -1008,9 +1004,9 @@ where
#[instrument(level = "trace", target = "stor", skip_all, err)]
pub async fn _create_new_watch(
&mut self,
key: TypedRecordKey,
key: RecordKey,
params: InboundWatchParameters,
member_check: Box<dyn Fn(PublicKey) -> bool + Send>,
member_check: Box<dyn Fn(BarePublicKey) -> bool + Send>,
) -> VeilidAPIResult<InboundWatchResult> {
// Generate a record-unique watch id > 0
let rtk = RecordTableKey { key };
@ -1099,7 +1095,7 @@ where
#[instrument(level = "trace", target = "stor", skip_all, err)]
pub async fn watch_record(
&mut self,
key: TypedRecordKey,
key: RecordKey,
mut params: InboundWatchParameters,
opt_watch_id: Option<u64>,
) -> VeilidAPIResult<InboundWatchResult> {
@ -1157,9 +1153,9 @@ where
#[instrument(level = "trace", target = "stor", skip_all, err)]
async fn cancel_watch(
&mut self,
key: TypedRecordKey,
key: RecordKey,
watch_id: u64,
watcher: PublicKey,
watcher: BarePublicKey,
) -> VeilidAPIResult<bool> {
if watch_id == 0 {
apibail_internal!("should not have let a zero watch id get here");
@ -1197,7 +1193,7 @@ where
#[instrument(level = "trace", target = "stor", skip_all)]
pub fn move_watches(
&mut self,
key: TypedRecordKey,
key: RecordKey,
in_watch: Option<(InboundWatchList, bool)>,
) -> Option<(InboundWatchList, bool)> {
let rtk = RecordTableKey { key };
@ -1235,7 +1231,7 @@ where
// ValueChangedInfo but without the subkey data that requires a double mutable borrow to get
struct EarlyValueChangedInfo {
target: Target,
key: TypedRecordKey,
key: RecordKey,
subkeys: ValueSubkeyRangeSet,
count: u32,
watch_id: u64,
@ -1373,7 +1369,7 @@ where
out
}
pub fn debug_record_info(&self, key: TypedRecordKey) -> String {
pub fn debug_record_info(&self, key: RecordKey) -> String {
let record_info = self
.peek_record(key, |r| format!("{:#?}", r))
.unwrap_or("Not found".to_owned());
@ -1386,11 +1382,7 @@ where
format!("{}\n{}\n", record_info, watched_record)
}
pub async fn debug_record_subkey_info(
&self,
key: TypedRecordKey,
subkey: ValueSubkey,
) -> String {
pub async fn debug_record_subkey_info(&self, key: RecordKey, subkey: ValueSubkey) -> String {
match self.peek_subkey(key, subkey, true).await {
Ok(Some(v)) => {
format!("{:#?}", v)

View file

@ -7,24 +7,24 @@ pub(in crate::storage_manager) struct OpenedRecord {
/// The key pair used to perform writes to subkey on this opened record
/// Without this, set_value() will fail regardless of which key or subkey is being written to
/// as all writes are signed
writer: Option<KeyPair>,
writer: Option<BareKeyPair>,
/// The safety selection in current use
safety_selection: SafetySelection,
}
impl OpenedRecord {
pub fn new(writer: Option<KeyPair>, safety_selection: SafetySelection) -> Self {
pub fn new(writer: Option<BareKeyPair>, safety_selection: SafetySelection) -> Self {
Self {
writer,
safety_selection,
}
}
pub fn writer(&self) -> Option<&KeyPair> {
pub fn writer(&self) -> Option<&BareKeyPair> {
self.writer.as_ref()
}
pub fn set_writer(&mut self, writer: Option<KeyPair>) {
pub fn set_writer(&mut self, writer: Option<BareKeyPair>) {
self.writer = writer;
}

View file

@ -37,7 +37,7 @@ where
pub fn descriptor(&self) -> Arc<SignedValueDescriptor> {
self.descriptor.clone()
}
pub fn owner(&self) -> &PublicKey {
pub fn owner(&self) -> &BarePublicKey {
self.descriptor.owner()
}

View file

@ -4,7 +4,7 @@ use super::{inspect_value::OutboundInspectValueResult, *};
#[derive(Debug, Clone)]
pub struct RehydrateReport {
/// The record key rehydrated
record_key: TypedRecordKey,
record_key: RecordKey,
/// The requested range of subkeys to rehydrate if necessary
subkeys: ValueSubkeyRangeSet,
/// The requested consensus count,
@ -24,7 +24,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all)]
pub async fn add_rehydration_request(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
consensus_count: usize,
) {
@ -55,7 +55,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip(self), ret, err)]
pub(super) async fn rehydrate_record(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
consensus_count: usize,
) -> VeilidAPIResult<RehydrateReport> {
@ -177,7 +177,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip(self), ret, err)]
pub(super) async fn rehydrate_all_subkeys(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
consensus_count: usize,
safety_selection: SafetySelection,
@ -217,7 +217,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip(self), ret, err)]
pub(super) async fn rehydrate_required_subkeys(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkeys: ValueSubkeyRangeSet,
consensus_count: usize,
safety_selection: SafetySelection,

View file

@ -28,7 +28,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "dht", skip_all, err)]
pub(super) async fn outbound_set_value(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
safety_selection: SafetySelection,
value: Arc<SignedValueData>,
@ -277,7 +277,7 @@ impl StorageManager {
pub(super) fn process_deferred_outbound_set_value_result(
&self,
res_rx: flume::Receiver<Result<set_value::OutboundSetValueResult, VeilidAPIError>>,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
requested_value_data: ValueData,
safety_selection: SafetySelection,
@ -343,7 +343,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "stor", skip_all, err)]
pub(super) async fn process_outbound_set_value_result(
&self,
record_key: TypedRecordKey,
record_key: RecordKey,
subkey: ValueSubkey,
requested_value_data: ValueData,
safety_selection: SafetySelection,
@ -407,7 +407,7 @@ impl StorageManager {
#[instrument(level = "trace", target = "dht", skip_all)]
pub async fn inbound_set_value(
&self,
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
value: Arc<SignedValueData>,
descriptor: Option<Arc<SignedValueDescriptor>>,

View file

@ -13,7 +13,7 @@ enum OfflineSubkeyWriteResult {
#[derive(Debug)]
struct WorkItem {
record_key: TypedRecordKey,
record_key: RecordKey,
safety_selection: SafetySelection,
subkeys: ValueSubkeyRangeSet,
}
@ -31,7 +31,7 @@ impl StorageManager {
async fn write_single_offline_subkey(
&self,
stop_token: StopToken,
key: TypedRecordKey,
key: RecordKey,
subkey: ValueSubkey,
safety_selection: SafetySelection,
) -> EyreResult<OfflineSubkeyWriteResult> {

Some files were not shown because too many files have changed in this diff Show more