Use NodeId instead of PublicKey where accurate

This commit is contained in:
Brandon Vandegrift 2025-05-23 20:19:25 -04:00
parent 9709ce326c
commit a6724d014b
63 changed files with 345 additions and 292 deletions

View file

@ -39,8 +39,8 @@ pub struct Envelope {
crypto_kind: CryptoKind,
timestamp: Timestamp,
nonce: Nonce,
sender_id: PublicKey,
recipient_id: PublicKey,
sender_id: NodeId,
recipient_id: NodeId,
}
impl Envelope {
@ -50,8 +50,8 @@ impl Envelope {
crypto_kind: CryptoKind,
timestamp: Timestamp,
nonce: Nonce,
sender_id: PublicKey,
recipient_id: PublicKey,
sender_id: NodeId,
recipient_id: NodeId,
) -> Self {
assert!(VALID_ENVELOPE_VERSIONS.contains(&version));
assert!(VALID_CRYPTO_KINDS.contains(&crypto_kind));
@ -140,8 +140,8 @@ impl Envelope {
.try_into()
.map_err(VeilidAPIError::internal)?;
let mut nonce: Nonce = Nonce::new(nonce_slice);
let mut sender_id = PublicKey::new(sender_id_slice);
let mut recipient_id = PublicKey::new(recipient_id_slice);
let mut sender_id = NodeId::new(sender_id_slice);
let mut recipient_id = NodeId::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() {
@ -173,7 +173,7 @@ impl Envelope {
// Validate signature
if !vcrypto
.verify(&sender_id, &data[0..(data.len() - 64)], &signature)
.verify(&sender_id.into(), &data[0..(data.len() - 64)], &signature)
.map_err(VeilidAPIError::internal)?
{
apibail_parse_error!("signature verification of envelope failed", signature);
@ -202,7 +202,7 @@ impl Envelope {
let vcrypto = crypto
.get(self.crypto_kind)
.expect("need to ensure only valid crypto kinds here");
let mut dh_secret = vcrypto.cached_dh(&self.sender_id, node_id_secret)?;
let mut dh_secret = vcrypto.cached_dh(&self.sender_id.into(), node_id_secret)?;
// Apply network key
if let Some(nk) = network_key.as_ref() {
@ -252,7 +252,7 @@ impl Envelope {
let vcrypto = crypto
.get(self.crypto_kind)
.expect("need to ensure only valid crypto kinds here");
let mut dh_secret = vcrypto.cached_dh(&self.recipient_id, node_id_secret)?;
let mut dh_secret = vcrypto.cached_dh(&self.recipient_id.into(), node_id_secret)?;
// Write envelope body
let mut data = vec![0u8; envelope_size];
@ -300,7 +300,7 @@ impl Envelope {
// Sign the envelope
let signature = vcrypto.sign(
&self.sender_id,
&self.sender_id.into(),
node_id_secret,
&data[0..(envelope_size - 64)],
)?;
@ -328,19 +328,19 @@ impl Envelope {
self.nonce
}
pub fn get_sender_id(&self) -> PublicKey {
pub fn get_sender_id(&self) -> NodeId {
self.sender_id
}
pub fn get_sender_typed_id(&self) -> TypedPublicKey {
TypedPublicKey::new(self.crypto_kind, self.sender_id)
pub fn get_sender_typed_id(&self) -> TypedNodeId {
TypedNodeId::new(self.crypto_kind, self.sender_id)
}
pub fn get_recipient_id(&self) -> PublicKey {
pub fn get_recipient_id(&self) -> NodeId {
self.recipient_id
}
pub fn get_recipient_typed_id(&self) -> TypedPublicKey {
TypedPublicKey::new(self.crypto_kind, self.recipient_id)
pub fn get_recipient_typed_id(&self) -> TypedNodeId {
TypedNodeId::new(self.crypto_kind, self.recipient_id)
}
}

View file

@ -352,7 +352,7 @@ impl Crypto {
&self,
vcrypto: AsyncCryptoSystemGuard<'_>,
table_store: &TableStore,
) -> VeilidAPIResult<(TypedPublicKey, TypedSecretKey)> {
) -> VeilidAPIResult<(TypedNodeId, TypedSecretKey)> {
let config = self.config();
let ck = vcrypto.kind();
let (mut node_id, mut node_id_secret) = config.with(|c| {
@ -371,7 +371,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::<TypedPublicKey>(0, table_key_node_id.as_bytes())
.load_json::<TypedNodeId>(0, table_key_node_id.as_bytes())
.await
{
veilid_log!(self debug "{} found in storage", table_key_node_id);
@ -400,7 +400,7 @@ impl Crypto {
if let (Some(node_id), Some(node_id_secret)) = (node_id, node_id_secret) {
// Validate node id
if !vcrypto
.validate_keypair(&node_id.value, &node_id_secret.value)
.validate_keypair(&node_id.value.into(), &node_id_secret.value)
.await
{
apibail_generic!(format!(
@ -414,7 +414,7 @@ impl Crypto {
veilid_log!(self debug "generating new node_id_{}", ck);
let kp = vcrypto.generate_keypair().await;
(
TypedPublicKey::new(ck, kp.key),
TypedNodeId::new(ck, kp.key.into()),
TypedSecretKey::new(ck, kp.secret),
)
};
@ -435,7 +435,7 @@ 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 = TypedPublicKeyGroup::new();
let mut out_node_id = TypedNodeIdGroup::new();
let mut out_node_id_secret = TypedSecretKeyGroup::new();
for ck in VALID_CRYPTO_KINDS {
@ -447,7 +447,7 @@ impl Crypto {
let (node_id, node_id_secret) = {
let kp = vcrypto.generate_keypair().await;
(
TypedPublicKey::new(ck, kp.key),
TypedNodeId::new(ck, kp.key.into()),
TypedSecretKey::new(ck, kp.secret),
)
};

View file

@ -36,7 +36,7 @@ pub struct Receipt {
version: u8,
crypto_kind: CryptoKind,
nonce: Nonce,
sender_id: PublicKey,
sender_id: NodeId,
extra_data: Vec<u8>,
}
@ -45,7 +45,7 @@ impl Receipt {
version: u8,
crypto_kind: CryptoKind,
nonce: Nonce,
sender_id: PublicKey,
sender_id: NodeId,
extra_data: D,
) -> VeilidAPIResult<Self> {
assert!(VALID_ENVELOPE_VERSIONS.contains(&version));
@ -114,7 +114,7 @@ impl Receipt {
}
// Get sender id
let sender_id = PublicKey::new(
let sender_id = NodeId::new(
data[0x22..0x42]
.try_into()
.map_err(VeilidAPIError::internal)?,
@ -129,7 +129,7 @@ impl Receipt {
// Validate signature
if !vcrypto
.verify(&sender_id, &data[0..(data.len() - 64)], &signature)
.verify(&sender_id.into(), &data[0..(data.len() - 64)], &signature)
.map_err(VeilidAPIError::generic)?
{
apibail_parse_error!("signature failure in receipt", signature);
@ -187,7 +187,11 @@ impl Receipt {
}
// Sign the receipt
let signature = vcrypto
.sign(&self.sender_id, secret, &data[0..(receipt_size - 64)])
.sign(
&self.sender_id.into(),
secret,
&data[0..(receipt_size - 64)],
)
.map_err(VeilidAPIError::generic)?;
// Append the signature
data[(receipt_size - 64)..].copy_from_slice(&signature.bytes);
@ -208,12 +212,12 @@ impl Receipt {
self.nonce
}
pub fn get_sender_id(&self) -> PublicKey {
pub fn get_sender_id(&self) -> NodeId {
self.sender_id
}
pub fn get_sender_typed_id(&self) -> TypedPublicKey {
TypedPublicKey::new(self.crypto_kind, self.sender_id)
pub fn get_sender_typed_id(&self) -> TypedNodeId {
TypedNodeId::new(self.crypto_kind, self.sender_id)
}
#[must_use]

View file

@ -25,8 +25,8 @@ pub async fn test_envelope_round_trip(
vcrypto.kind(),
ts,
nonce,
sender_id,
recipient_id,
sender_id.into(),
recipient_id.into(),
);
// Create arbitrary body
@ -77,8 +77,14 @@ pub async fn test_receipt_round_trip(
// Create receipt
let nonce = vcrypto.random_nonce().await;
let (sender_id, sender_secret) = vcrypto.generate_keypair().await.into_split();
let receipt = Receipt::try_new(envelope_version, vcrypto.kind(), nonce, sender_id, body)
.expect("should not fail");
let receipt = Receipt::try_new(
envelope_version,
vcrypto.kind(),
nonce,
sender_id.into(),
body,
)
.expect("should not fail");
// Serialize to bytes
let mut enc_data = receipt

View file

@ -345,13 +345,6 @@ impl From<NodeId> for HashDigest {
}
}
// Removing this will show where PublicKey might need to be converted to NodeId or RecordKey.
impl From<PublicKey> for HashDigest {
fn from(value: PublicKey) -> Self {
Self::new(value.bytes)
}
}
impl From<HashDigest> for PublicKey {
fn from(value: HashDigest) -> Self {
Self::new(value.bytes)

View file

@ -2,7 +2,7 @@ use super::*;
#[derive(Clone, Debug, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq, Hash, Default)]
#[serde(from = "Vec<CryptoTyped<K>>", into = "Vec<CryptoTyped<K>>")]
pub struct CryptoTypedGroup<K = PublicKey>
pub struct CryptoTypedGroup<K>
where
K: Clone
+ Copy

View file

@ -92,13 +92,40 @@ pub type TypedNodeIdGroup = CryptoTypedGroup<NodeId>;
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), declare)]
pub type TypedHashDigestGroup = CryptoTypedGroup<HashDigest>;
impl From<TypedPublicKey> for TypedHashDigest {
fn from(value: TypedPublicKey) -> Self {
impl From<TypedNodeId> for TypedHashDigest {
fn from(value: TypedNodeId) -> Self {
TypedHashDigest::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<TypedNodeId> for TypedPublicKey {
fn from(value: TypedNodeId) -> Self {
TypedPublicKey::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<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<TypedPublicKeyGroup> for TypedNodeIdGroup {
fn from(value: TypedPublicKeyGroup) -> Self {
let items: Vec<TypedNodeId> = value.iter().map(|node_id| (*node_id).into()).collect();
TypedNodeIdGroup::from(items)
}
}

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<TypedPublicKey, Punishment>,
punishments_by_node_id: BTreeMap<TypedNodeId, Punishment>,
dial_info_failures: BTreeMap<DialInfo, Timestamp>,
}
@ -178,7 +178,7 @@ impl AddressFilter {
}
// node id
{
let mut dead_keys = Vec::<TypedPublicKey>::new();
let mut dead_keys = Vec::<TypedNodeId>::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,23 +297,19 @@ impl AddressFilter {
};
}
fn is_node_id_punished_inner(
&self,
inner: &AddressFilterInner,
node_id: TypedPublicKey,
) -> bool {
fn is_node_id_punished_inner(&self, inner: &AddressFilterInner, node_id: TypedNodeId) -> bool {
if inner.punishments_by_node_id.contains_key(&node_id) {
return true;
}
false
}
pub fn is_node_id_punished(&self, node_id: TypedPublicKey) -> bool {
pub fn is_node_id_punished(&self, node_id: TypedNodeId) -> bool {
let inner = self.inner.lock();
self.is_node_id_punished_inner(&inner, node_id)
}
pub fn punish_node_id(&self, node_id: TypedPublicKey, reason: PunishmentReason) {
pub fn punish_node_id(&self, node_id: TypedNodeId, 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: TypedPublicKeyGroup,
node_ids: TypedNodeIdGroup,
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: TypedPublicKeyGroup,
node_ids: TypedNodeIdGroup,
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) -> &TypedPublicKeyGroup {
pub fn node_ids(&self) -> &TypedNodeIdGroup {
&self.node_ids
}
pub fn envelope_support(&self) -> &[u8] {
@ -309,10 +309,10 @@ impl BootstrapRecord {
envelope_support.dedup();
// Node Id
let mut node_ids = TypedPublicKeyGroup::new();
let mut node_ids = TypedNodeIdGroup::new();
for node_id_str in fields[2].split(',') {
let node_id_str = node_id_str.trim();
let node_id = match TypedPublicKey::from_str(node_id_str) {
let node_id = match TypedNodeId::from_str(node_id_str) {
Ok(v) => v,
Err(e) => {
bail!(
@ -432,10 +432,10 @@ impl BootstrapRecord {
envelope_support.dedup();
// Node Id
let mut node_ids = TypedPublicKeyGroup::new();
let mut node_ids = TypedNodeIdGroup::new();
for node_id_str in fields[2].split(',') {
let node_id_str = node_id_str.trim();
let node_id = match TypedPublicKey::from_str(node_id_str) {
let node_id = match TypedNodeId::from_str(node_id_str) {
Ok(v) => v,
Err(e) => {
bail!(

View file

@ -193,7 +193,7 @@ impl Default for NetworkManagerStartupContext {
#[derive(Debug)]
struct NetworkManagerInner {
stats: NetworkManagerStats,
client_allowlist: LruCache<TypedPublicKey, ClientAllowlistEntry>,
client_allowlist: LruCache<TypedNodeId, ClientAllowlistEntry>,
node_contact_method_cache: NodeContactMethodCache,
address_check: Option<AddressCheck>,
peer_info_change_subscription: Option<EventBusSubscription>,
@ -531,7 +531,7 @@ impl NetworkManager {
}
#[expect(dead_code)]
pub fn update_client_allowlist(&self, client: TypedPublicKey) {
pub fn update_client_allowlist(&self, client: TypedNodeId) {
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: TypedPublicKey) -> bool {
pub fn check_client_allowlist(&self, client: TypedNodeId) -> bool {
let mut inner = self.inner.lock();
match inner.client_allowlist.entry(client) {
@ -874,7 +874,7 @@ impl NetworkManager {
#[instrument(level = "trace", target = "net", skip_all)]
fn build_envelope<B: AsRef<[u8]>>(
&self,
dest_node_id: TypedPublicKey,
dest_node_id: TypedNodeId,
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: TypedPublicKeyGroup,
pub node_ids: TypedNodeIdGroup,
pub own_node_info_ts: Timestamp,
pub target_node_info_ts: Timestamp,
pub target_node_ref_filter: NodeRefFilter,

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(
TypedPublicKey::from_str("VLD0:f8G4Ckr1UR8YXnmAllwfvBEvXGgfYicZllb7jEpJeSU")
TypedNodeId::from_str("VLD0:f8G4Ckr1UR8YXnmAllwfvBEvXGgfYicZllb7jEpJeSU")
.expect("should parse key"),
);
let envelope_support = VALID_ENVELOPE_VERSIONS.to_vec();

View file

@ -36,13 +36,14 @@ pub async fn test_signed_node_info() {
)
.unwrap();
let tks: TypedPublicKeyGroup = TypedPublicKey::new(ck, keypair.key).into();
let tks_node_ids = TypedNodeIdGroup::from(tks.clone());
let oldtkslen = tks.len();
let sdni = SignedDirectNodeInfo::new(
node_info.clone(),
sni.timestamp(),
sni.signatures().to_vec(),
);
let tks_validated = sdni.validate(&tks, &crypto).unwrap();
let tks_validated = sdni.validate(&tks_node_ids, &crypto).unwrap();
assert_eq!(tks_validated.len(), oldtkslen);
assert_eq!(tks_validated.len(), sni.signatures().len());
@ -54,7 +55,7 @@ pub async fn test_signed_node_info() {
sni.timestamp(),
sni.signatures().to_vec(),
);
let _ = sdni.validate(&tks1, &crypto).unwrap_err();
let _ = sdni.validate(&tks1.into(), &crypto).unwrap_err();
// Test unsupported cryptosystem validation
let fake_crypto_kind: CryptoKind = FourCC::from([0, 1, 2, 3]);
@ -65,7 +66,7 @@ pub async fn test_signed_node_info() {
tksfake.add(TypedPublicKey::new(ck, keypair.key));
let sdnifake =
SignedDirectNodeInfo::new(node_info.clone(), sni.timestamp(), sigsfake.clone());
let tksfake_validated = sdnifake.validate(&tksfake, &crypto).unwrap();
let tksfake_validated = sdnifake.validate(&tksfake.into(), &crypto).unwrap();
assert_eq!(tksfake_validated.len(), 1);
assert_eq!(sdnifake.signatures().len(), sigsfake.len());
@ -92,18 +93,18 @@ pub async fn test_signed_node_info() {
&crypto,
vec![TypedKeyPair::new(ck, keypair2)],
node_info2.clone(),
tks.clone(),
tks_node_ids.clone(),
sni.clone(),
)
.unwrap();
let srni = SignedRelayedNodeInfo::new(
node_info2.clone(),
tks.clone(),
tks.clone().into(),
sni.clone(),
sni2.timestamp(),
sni2.signatures().to_vec(),
);
let tks2_validated = srni.validate(&tks2, &crypto).unwrap();
let tks2_validated = srni.validate(&tks2.into(), &crypto).unwrap();
assert_eq!(tks2_validated.len(), oldtks2len);
assert_eq!(tks2_validated.len(), sni2.signatures().len());
@ -114,12 +115,12 @@ pub async fn test_signed_node_info() {
let srni = SignedRelayedNodeInfo::new(
node_info2.clone(),
tks.clone(),
tks.clone().into(),
sni.clone(),
sni2.timestamp(),
sni2.signatures().to_vec(),
);
assert_err!(srni.validate(&tks3, &crypto));
assert_err!(srni.validate(&tks3.into(), &crypto));
// Test unsupported cryptosystem validation
let fake_crypto_kind: CryptoKind = FourCC::from([0, 1, 2, 3]);
@ -130,12 +131,12 @@ pub async fn test_signed_node_info() {
tksfake3.add(TypedPublicKey::new(ck, keypair2.key));
let srnifake = SignedRelayedNodeInfo::new(
node_info2.clone(),
tks.clone(),
tks.clone().into(),
sni.clone(),
sni2.timestamp(),
sigsfake3.clone(),
);
let tksfake3_validated = srnifake.validate(&tksfake3, &crypto).unwrap();
let tksfake3_validated = srnifake.validate(&tksfake3.into(), &crypto).unwrap();
assert_eq!(tksfake3_validated.len(), 1);
assert_eq!(srnifake.signatures().len(), sigsfake3.len());
}

View file

@ -12,16 +12,15 @@ pub struct Bucket {
/// Component registryo accessor
registry: VeilidComponentRegistry,
/// Map of keys to entries for this bucket
entries: BTreeMap<PublicKey, Arc<BucketEntry>>,
entries: BTreeMap<NodeId, 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, PublicKey, Arc<BucketEntry>>;
pub(super) type EntriesIter<'a> = alloc::collections::btree_map::Iter<'a, NodeId, Arc<BucketEntry>>;
#[derive(Debug, Serialize, Deserialize)]
struct SerializedBucketEntryData {
key: PublicKey,
key: NodeId,
value: u32, // index into serialized entries list
}
@ -79,14 +78,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: PublicKey) -> Arc<BucketEntry> {
pub(super) fn add_new_entry(&mut self, node_id_key: NodeId) -> Arc<BucketEntry> {
veilid_log!(self trace "Node added: {}:{}", self.kind, node_id_key);
// Add new entry
let entry = Arc::new(BucketEntry::new(TypedPublicKey::new(
self.kind,
node_id_key,
)));
let entry = Arc::new(BucketEntry::new(TypedNodeId::new(self.kind, node_id_key)));
self.entries.insert(node_id_key, entry.clone());
// Return the new entry
@ -94,7 +90,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: PublicKey, entry: Arc<BucketEntry>) {
pub(super) fn add_existing_entry(&mut self, node_id_key: NodeId, entry: Arc<BucketEntry>) {
veilid_log!(self trace "Existing node added: {}:{}", self.kind, node_id_key);
// Add existing entry
@ -102,14 +98,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: &PublicKey) {
pub(super) fn remove_entry(&mut self, node_id_key: &NodeId) {
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: &PublicKey) -> Option<Arc<BucketEntry>> {
pub(super) fn entry(&self, key: &NodeId) -> Option<Arc<BucketEntry>> {
self.entries.get(key).cloned()
}
@ -120,8 +116,8 @@ impl Bucket {
pub(super) fn kick(
&mut self,
bucket_depth: usize,
exempt_peers: &BTreeSet<PublicKey>,
) -> Option<BTreeSet<PublicKey>> {
exempt_peers: &BTreeSet<NodeId>,
) -> Option<BTreeSet<NodeId>> {
// Get number of entries to attempt to purge from bucket
let bucket_len = self.entries.len();
@ -131,11 +127,11 @@ impl Bucket {
}
// Try to purge the newest entries that overflow the bucket
let mut dead_node_ids: BTreeSet<PublicKey> = BTreeSet::new();
let mut dead_node_ids: BTreeSet<NodeId> = 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<(PublicKey, Arc<BucketEntry>)> =
let mut sorted_entries: Vec<(NodeId, 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: TypedPublicKeyGroup,
validated_node_ids: TypedNodeIdGroup,
/// The node ids claimed by the remote node that use cryptography versions we do not support
unsupported_node_ids: TypedPublicKeyGroup,
unsupported_node_ids: TypedNodeIdGroup,
/// 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) -> TypedPublicKeyGroup {
pub fn node_ids(&self) -> TypedNodeIdGroup {
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: TypedPublicKey) -> EyreResult<Option<TypedPublicKey>> {
pub fn add_node_id(&mut self, node_id: TypedNodeId) -> EyreResult<Option<TypedNodeId>> {
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<TypedPublicKey> {
pub fn remove_node_id(&mut self, crypto_kind: CryptoKind) -> Option<TypedNodeId> {
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<TypedPublicKey> {
pub fn best_node_id(&self) -> Option<TypedNodeId> {
self.validated_node_ids.best()
}
@ -1217,14 +1217,14 @@ pub(crate) struct BucketEntry {
}
impl BucketEntry {
pub(super) fn new(first_node_id: TypedPublicKey) -> Self {
pub(super) fn new(first_node_id: TypedNodeId) -> 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: TypedPublicKeyGroup::from(first_node_id),
unsupported_node_ids: TypedPublicKeyGroup::new(),
validated_node_ids: TypedNodeIdGroup::from(first_node_id),
unsupported_node_ids: TypedNodeIdGroup::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<(&PublicKey, &Arc<BucketEntry>)> = inner.buckets[ck][b]
let filtered_entries: Vec<(&NodeId, &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 = TypedPublicKey::new(*ck, node).to_string();
let node_id_str = TypedNodeId::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: TypedPublicKey,
key: TypedNodeId,
capabilities: &[Capability],
) -> NetworkResult<Vec<Arc<PeerInfo>>> {
if Crypto::validate_crypto_kind(key.kind).is_err() {

View file

@ -304,7 +304,7 @@ impl RoutingTable {
///////////////////////////////////////////////////////////////////
pub fn node_id(&self, kind: CryptoKind) -> TypedPublicKey {
pub fn node_id(&self, kind: CryptoKind) -> TypedNodeId {
self.config()
.with(|c| c.network.routing_table.node_id.get(kind).unwrap())
}
@ -315,7 +315,7 @@ impl RoutingTable {
.value
}
pub fn node_ids(&self) -> TypedPublicKeyGroup {
pub fn node_ids(&self) -> TypedNodeIdGroup {
self.config()
.with(|c| c.network.routing_table.node_id.clone())
}
@ -325,13 +325,13 @@ impl RoutingTable {
for ck in VALID_CRYPTO_KINDS {
tkps.push(TypedKeyPair::new(
ck,
KeyPair::new(self.node_id(ck).value, self.node_id_secret_key(ck)),
KeyPair::new(self.node_id(ck).value.into(), self.node_id_secret_key(ck)),
));
}
tkps
}
pub fn matches_own_node_id(&self, node_ids: &[TypedPublicKey]) -> bool {
pub fn matches_own_node_id(&self, node_ids: &[TypedNodeId]) -> 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: &PublicKey) -> bool {
pub fn matches_own_node_id_key(&self, node_id_key: &NodeId) -> 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: &TypedPublicKey) -> BucketIndex {
pub fn calculate_bucket_index(&self, node_id: &TypedNodeId) -> 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();
@ -662,7 +662,7 @@ impl RoutingTable {
.get_nodes_needing_ping(routing_domain, cur_ts)
}
fn queue_bucket_kicks(&self, node_ids: TypedPublicKeyGroup) {
fn queue_bucket_kicks(&self, node_ids: TypedNodeIdGroup) {
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: PublicKey) -> EyreResult<Option<NodeRef>> {
pub fn lookup_any_node_ref(&self, node_id_key: NodeId) -> 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: TypedPublicKey) -> EyreResult<Option<NodeRef>> {
pub fn lookup_node_ref(&self, node_id: TypedNodeId) -> 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: TypedPublicKey,
node_id: TypedNodeId,
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: TypedPublicKey,
node_id: TypedNodeId,
timestamp: Timestamp,
) -> EyreResult<FilteredNodeRef> {
self.inner
@ -739,7 +739,7 @@ impl RoutingTable {
}
#[instrument(level = "trace", skip_all)]
pub fn get_recent_peers(&self) -> Vec<(TypedPublicKey, RecentPeersEntry)> {
pub fn get_recent_peers(&self) -> Vec<(TypedNodeId, RecentPeersEntry)> {
let mut recent_peers = Vec::new();
let mut dead_peers = Vec::new();
let mut out = Vec::new();
@ -963,7 +963,7 @@ impl RoutingTable {
pub async fn find_nodes_close_to_node_id(
&self,
node_ref: FilteredNodeRef,
node_id: TypedPublicKey,
node_id: TypedNodeId,
capabilities: Vec<Capability>,
) -> 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: TypedPublicKey,
node_id: TypedNodeId,
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) -> TypedPublicKeyGroup {
fn node_ids(&self) -> TypedNodeIdGroup {
self.operate(|_rti, e| e.node_ids())
}
fn best_node_id(&self) -> Option<TypedPublicKey> {
fn best_node_id(&self) -> Option<TypedNodeId> {
self.operate(|_rti, e| e.best_node_id())
}

View file

@ -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(PublicKey),
NodeId(NodeId),
/// Route node with full contact method information to ensure the peer is reachable
PeerInfo(Arc<PeerInfo>),
}
@ -47,7 +47,7 @@ impl RouteNode {
match self {
RouteNode::NodeId(id) => {
//
match routing_table.lookup_node_ref(TypedPublicKey::new(crypto_kind, *id)) {
match routing_table.lookup_node_ref(TypedNodeId::new(crypto_kind, *id)) {
Ok(nr) => nr,
Err(e) => {
veilid_log!(routing_table debug "failed to look up route node: {}", e);
@ -71,7 +71,7 @@ impl RouteNode {
pub fn describe(&self, crypto_kind: CryptoKind) -> String {
match self {
RouteNode::NodeId(id) => {
format!("{}", TypedPublicKey::new(crypto_kind, *id))
format!("{}", TypedNodeId::new(crypto_kind, *id))
}
RouteNode::PeerInfo(pi) => match pi.node_ids().get(crypto_kind) {
Some(id) => format!("{}", id),
@ -182,14 +182,14 @@ impl PrivateRoute {
}
}
pub fn first_hop_node_id(&self) -> Option<TypedPublicKey> {
pub fn first_hop_node_id(&self) -> Option<TypedNodeId> {
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) => TypedPublicKey::new(self.public_key.kind, *n),
RouteNode::NodeId(n) => TypedNodeId::new(self.public_key.kind, *n),
RouteNode::PeerInfo(p) => p.node_ids().get(self.public_key.kind).unwrap(),
})
}

View file

@ -166,7 +166,7 @@ impl RouteSpecStore {
crypto_kinds: &[CryptoKind],
safety_spec: &SafetySpec,
directions: DirectionSet,
avoid_nodes: &[TypedPublicKey],
avoid_nodes: &[TypedNodeId],
automatic: bool,
) -> VeilidAPIResult<RouteId> {
let inner = &mut *self.inner.lock();
@ -193,7 +193,7 @@ impl RouteSpecStore {
crypto_kinds: &[CryptoKind],
safety_spec: &SafetySpec,
directions: DirectionSet,
avoid_nodes: &[TypedPublicKey],
avoid_nodes: &[TypedNodeId],
automatic: bool,
) -> VeilidAPIResult<RouteId> {
use core::cmp::Ordering;
@ -655,7 +655,7 @@ impl RouteSpecStore {
for crypto_kind in crypto_kinds.iter().copied() {
let vcrypto = crypto.get(crypto_kind).unwrap();
let keypair = vcrypto.generate_keypair();
let hops: Vec<PublicKey> = route_nodes
let hops: Vec<NodeId> = route_nodes
.iter()
.map(|v| {
nodes[*v]
@ -706,7 +706,7 @@ impl RouteSpecStore {
public_key: &TypedPublicKey,
signatures: &[Signature],
data: &[u8],
last_hop_id: PublicKey,
last_hop_id: NodeId,
callback: F,
) -> Option<R>
where
@ -751,7 +751,7 @@ impl RouteSpecStore {
}
} else {
// Verify a signature for a hop node along the route
match vcrypto.verify(hop_public_key, data, &signatures[hop_n]) {
match vcrypto.verify(&(*hop_public_key).into(), data, &signatures[hop_n]) {
Ok(true) => {}
Ok(false) => {
veilid_log!(self debug "invalid signature for hop {} at {} on private route {}", hop_n, hop_public_key, public_key);
@ -953,7 +953,7 @@ impl RouteSpecStore {
stability: Stability,
sequencing: Sequencing,
directions: DirectionSet,
avoid_nodes: &[TypedPublicKey],
avoid_nodes: &[TypedNodeId],
) -> Option<RouteId> {
let cur_ts = Timestamp::now();
@ -1110,7 +1110,7 @@ impl RouteSpecStore {
let opt_first_hop = match pr_first_hop_node {
RouteNode::NodeId(id) => rti
.lookup_node_ref(TypedPublicKey::new(crypto_kind, id))
.lookup_node_ref(TypedNodeId::new(crypto_kind, id))
.map_err(VeilidAPIError::internal)?,
RouteNode::PeerInfo(pi) => Some(
rti.register_node_with_peer_info(pi, false)
@ -1135,7 +1135,7 @@ impl RouteSpecStore {
//veilid_log!(self info "compile_safety_route profile (stub): {} us", (get_timestamp() - profile_start_ts));
return Ok(CompiledRoute {
safety_route: SafetyRoute::new_stub(
routing_table.node_id(crypto_kind),
routing_table.node_id(crypto_kind).into(),
private_route,
),
secret: routing_table.node_id_secret_key(crypto_kind),
@ -1238,7 +1238,7 @@ impl RouteSpecStore {
blob_data = {
// Encrypt the previous blob ENC(nonce, DH(PKhop,SKsr))
let dh_secret = vcrypto
.cached_dh(&safety_rsd.hops[h], &safety_rsd.secret_key)
.cached_dh(&safety_rsd.hops[h].into(), &safety_rsd.secret_key)
.map_err(VeilidAPIError::internal)?;
let enc_msg_data = vcrypto
.encrypt_aead(blob_data.as_slice(), &nonce, &dh_secret, None)
@ -1258,7 +1258,7 @@ impl RouteSpecStore {
} else {
// Full peer info, required until we are sure the route has been fully established
let node_id =
TypedPublicKey::new(safety_rsd.crypto_kind, safety_rsd.hops[h]);
TypedNodeId::new(safety_rsd.crypto_kind, safety_rsd.hops[h]);
let pi = rti
.with_node_entry(node_id, |entry| {
entry.with(rti, |_rti, e| {
@ -1291,7 +1291,7 @@ impl RouteSpecStore {
// Encode first RouteHopData
let dh_secret = vcrypto
.cached_dh(&safety_rsd.hops[0], &safety_rsd.secret_key)
.cached_dh(&safety_rsd.hops[0].into(), &safety_rsd.secret_key)
.map_err(VeilidAPIError::internal)?;
let enc_msg_data = vcrypto
.encrypt_aead(blob_data.as_slice(), &nonce, &dh_secret, None)
@ -1340,7 +1340,7 @@ impl RouteSpecStore {
crypto_kind: CryptoKind,
safety_spec: &SafetySpec,
direction: DirectionSet,
avoid_nodes: &[TypedPublicKey],
avoid_nodes: &[TypedNodeId],
) -> VeilidAPIResult<PublicKey> {
// Ensure the total hop count isn't too long for our config
let max_route_hop_count = self.max_route_hop_count;
@ -1416,7 +1416,7 @@ impl RouteSpecStore {
&self,
crypto_kind: CryptoKind,
safety_spec: &SafetySpec,
avoid_nodes: &[TypedPublicKey],
avoid_nodes: &[TypedNodeId],
) -> VeilidAPIResult<PublicKey> {
let inner = &mut *self.inner.lock();
let routing_table = self.routing_table();
@ -1488,7 +1488,7 @@ impl RouteSpecStore {
};
// Encrypt the previous blob ENC(nonce, DH(PKhop,SKpr))
let dh_secret = vcrypto.cached_dh(&rsd.hops[h], &rsd.secret_key)?;
let dh_secret = vcrypto.cached_dh(&rsd.hops[h].into(), &rsd.secret_key)?;
let enc_msg_data =
vcrypto.encrypt_aead(blob_data.as_slice(), &nonce, &dh_secret, None)?;
let route_hop_data = RouteHopData {
@ -1502,7 +1502,7 @@ impl RouteSpecStore {
RouteNode::NodeId(rsd.hops[h])
} else {
// Full peer info, required until we are sure the route has been fully established
let node_id = TypedPublicKey::new(rsd.crypto_kind, rsd.hops[h]);
let node_id = TypedNodeId::new(rsd.crypto_kind, rsd.hops[h]);
let pi = rti
.with_node_entry(node_id, |entry| {
entry.with(rti, |_rti, e| {
@ -1536,7 +1536,7 @@ impl RouteSpecStore {
key: &PublicKey,
optimized: Option<bool>,
) -> VeilidAPIResult<PrivateRoute> {
let inner = &*self.inner.lock();
let inner: &RouteSpecStoreInner = &self.inner.lock();
let Some(rsid) = inner.content.get_id_by_key(key) else {
// Route doesn't exist
apibail_invalid_target!("route id does not exist");
@ -1747,7 +1747,7 @@ impl RouteSpecStore {
let inner = &mut *self.inner.lock();
// Check for stub route
if self.routing_table().matches_own_node_id_key(key) {
if self.routing_table().matches_own_node_id_key(&(*key).into()) {
return None;
}

View file

@ -7,7 +7,7 @@ pub struct RouteSpecDetail {
/// Secret key
pub secret_key: SecretKey,
/// Route hops (node id keys)
pub hops: Vec<PublicKey>,
pub hops: Vec<NodeId>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
@ -109,7 +109,7 @@ impl RouteSetSpecDetail {
Sequencing::EnsureOrdered => self.can_do_sequenced,
}
}
pub fn contains_nodes(&self, nodes: &[TypedPublicKey]) -> bool {
pub fn contains_nodes(&self, nodes: &[TypedNodeId]) -> 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

@ -26,14 +26,14 @@ pub struct RouteSpecStoreCache {
/// Registry accessor
registry: VeilidComponentRegistry,
/// How many times nodes have been used
used_nodes: HashMap<PublicKey, usize>,
used_nodes: HashMap<NodeId, usize>,
/// How many times nodes have been used at the terminal point of a route
used_end_nodes: HashMap<PublicKey, usize>,
used_end_nodes: HashMap<NodeId, 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 routes indexed by public key
/// Remote private route ids indexed by route's public key
remote_private_routes_by_key: HashMap<PublicKey, RouteId>,
/// Compiled route cache
compiled_route_cache: LruCache<CompiledRouteCacheKey, SafetyRoute>,
@ -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: &TypedPublicKeyGroup) -> usize {
pub fn get_used_node_count(&self, node_ids: &TypedNodeIdGroup) -> 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: &TypedPublicKeyGroup) -> usize {
pub fn get_used_end_node_count(&self, node_ids: &TypedNodeIdGroup) -> usize {
node_ids.iter().fold(0usize, |acc, k| {
acc + self
.used_end_nodes

View file

@ -35,7 +35,7 @@ impl RouteSpecStoreContent {
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(TypedPublicKey::new(rsd.crypto_kind, *h))
routing_table.lookup_node_ref(TypedNodeId::new(rsd.crypto_kind, *h))
else {
dead_ids.push(*rsid);
break;

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<TypedPublicKey, RecentPeersEntry>,
pub(super) recent_peers: LruCache<TypedNodeId, 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<PublicKey>) {
pub fn kick_bucket(&mut self, bucket_index: BucketIndex, exempt_peers: &BTreeSet<NodeId>) {
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: &[TypedPublicKey],
node_ids: &[TypedNodeId],
) -> EyreResult<()> {
let routing_table = self.routing_table();
@ -745,7 +745,7 @@ impl RoutingTableInner {
#[instrument(level = "trace", skip_all, err)]
fn create_node_ref<F>(
&mut self,
node_ids: &TypedPublicKeyGroup,
node_ids: &TypedNodeIdGroup,
update_func: F,
) -> EyreResult<NodeRef>
where
@ -825,9 +825,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: PublicKey) -> EyreResult<Option<NodeRef>> {
pub fn lookup_any_node_ref(&self, node_id_key: NodeId) -> EyreResult<Option<NodeRef>> {
for ck in VALID_CRYPTO_KINDS {
if let Some(nr) = self.lookup_node_ref(TypedPublicKey::new(ck, node_id_key))? {
if let Some(nr) = self.lookup_node_ref(TypedNodeId::new(ck, node_id_key))? {
return Ok(Some(nr));
}
}
@ -836,7 +836,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: TypedPublicKey) -> EyreResult<Option<NodeRef>> {
pub fn lookup_node_ref(&self, node_id: TypedNodeId) -> EyreResult<Option<NodeRef>> {
if self.routing_table().matches_own_node_id(&[node_id]) {
bail!("can't look up own node id in routing table");
}
@ -855,7 +855,7 @@ impl RoutingTableInner {
#[instrument(level = "trace", skip_all, err)]
pub fn lookup_and_filter_noderef(
&self,
node_id: TypedPublicKey,
node_id: TypedNodeId,
routing_domain_set: RoutingDomainSet,
dial_info_filter: DialInfoFilter,
) -> EyreResult<Option<FilteredNodeRef>> {
@ -870,7 +870,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: TypedPublicKey, f: F) -> Option<R>
pub fn with_node_entry<F, R>(&self, node_id: TypedNodeId, f: F) -> Option<R>
where
F: FnOnce(Arc<BucketEntry>) -> R,
{
@ -970,10 +970,10 @@ impl RoutingTableInner {
pub fn register_node_with_id(
&mut self,
routing_domain: RoutingDomain,
node_id: TypedPublicKey,
node_id: TypedNodeId,
timestamp: Timestamp,
) -> EyreResult<FilteredNodeRef> {
let nr = self.create_node_ref(&TypedPublicKeyGroup::from(node_id), |_rti, e| {
let nr = self.create_node_ref(&TypedNodeIdGroup::from(node_id), |_rti, e| {
//e.make_not_dead(timestamp);
e.touch_last_seen(timestamp);
})?;
@ -1091,7 +1091,7 @@ impl RoutingTableInner {
}
}
pub fn touch_recent_peer(&mut self, node_id: TypedPublicKey, last_connection: Flow) {
pub fn touch_recent_peer(&mut self, node_id: TypedNodeId, last_connection: Flow) {
self.recent_peers
.insert(node_id, RecentPeersEntry { last_connection });
}
@ -1525,7 +1525,7 @@ impl RoutingTableInner {
#[instrument(level = "trace", skip(self, filter, metric), ret)]
pub fn get_node_relative_performance(
&self,
node_id: TypedPublicKey,
node_id: TypedNodeId,
cur_ts: Timestamp,
filter: impl Fn(&BucketEntryInner) -> bool,
metric: impl Fn(&LatencyStats) -> TimestampDuration,
@ -1615,13 +1615,13 @@ pub fn make_closest_noderef_sort<'a>(
pub fn make_closest_node_id_sort(
crypto: &Crypto,
node_id: TypedPublicKey,
) -> impl Fn(&PublicKey, &PublicKey) -> core::cmp::Ordering + '_ {
node_id: TypedNodeId,
) -> impl Fn(&NodeId, &NodeId) -> core::cmp::Ordering + '_ {
let kind = node_id.kind;
// Get cryptoversion to check distance with
let vcrypto = crypto.get(kind).unwrap();
move |a: &PublicKey, b: &PublicKey| -> core::cmp::Ordering {
move |a: &NodeId, b: &NodeId| -> 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));

View file

@ -62,7 +62,7 @@ impl RoutingTable {
}));
}
let mut bootstrapped_peer_id_set = HashSet::<TypedPublicKey>::new();
let mut bootstrapped_peer_id_set = HashSet::<TypedNodeId>::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<PublicKey>>::new();
let mut exempt_peers_by_kind = BTreeMap::<CryptoKind, BTreeSet<NodeId>>::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::<PublicKey>::new();
let mut closest_peers = BTreeSet::<NodeId>::new();
let mut closest_unreliable_count = 0usize;
let mut closest_reliable_count = 0usize;

View file

@ -68,7 +68,7 @@ pub fn test_round_trip_peerinfo() {
));
let pi: PeerInfo = PeerInfo::new(
RoutingDomain::PublicInternet,
tks,
tks.into(),
SignedNodeInfo::Direct(SignedDirectNodeInfo::new(
NodeInfo::new(
NetworkClass::OutboundOnly,

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(TypedPublicKey, TypedPublicKey),
SignalReverse(TypedNodeId, TypedNodeId),
/// Request via signal the node negotiate a hole punch (relay, target)
SignalHolePunch(TypedPublicKey, TypedPublicKey),
SignalHolePunch(TypedNodeId, TypedNodeId),
/// Must use an inbound relay to reach the node
InboundRelay(TypedPublicKey),
InboundRelay(TypedNodeId),
/// Must use outbound relay to reach the node
OutboundRelay(TypedPublicKey),
OutboundRelay(TypedNodeId),
}

View file

@ -7,7 +7,7 @@ pub struct PeerInfo {
skip_serializing_if = "is_default_routing_domain"
)]
routing_domain: RoutingDomain,
node_ids: TypedPublicKeyGroup,
node_ids: TypedNodeIdGroup,
signed_node_info: SignedNodeInfo,
}
@ -32,7 +32,7 @@ impl fmt::Display for PeerInfo {
impl PeerInfo {
pub fn new(
routing_domain: RoutingDomain,
node_ids: TypedPublicKeyGroup,
node_ids: TypedNodeIdGroup,
signed_node_info: SignedNodeInfo,
) -> Self {
assert!(!node_ids.is_empty() && node_ids.len() <= MAX_CRYPTO_KINDS);
@ -55,13 +55,13 @@ impl PeerInfo {
pub fn routing_domain(&self) -> RoutingDomain {
self.routing_domain
}
pub fn node_ids(&self) -> &TypedPublicKeyGroup {
pub fn node_ids(&self) -> &TypedNodeIdGroup {
&self.node_ids
}
pub fn signed_node_info(&self) -> &SignedNodeInfo {
&self.signed_node_info
}
pub fn destructure(self) -> (RoutingDomain, TypedPublicKeyGroup, SignedNodeInfo) {
pub fn destructure(self) -> (RoutingDomain, TypedNodeIdGroup, SignedNodeInfo) {
(self.routing_domain, self.node_ids, self.signed_node_info)
}

View file

@ -35,14 +35,15 @@ impl SignedDirectNodeInfo {
pub fn validate(
&self,
node_ids: &TypedPublicKeyGroup,
node_ids: &TypedNodeIdGroup,
crypto: &Crypto,
) -> VeilidAPIResult<TypedPublicKeyGroup> {
) -> VeilidAPIResult<TypedNodeIdGroup> {
let node_info_bytes = Self::make_signature_bytes(&self.node_info, self.timestamp)?;
let public_keys = TypedPublicKeyGroup::from(node_ids.clone());
// Verify the signatures that we can
let opt_validated_node_ids =
crypto.verify_signatures(node_ids, &node_info_bytes, &self.signatures)?;
crypto.verify_signatures(&public_keys, &node_info_bytes, &self.signatures)?;
let Some(validated_node_ids) = opt_validated_node_ids else {
apibail_generic!("verification error in direct node info");
};
@ -50,7 +51,7 @@ impl SignedDirectNodeInfo {
apibail_generic!("no valid node ids in direct node info");
}
Ok(validated_node_ids)
Ok(validated_node_ids.into())
}
pub fn make_signatures(

View file

@ -26,9 +26,9 @@ impl fmt::Display for SignedNodeInfo {
impl SignedNodeInfo {
pub fn validate(
&self,
node_ids: &TypedPublicKeyGroup,
node_ids: &TypedNodeIdGroup,
crypto: &Crypto,
) -> VeilidAPIResult<TypedPublicKeyGroup> {
) -> VeilidAPIResult<TypedNodeIdGroup> {
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) -> TypedPublicKeyGroup {
pub fn relay_ids(&self) -> TypedNodeIdGroup {
match self {
SignedNodeInfo::Direct(_) => TypedPublicKeyGroup::new(),
SignedNodeInfo::Direct(_) => TypedNodeIdGroup::new(),
SignedNodeInfo::Relayed(r) => r.relay_ids().clone(),
}
}

View file

@ -4,7 +4,7 @@ use super::*;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SignedRelayedNodeInfo {
node_info: NodeInfo,
relay_ids: TypedPublicKeyGroup,
relay_ids: TypedNodeIdGroup,
relay_info: SignedDirectNodeInfo,
timestamp: Timestamp,
signatures: Vec<TypedSignature>,
@ -32,7 +32,7 @@ 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: TypedPublicKeyGroup,
relay_ids: TypedNodeIdGroup,
relay_info: SignedDirectNodeInfo,
timestamp: Timestamp,
signatures: Vec<TypedSignature>,
@ -48,9 +48,9 @@ impl SignedRelayedNodeInfo {
pub fn validate(
&self,
node_ids: &TypedPublicKeyGroup,
node_ids: &TypedNodeIdGroup,
crypto: &Crypto,
) -> VeilidAPIResult<TypedPublicKeyGroup> {
) -> VeilidAPIResult<TypedNodeIdGroup> {
// 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,22 +69,23 @@ impl SignedRelayedNodeInfo {
&self.relay_info,
self.timestamp,
)?;
let public_keys = TypedPublicKeyGroup::from(node_ids.clone());
let opt_validated_node_ids =
crypto.verify_signatures(node_ids, &node_info_bytes, &self.signatures)?;
crypto.verify_signatures(&public_keys, &node_info_bytes, &self.signatures)?;
let Some(validated_node_ids) = opt_validated_node_ids else {
apibail_generic!("verification error in relayed node info");
};
if validated_node_ids.is_empty() {
apibail_generic!("no valid node ids in relayed node info");
}
Ok(validated_node_ids)
Ok(TypedNodeIdGroup::from(validated_node_ids))
}
pub fn make_signatures(
crypto: &Crypto,
typed_key_pairs: Vec<TypedKeyPair>,
node_info: NodeInfo,
relay_ids: TypedPublicKeyGroup,
relay_ids: TypedNodeIdGroup,
relay_info: SignedDirectNodeInfo,
) -> VeilidAPIResult<Self> {
let timestamp = Timestamp::now();
@ -105,7 +106,7 @@ impl SignedRelayedNodeInfo {
fn make_signature_bytes(
node_info: &NodeInfo,
relay_ids: &[TypedPublicKey],
relay_ids: &[TypedNodeId],
relay_info: &SignedDirectNodeInfo,
timestamp: Timestamp,
) -> VeilidAPIResult<Vec<u8>> {
@ -121,7 +122,7 @@ impl SignedRelayedNodeInfo {
for relay_id in relay_ids {
let mut rid_msg = ::capnp::message::Builder::new_default();
let mut rid_builder = rid_msg.init_root::<veilid_capnp::typed_key::Builder>();
encode_typed_key(relay_id, &mut rid_builder);
encode_typed_node_id(relay_id, &mut rid_builder);
sig_bytes.append(&mut builder_to_vec(rid_msg).map_err(VeilidAPIError::internal)?);
}
@ -148,7 +149,7 @@ impl SignedRelayedNodeInfo {
pub fn timestamp(&self) -> Timestamp {
self.timestamp
}
pub fn relay_ids(&self) -> &TypedPublicKeyGroup {
pub fn relay_ids(&self) -> &TypedNodeIdGroup {
&self.relay_ids
}
pub fn relay_info(&self) -> &SignedDirectNodeInfo {

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: TypedPublicKey,
node_id: TypedNodeId,
capabilities: Vec<Capability>,
}
impl RPCOperationFindNodeQ {
pub fn new(node_id: TypedPublicKey, capabilities: Vec<Capability>) -> Self {
pub fn new(node_id: TypedNodeId, capabilities: Vec<Capability>) -> Self {
Self {
node_id,
capabilities,
@ -26,7 +26,7 @@ impl RPCOperationFindNodeQ {
// &self.capabilities
// }
pub fn destructure(self) -> (TypedPublicKey, Vec<Capability>) {
pub fn destructure(self) -> (TypedNodeId, Vec<Capability>) {
(self.node_id, self.capabilities)
}
@ -35,7 +35,7 @@ impl RPCOperationFindNodeQ {
reader: &veilid_capnp::operation_find_node_q::Reader,
) -> Result<Self, RPCError> {
let ni_reader = reader.get_node_id().map_err(RPCError::protocol)?;
let node_id = decode_typed_key(&ni_reader)?;
let node_id = decode_typed_node_id(&ni_reader)?;
let cap_reader = reader
.reborrow()
.get_capabilities()
@ -58,7 +58,7 @@ impl RPCOperationFindNodeQ {
builder: &mut veilid_capnp::operation_find_node_q::Builder,
) -> Result<(), RPCError> {
let mut ni_builder = builder.reborrow().init_node_id();
encode_typed_key(&self.node_id, &mut ni_builder);
encode_typed_node_id(&self.node_id, &mut ni_builder);
let mut cap_builder = builder
.reborrow()

View file

@ -13,7 +13,7 @@ pub fn encode_peer_info(
.map_err(RPCError::map_invalid_format("out of bound error"))?,
);
for (i, nid) in peer_info.node_ids().iter().enumerate() {
encode_typed_key(
encode_typed_node_id(
nid,
&mut nids_builder.reborrow().get(
i.try_into()
@ -39,9 +39,9 @@ pub fn decode_peer_info(
.reborrow()
.get_signed_node_info()
.map_err(RPCError::protocol)?;
let mut node_ids = TypedPublicKeyGroup::with_capacity(nids_reader.len() as usize);
let mut node_ids = TypedNodeIdGroup::with_capacity(nids_reader.len() as usize);
for nid_reader in nids_reader.iter() {
node_ids.add(decode_typed_key(&nid_reader)?);
node_ids.add(decode_typed_node_id(&nid_reader)?);
}
let signed_node_info = decode_signed_node_info(&sni_reader)?;
if node_ids.is_empty() {

View file

@ -53,7 +53,7 @@ pub fn encode_route_hop(
match &route_hop.node {
RouteNode::NodeId(ni) => {
let mut ni_builder = node_builder.init_node_id();
encode_key256(ni, &mut ni_builder);
encode_key256(&(*ni).into(), &mut ni_builder);
}
RouteNode::PeerInfo(pi) => {
let mut pi_builder = node_builder.init_peer_info();
@ -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))
RouteNode::NodeId(decode_key256(&ni_reader).into())
}
veilid_capnp::route_hop::node::Which::PeerInfo(pi) => {
let pi_reader = pi.map_err(RPCError::protocol)?;
@ -104,7 +104,7 @@ pub fn encode_private_route(
private_route: &PrivateRoute,
builder: &mut veilid_capnp::private_route::Builder,
) -> Result<(), RPCError> {
encode_typed_key(
encode_typed_public_key(
&private_route.public_key,
&mut builder.reborrow().init_public_key(),
);
@ -130,7 +130,7 @@ pub fn decode_private_route(
decode_context: &RPCDecodeContext,
reader: &veilid_capnp::private_route::Reader,
) -> Result<PrivateRoute, RPCError> {
let public_key = decode_typed_key(&reader.get_public_key().map_err(
let public_key = decode_typed_public_key(&reader.get_public_key().map_err(
RPCError::map_protocol("invalid public key in private route"),
)?)?;
let hop_count = reader.get_hop_count();
@ -160,7 +160,7 @@ pub fn encode_safety_route(
safety_route: &SafetyRoute,
builder: &mut veilid_capnp::safety_route::Builder,
) -> Result<(), RPCError> {
encode_typed_key(
encode_typed_public_key(
&safety_route.public_key,
&mut builder.reborrow().init_public_key(),
);
@ -184,7 +184,7 @@ pub fn decode_safety_route(
decode_context: &RPCDecodeContext,
reader: &veilid_capnp::safety_route::Reader,
) -> Result<SafetyRoute, RPCError> {
let public_key = decode_typed_key(
let public_key = decode_typed_public_key(
&reader
.get_public_key()
.map_err(RPCError::map_protocol("invalid public key in safety route"))?,

View file

@ -16,7 +16,7 @@ pub fn encode_signed_relayed_node_info(
.map_err(RPCError::map_invalid_format("out of bound error"))?,
);
for (i, typed_key) in signed_relayed_node_info.relay_ids().iter().enumerate() {
encode_typed_key(
encode_typed_node_id(
typed_key,
&mut rids_builder.reborrow().get(
i.try_into()
@ -69,9 +69,9 @@ 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 = TypedPublicKeyGroup::with_capacity(rid_count);
let mut relay_ids = TypedNodeIdGroup::with_capacity(rid_count);
for rid_reader in rids_reader {
let relay_id = decode_typed_key(&rid_reader)?;
let relay_id = decode_typed_node_id(&rid_reader)?;
relay_ids.add(relay_id);
}

View file

@ -1,6 +1,6 @@
use super::*;
pub fn decode_typed_key(
pub fn decode_typed_public_key(
typed_key: &veilid_capnp::typed_key::Reader,
) -> Result<TypedPublicKey, RPCError> {
let key_reader = typed_key
@ -14,7 +14,7 @@ pub fn decode_typed_key(
))
}
pub fn encode_typed_key(
pub fn encode_typed_public_key(
typed_key: &TypedPublicKey,
builder: &mut veilid_capnp::typed_key::Builder,
) {
@ -23,6 +23,29 @@ pub fn encode_typed_key(
encode_key256(&typed_key.value, &mut key_builder);
}
pub fn decode_typed_node_id(
typed_key: &veilid_capnp::typed_key::Reader,
) -> Result<TypedNodeId, 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(
CryptoKind::from(kind.to_be_bytes()),
NodeId::new(decode_key256(&key_reader).bytes),
))
}
pub fn encode_typed_node_id(
typed_key: &TypedNodeId,
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);
}
pub fn decode_typed_record_key(
typed_key: &veilid_capnp::typed_key::Reader,
) -> Result<TypedRecordKey, RPCError> {

View file

@ -107,7 +107,7 @@ impl Destination {
}
}
pub fn get_target_node_ids(&self) -> Option<TypedPublicKeyGroup> {
pub fn get_target_node_ids(&self) -> Option<TypedNodeIdGroup> {
match self {
Destination::Direct {
node,
@ -429,7 +429,10 @@ impl RPCProcessor {
};
Ok(NetworkResult::value(RespondTo::PrivateRoute(
PrivateRoute::new_stub(routing_table.node_id(crypto_kind), route_node),
PrivateRoute::new_stub(
routing_table.node_id(crypto_kind).into(),
route_node,
),
)))
}
SafetySelection::Safe(safety_spec) => {

View file

@ -112,7 +112,7 @@ pub enum FanoutCallDisposition {
}
pub type FanoutCallResult = Result<FanoutCallOutput, RPCError>;
pub type FanoutNodeInfoFilter = Arc<dyn (Fn(&[TypedPublicKey], &NodeInfo) -> bool) + Send + Sync>;
pub type FanoutNodeInfoFilter = Arc<dyn (Fn(&[TypedNodeId], &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>;
@ -421,9 +421,7 @@ impl<'a> FanoutCall<'a> {
));
};
let node_sort = Box::new(
|a_key: &CryptoTyped<PublicKey>,
b_key: &CryptoTyped<PublicKey>|
-> core::cmp::Ordering {
|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 =

View file

@ -33,7 +33,7 @@ pub struct FanoutNode {
}
pub type FanoutQueueSort<'a> =
Box<dyn Fn(&TypedPublicKey, &TypedPublicKey) -> core::cmp::Ordering + Send + 'a>;
Box<dyn Fn(&TypedNodeId, &TypedNodeId) -> core::cmp::Ordering + Send + 'a>;
pub struct FanoutQueue<'a> {
/// Link back to veilid component registry for logging
@ -41,9 +41,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<TypedPublicKey, FanoutNode>,
nodes: HashMap<TypedNodeId, FanoutNode>,
/// Closer nodes to the record key are at the front of the list
sorted_nodes: Vec<TypedPublicKey>,
sorted_nodes: Vec<TypedNodeId>,
/// The sort function to use for the nodes
node_sort: FanoutQueueSort<'a>,
/// The channel to receive work requests to process
@ -265,10 +265,7 @@ impl<'a> FanoutQueue<'a> {
}
/// Review the nodes in the queue
pub fn with_nodes<
R,
F: FnOnce(&HashMap<TypedPublicKey, FanoutNode>, &[TypedPublicKey]) -> R,
>(
pub fn with_nodes<R, F: FnOnce(&HashMap<TypedNodeId, FanoutNode>, &[TypedNodeId]) -> R>(
&self,
func: F,
) -> R {

View file

@ -72,7 +72,7 @@ impl MessageHeader {
RPCMessageHeaderDetail::PrivateRouted(p) => p.direct.routing_domain,
}
}
pub fn direct_sender_node_id(&self) -> TypedPublicKey {
pub fn direct_sender_node_id(&self) -> TypedNodeId {
match &self.detail {
RPCMessageHeaderDetail::Direct(d) => d.envelope.get_sender_typed_id(),
RPCMessageHeaderDetail::SafetyRouted(s) => s.direct.envelope.get_sender_typed_id(),

View file

@ -42,7 +42,7 @@ mod rpc_start_tunnel;
pub(crate) use answer::*;
pub(crate) use coders::{
builder_to_vec, decode_private_route, encode_node_info, encode_private_route, encode_route_hop,
encode_signed_direct_node_info, encode_typed_key, RPCDecodeContext,
encode_signed_direct_node_info, encode_typed_node_id, RPCDecodeContext,
MAX_INSPECT_VALUE_A_SEQS_LEN,
};
pub(crate) use destination::*;
@ -303,7 +303,7 @@ impl RPCProcessor {
fn process_sender_peer_info(
&self,
routing_domain: RoutingDomain,
sender_node_id: TypedPublicKey,
sender_node_id: TypedNodeId,
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: TypedPublicKey,
node_id: TypedNodeId,
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: TypedPublicKey,
node_id: TypedNodeId,
safety_selection: SafetySelection,
) -> PinBoxFuture<Result<Option<NodeRef>, RPCError>> {
let registry = self.registry();
@ -575,7 +575,7 @@ impl RPCProcessor {
let node_id = self
.routing_table()
.node_id(sr.direct.envelope.get_crypto_kind());
if node_id.value != reply_private_route {
if node_id.value != reply_private_route.into() {
return Err(RPCError::protocol(
"should have received reply from safety route to a stub",
));
@ -773,7 +773,7 @@ impl RPCProcessor {
};
let private_route = PrivateRoute::new_stub(
match destination_node_ref.best_node_id() {
Some(nid) => nid,
Some(nid) => nid.into(),
None => {
return Ok(NetworkResult::no_connection_other(
"No best node id for stub private route",

View file

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

View file

@ -242,7 +242,7 @@ impl RPCProcessor {
) -> 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
if self.routing_table().node_ids().contains(&pr_pubkey) {
if self.routing_table().node_ids().contains(&pr_pubkey.into()) {
// The private route was a stub
self.process_safety_routed_operation(
detail,
@ -384,7 +384,11 @@ impl RPCProcessor {
let node_id = self.routing_table().node_id(crypto_kind);
let node_id_secret = self.routing_table().node_id_secret_key(crypto_kind);
let sig = vcrypto
.sign(&node_id.value, &node_id_secret, routed_operation.data())
.sign(
&node_id.value.into(),
&node_id_secret,
routed_operation.data(),
)
.map_err(RPCError::internal)?;
routed_operation.add_signature(sig);
}

View file

@ -62,9 +62,10 @@ impl RPCProcessor {
"not processing value change over safety route",
));
}
RPCMessageHeaderDetail::PrivateRouted(p) => {
TypedPublicKey::new(p.direct.envelope.get_crypto_kind(), p.remote_safety_route)
}
RPCMessageHeaderDetail::PrivateRouted(p) => TypedNodeId::new(
p.direct.envelope.get_crypto_kind(),
p.remote_safety_route.into(),
),
};
if debug_target_enabled!("dht") {

View file

@ -1343,7 +1343,7 @@ impl StorageManager {
let config = self.config();
let cfg = config.get();
if let Some(node_id) = cfg.network.routing_table.node_id.get(kind) {
if schema.is_member(&node_id.value) {
if schema.is_member(&node_id.value.into()) {
apibail_invalid_argument!(
"node id can not be schema member",
"schema",
@ -1602,7 +1602,7 @@ impl StorageManager {
.copied()
.filter_map(|x| {
routing_table
.lookup_node_ref(TypedPublicKey::new(record_key.kind, x))
.lookup_node_ref(TypedNodeId::new(record_key.kind, x))
.ok()
.flatten()
})

View file

@ -7,7 +7,7 @@ pub(in crate::storage_manager) struct PerNodeKey {
/// Watched record key
pub record_key: TypedRecordKey,
/// Watching node id
pub node_id: TypedPublicKey,
pub node_id: TypedNodeId,
}
impl fmt::Display for PerNodeKey {
@ -24,7 +24,7 @@ impl FromStr for PerNodeKey {
.ok_or_else(|| VeilidAPIError::parse_error("invalid per-node key", s))?;
Ok(PerNodeKey {
record_key: TypedRecordKey::from_str(rkey)?,
node_id: TypedPublicKey::from_str(nid)?,
node_id: TypedNodeId::from_str(nid)?,
})
}
}

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<PublicKey, PerNodeRecordDetail>,
pub nodes: HashMap<NodeId, PerNodeRecordDetail>,
}
impl LocalRecordDetail {

View file

@ -1059,7 +1059,7 @@ impl StorageManager {
mut subkeys: ValueSubkeyRangeSet,
count: u32,
value: Option<Arc<SignedValueData>>,
inbound_node_id: TypedPublicKey,
inbound_node_id: TypedNodeId,
watch_id: u64,
) -> VeilidAPIResult<NetworkResult<()>> {
// Operate on the watch for this record

View file

@ -204,7 +204,7 @@ pub fn config_callback(key: String) -> ConfigCallbackReturn {
"network.reverse_connection_receipt_time_ms" => Ok(Box::new(5_000u32)),
"network.hole_punch_receipt_time_ms" => Ok(Box::new(5_000u32)),
"network.network_key_password" => Ok(Box::new(Option::<String>::None)),
"network.routing_table.node_id" => Ok(Box::new(TypedPublicKeyGroup::new())),
"network.routing_table.node_id" => Ok(Box::new(TypedNodeIdGroup::new())),
"network.routing_table.node_id_secret" => Ok(Box::new(TypedSecretKeyGroup::new())),
// "network.routing_table.bootstrap" => Ok(Box::new(Vec::<String>::new())),
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]

View file

@ -246,7 +246,7 @@ impl VeilidAPI {
}
// Is this a node id?
if let Ok(nid) = TypedPublicKey::from_str(&s) {
if let Ok(nid) = TypedNodeId::from_str(&s) {
return Ok(Target::NodeId(nid));
}

View file

@ -228,14 +228,14 @@ fn get_number<T: num_traits::Num + FromStr>(text: &str) -> Option<T> {
T::from_str(text).ok()
}
fn get_typed_key(text: &str) -> Option<TypedPublicKey> {
TypedPublicKey::from_str(text).ok()
}
fn get_typed_record_key(text: &str) -> Option<TypedRecordKey> {
TypedRecordKey::from_str(text).ok()
}
fn get_public_key(text: &str) -> Option<PublicKey> {
PublicKey::from_str(text).ok()
fn get_node_id(text: &str) -> Option<NodeId> {
NodeId::from_str(text).ok()
}
fn get_typed_node_id(text: &str) -> Option<TypedNodeId> {
TypedNodeId::from_str(text).ok()
}
fn get_record_key(text: &str) -> Option<RecordKey> {
RecordKey::from_str(text).ok()
@ -303,15 +303,15 @@ fn resolve_node_ref(
move |text| {
let text = text.to_owned();
Box::pin(async move {
let nr = if let Some(key) = get_public_key(&text) {
let node_id = TypedPublicKey::new(best_crypto_kind(), key);
let nr = if let Some(key) = get_node_id(&text) {
let node_id = TypedNodeId::new(best_crypto_kind(), key);
registry
.rpc_processor()
.resolve_node(node_id, safety_selection)
.await
.ok()
.flatten()?
} else if let Some(node_id) = get_typed_key(&text) {
} else if let Some(node_id) = get_typed_node_id(&text) {
registry
.rpc_processor()
.resolve_node(node_id, safety_selection)
@ -338,15 +338,15 @@ fn resolve_filtered_node_ref(
.map(|x| (x.0, Some(x.1)))
.unwrap_or((&text, None));
let nr = if let Some(key) = get_public_key(text) {
let node_id = TypedPublicKey::new(best_crypto_kind(), key);
let nr = if let Some(key) = get_node_id(text) {
let node_id = TypedNodeId::new(best_crypto_kind(), key);
registry
.rpc_processor()
.resolve_node(node_id, safety_selection)
.await
.ok()
.flatten()?
} else if let Some(node_id) = get_typed_key(text) {
} else if let Some(node_id) = get_typed_node_id(text) {
registry
.rpc_processor()
.resolve_node(node_id, safety_selection)
@ -368,9 +368,9 @@ fn resolve_filtered_node_ref(
fn get_node_ref(registry: VeilidComponentRegistry) -> impl FnOnce(&str) -> Option<NodeRef> {
move |text| {
let routing_table = registry.routing_table();
let nr = if let Some(key) = get_public_key(text) {
let nr = if let Some(key) = get_node_id(text) {
routing_table.lookup_any_node_ref(key).ok().flatten()?
} else if let Some(node_id) = get_typed_key(text) {
} else if let Some(node_id) = get_typed_node_id(text) {
routing_table.lookup_node_ref(node_id).ok().flatten()?
} else {
return None;
@ -401,9 +401,9 @@ fn get_filtered_node_ref(
.map(|x| (x.0, Some(x.1)))
.unwrap_or((text, None));
let nr = if let Some(key) = get_public_key(text) {
let nr = if let Some(key) = get_node_id(text) {
routing_table.lookup_any_node_ref(key).ok().flatten()?
} else if let Some(node_id) = get_typed_key(text) {
} else if let Some(node_id) = get_typed_node_id(text) {
routing_table.lookup_node_ref(node_id).ok().flatten()?
} else {
return None;

View file

@ -89,9 +89,9 @@ pub enum CryptoSystemRequestOp {
},
Distance {
#[schemars(with = "String")]
key1: PublicKey,
key1: HashDigest,
#[schemars(with = "String")]
key2: PublicKey,
key2: HashDigest,
},
Sign {
#[schemars(with = "String")]

View file

@ -227,7 +227,7 @@ impl JsonRequestProcessor {
}
// Is this a node id?
if let Ok(nid) = TypedPublicKey::from_str(&s) {
if let Ok(nid) = TypedNodeId::from_str(&s) {
return Ok(Target::NodeId(nid));
}
@ -551,7 +551,7 @@ impl JsonRequestProcessor {
}
}
CryptoSystemRequestOp::Distance { key1, key2 } => CryptoSystemResponseOp::Distance {
value: csv.distance(&HashDigest::from(key1), &HashDigest::from(key2)),
value: csv.distance(&key1, &key2),
},
CryptoSystemRequestOp::Sign { key, secret, data } => CryptoSystemResponseOp::Sign {
result: to_json_api_result_with_string(csv.sign(&key, &secret, &data)),

View file

@ -9,7 +9,7 @@ impl_veilid_log_facility!("veilid_api");
#[must_use]
pub enum Target {
/// Node by its public key.
NodeId(TypedPublicKey),
NodeId(TypedNodeId),
/// Remote private route by its id.
PrivateRoute(RouteId),
}

View file

@ -108,12 +108,18 @@ pub fn fix_routeid() -> RouteId {
RouteId::new(fake_key)
}
pub fn fix_typedkey() -> TypedPublicKey {
pub fn fix_nodeid() -> NodeId {
let mut fake_key = [0u8; CRYPTO_KEY_LENGTH];
random_bytes(&mut fake_key);
TypedPublicKey {
NodeId::new(fake_key)
}
pub fn fix_typednodeid() -> TypedNodeId {
let mut fake_key = [0u8; CRYPTO_KEY_LENGTH];
random_bytes(&mut fake_key);
TypedNodeId {
kind: FourCC::from_str("FAKE").unwrap(),
value: fix_publickey(),
value: fix_nodeid(),
}
}
@ -134,7 +140,7 @@ pub fn fix_secretkey() -> SecretKey {
pub fn fix_peertabledata() -> PeerTableData {
PeerTableData {
node_ids: vec![fix_typedkey()],
node_ids: vec![fix_typednodeid()],
peer_address: "123 Main St.".to_string(),
peer_stats: fix_peerstats(),
}
@ -175,7 +181,7 @@ pub fn fix_veilidconfig() -> VeilidConfig {
hole_punch_receipt_time_ms: 9000,
network_key_password: None,
routing_table: VeilidConfigRoutingTable {
node_id: TypedPublicKeyGroup::new(),
node_id: TypedNodeIdGroup::new(),
node_id_secret: TypedSecretKeyGroup::new(),
bootstrap: vec!["boots".to_string()],
bootstrap_keys: vec![TypedPublicKey::from_str(

View file

@ -14,7 +14,7 @@ pub fn test_alignedu64() {
pub fn test_veilidappmessage() {
let orig = VeilidAppMessage::new(
Some(fix_typedkey()),
Some(fix_typednodeid()),
Some(fix_routeid()),
b"Hi there!".to_vec(),
);
@ -25,7 +25,7 @@ pub fn test_veilidappmessage() {
pub fn test_veilidappcall() {
let orig = VeilidAppCall::new(
Some(fix_typedkey()),
Some(fix_typednodeid()),
Some(fix_routeid()),
b"Well, hello!".to_vec(),
OperationId::from(123),

View file

@ -11,7 +11,7 @@ pub struct VeilidAppMessage {
all(target_arch = "wasm32", target_os = "unknown"),
tsify(optional, type = "string")
)]
sender: Option<TypedPublicKey>,
sender: Option<TypedNodeId>,
#[serde(with = "as_human_opt_string")]
#[schemars(with = "Option<String>")]
@ -35,11 +35,7 @@ pub struct VeilidAppMessage {
}
impl VeilidAppMessage {
pub fn new(
sender: Option<TypedPublicKey>,
route_id: Option<RouteId>,
message: Vec<u8>,
) -> Self {
pub fn new(sender: Option<TypedNodeId>, route_id: Option<RouteId>, message: Vec<u8>) -> Self {
Self {
sender,
route_id,
@ -49,7 +45,7 @@ impl VeilidAppMessage {
/// Some(sender) if the message was sent directly, None if received via a private/safety route.
#[must_use]
pub fn sender(&self) -> Option<&TypedPublicKey> {
pub fn sender(&self) -> Option<&TypedNodeId> {
self.sender.as_ref()
}
@ -74,7 +70,7 @@ pub struct VeilidAppCall {
#[serde(with = "as_human_opt_string")]
#[schemars(with = "Option<String>")]
#[cfg_attr(all(target_arch = "wasm32", target_os = "unknown"), tsify(optional))]
sender: Option<TypedPublicKey>,
sender: Option<TypedNodeId>,
#[serde(with = "as_human_opt_string")]
#[schemars(with = "Option<String>")]
@ -103,7 +99,7 @@ pub struct VeilidAppCall {
impl VeilidAppCall {
pub fn new(
sender: Option<TypedPublicKey>,
sender: Option<TypedNodeId>,
route_id: Option<RouteId>,
message: Vec<u8>,
call_id: OperationId,
@ -118,7 +114,7 @@ impl VeilidAppCall {
/// Some(sender) if the request was sent directly, None if received via a private/safety route.
#[must_use]
pub fn sender(&self) -> Option<&TypedPublicKey> {
pub fn sender(&self) -> Option<&TypedNodeId> {
self.sender.as_ref()
}

View file

@ -107,7 +107,7 @@ pub struct PeerTableData {
all(target_arch = "wasm32", target_os = "unknown"),
tsify(type = "string[]")
)]
pub node_ids: Vec<TypedPublicKey>,
pub node_ids: Vec<TypedNodeId>,
/// The peer's human readable address.
pub peer_address: String,
/// Statistics we have collected on this peer.

View file

@ -496,7 +496,7 @@ impl Default for VeilidConfigRPC {
#[must_use]
pub struct VeilidConfigRoutingTable {
#[schemars(with = "Vec<String>")]
pub node_id: TypedPublicKeyGroup,
pub node_id: TypedNodeIdGroup,
#[schemars(with = "Vec<String>")]
pub node_id_secret: TypedSecretKeyGroup,
pub bootstrap: Vec<String>,
@ -530,7 +530,7 @@ impl Default for VeilidConfigRoutingTable {
];
Self {
node_id: TypedPublicKeyGroup::default(),
node_id: TypedNodeIdGroup::default(),
node_id_secret: TypedSecretKeyGroup::default(),
bootstrap,
bootstrap_keys,

View file

@ -20,7 +20,7 @@ use clap::{Args, Parser};
use server::*;
use settings::LogLevel;
use tools::*;
use veilid_core::{TypedPublicKeyGroup, TypedSecretKeyGroup};
use veilid_core::{TypedNodeIdGroup, TypedSecretKeyGroup};
use veilid_logs::*;
#[derive(Args, Debug, Clone)]
@ -315,7 +315,7 @@ fn main() -> EyreResult<()> {
settingsrw.logging.terminal.enabled = false;
// Split or get secret
let tks = TypedPublicKeyGroup::from_str(&key_set)
let tks = TypedNodeIdGroup::from_str(&key_set)
.wrap_err("failed to decode node id set from command line")?;
let buffer = rpassword::prompt_password("Enter secret key set (will not echo): ")

View file

@ -698,7 +698,7 @@ pub struct Dht {
#[derive(Debug, Deserialize, Serialize)]
pub struct RoutingTable {
pub node_id: Option<veilid_core::TypedPublicKeyGroup>,
pub node_id: Option<veilid_core::TypedNodeIdGroup>,
pub node_id_secret: Option<veilid_core::TypedSecretKeyGroup>,
pub bootstrap: Vec<String>,
pub bootstrap_keys: Vec<veilid_core::TypedPublicKey>,