unc_primitives/
network.rs

1use crate::hash::CryptoHash;
2use crate::types::{AccountId, EpochId};
3use borsh::{BorshDeserialize, BorshSerialize};
4use std::fmt;
5use std::hash::Hash;
6use std::sync::Arc;
7use unc_crypto::{KeyType, PublicKey, SecretKey, Signature};
8
9/// Peer id is the public key.
10#[derive(
11    BorshSerialize,
12    BorshDeserialize,
13    Clone,
14    PartialEq,
15    Eq,
16    PartialOrd,
17    Ord,
18    Hash,
19    serde::Serialize,
20    serde::Deserialize,
21)]
22pub struct PeerId(Arc<PublicKey>);
23
24impl PeerId {
25    pub fn new(key: PublicKey) -> Self {
26        Self(Arc::new(key))
27    }
28
29    pub fn public_key(&self) -> &PublicKey {
30        &self.0
31    }
32}
33
34impl PeerId {
35    pub fn random() -> Self {
36        PeerId::new(SecretKey::from_random(KeyType::ED25519).public_key())
37    }
38}
39
40impl fmt::Display for PeerId {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        write!(f, "{}", self.0)
43    }
44}
45
46impl fmt::Debug for PeerId {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        write!(f, "{}", self.0)
49    }
50}
51
52/// Account announcement information
53#[derive(BorshSerialize, BorshDeserialize, PartialEq, Eq, Clone, Debug, Hash)]
54pub struct AnnounceAccount {
55    /// AccountId to be announced.
56    pub account_id: AccountId,
57    /// PeerId from the owner of the account.
58    pub peer_id: PeerId,
59    /// This announcement is only valid for this `epoch`.
60    pub epoch_id: EpochId,
61    /// Signature using AccountId associated secret key.
62    pub signature: Signature,
63}
64
65impl AnnounceAccount {
66    /// We hash only (account_id, peer_id, epoch_id). There is no need hash the signature
67    /// as it's uniquely determined the the triple.
68    pub fn build_header_hash(
69        account_id: &AccountId,
70        peer_id: &PeerId,
71        epoch_id: &EpochId,
72    ) -> CryptoHash {
73        CryptoHash::hash_borsh((account_id, peer_id, epoch_id))
74    }
75
76    pub fn hash(&self) -> CryptoHash {
77        AnnounceAccount::build_header_hash(&self.account_id, &self.peer_id, &self.epoch_id)
78    }
79}