near_primitives/
network.rs

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