Skip to main content

antenna_protocol/identity/
mod.rs

1mod peer_id;
2
3use crate::{deserialize_base64_keypair, serialize_base64_keypair};
4use anyhow::Result;
5use base64::{Engine, prelude::BASE64_URL_SAFE_NO_PAD};
6use biscuit_auth::{Biscuit, KeyPair, PublicKey};
7pub use peer_id::PeerID;
8use serde::{Deserialize, Serialize};
9
10/// Persistent ED25519 identity of a peer.
11///
12/// The public half is the [`PeerID`] used to address the peer in the mesh.
13#[derive(Serialize, Deserialize)]
14pub struct Identity {
15    #[serde(
16        serialize_with = "serialize_base64_keypair",
17        deserialize_with = "deserialize_base64_keypair"
18    )]
19    keypair: KeyPair,
20}
21
22impl Default for Identity {
23    fn default() -> Self {
24        Self::new()
25    }
26}
27
28impl Identity {
29    pub fn new() -> Self {
30        Self {
31            keypair: KeyPair::new(),
32        }
33    }
34
35    pub fn pubkey(&self) -> PublicKey {
36        self.keypair.public()
37    }
38
39    pub fn peer_id(&self) -> PeerID {
40        PeerID(self.keypair.public())
41    }
42
43    pub fn create_token(&self, sdp: &str) -> Result<Vec<u8>> {
44        let sdp_b64 = BASE64_URL_SAFE_NO_PAD.encode(sdp);
45        Ok(Biscuit::builder()
46            .fact(format!("sdp(\"{sdp_b64}\")").as_str())?
47            .build(&self.keypair)?
48            .to_vec()?)
49    }
50}