near_primitives/
network.rs1use 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#[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#[derive(BorshSerialize, BorshDeserialize, PartialEq, Eq, Clone, Debug, Hash, ProtocolSchema)]
59pub struct AnnounceAccount {
60 pub account_id: AccountId,
62 pub peer_id: PeerId,
64 pub epoch_id: EpochId,
66 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 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}