Skip to main content

rings_core/delegation/
signing_key.rs

1use std::str::FromStr;
2
3use rings_derive::wasm_export;
4use serde::Deserialize;
5use serde::Serialize;
6use zeroize::Zeroizing;
7
8use super::Delegation;
9use super::DelegationBuilder;
10use crate::dht::Did;
11use crate::ecc::keccak256;
12use crate::ecc::keys::AccountVerifier;
13use crate::ecc::prime_order::NonIdentityPoint;
14use crate::ecc::prime_order::NonZeroScalar;
15use crate::ecc::prime_order::SHARED_SECRET_BYTES;
16use crate::ecc::signers;
17use crate::ecc::PublicKey;
18use crate::ecc::Secp256k1;
19use crate::ecc::SecretKey;
20use crate::error::Error;
21use crate::error::Result;
22use crate::utils;
23
24/// A verified [`Delegation`] and the delegatee's private signing key.
25///
26/// Invariant: every non-test `DelegateeKey` constructed, deserialized, or parsed via [`FromStr`]
27/// satisfies `Did::from(delegatee_secret_key.address()) == delegation.delegatee_did()` and carries
28/// a cryptographically valid delegator signature over `delegation`.
29///
30/// Clone law: cloning a `DelegateeKey` duplicates the same in-memory signing and decryption
31/// authority. The clone preserves the delegator DID, delegatee identity, and delegatee public
32/// key; it does not mint, rotate, or narrow the capability.
33#[wasm_export]
34#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
35#[serde(try_from = "UnverifiedDelegateeKey")]
36pub struct DelegateeKey {
37    delegation: Delegation,
38    delegatee_secret_key: SecretKey,
39}
40
41#[derive(Deserialize)]
42struct UnverifiedDelegateeKey {
43    delegation: Delegation,
44    delegatee_secret_key: SecretKey,
45}
46
47impl TryFrom<UnverifiedDelegateeKey> for DelegateeKey {
48    type Error = Error;
49
50    fn try_from(raw: UnverifiedDelegateeKey) -> Result<Self> {
51        Self::try_from_parts(raw.delegation, raw.delegatee_secret_key)
52    }
53}
54
55impl FromStr for DelegateeKey {
56    type Err = Error;
57
58    fn from_str(s: &str) -> Result<Self> {
59        let s = crate::base58_check::decode(s).map_err(|_| Error::Decode)?;
60        serde_json::from_slice(&s).map_err(Error::Deserialize)
61    }
62}
63
64impl DelegateeKey {
65    pub(super) const fn from_parts(
66        delegation: Delegation,
67        delegatee_secret_key: SecretKey,
68    ) -> Self {
69        Self {
70            delegation,
71            delegatee_secret_key,
72        }
73    }
74
75    /// Construct a [`DelegateeKey`] after verifying both the private-key-to-delegation DID binding
76    /// and the delegator's signature over `delegation`, without enforcing wall-clock expiry so
77    /// genuinely bound historical keys used solely for decryption can still be restored.
78    pub fn try_from_parts(delegation: Delegation, delegatee_secret_key: SecretKey) -> Result<Self> {
79        let candidate = Self::from_parts(delegation, delegatee_secret_key);
80        candidate.verify_binding()?;
81        candidate.delegation.verify_delegator_signature()?;
82        Ok(candidate)
83    }
84
85    /// Verify that this key's private scalar derives `delegation.delegatee_did()`.
86    pub fn verify_binding(&self) -> Result<()> {
87        let actual = Did::from(self.delegatee_secret_key.address());
88        let expected = self.delegation.delegatee_did();
89        if actual != expected {
90            return Err(Error::DelegateeKeyMismatch { expected, actual });
91        }
92        Ok(())
93    }
94
95    /// Verify private-key binding, delegator signature, and delegation validity window as of now.
96    pub fn verify(&self) -> Result<()> {
97        self.verify_at(utils::get_epoch_ms())
98    }
99
100    /// Verify private-key binding, delegator signature, and delegation validity window at `at_ms`.
101    pub fn verify_at(&self, at_ms: u128) -> Result<()> {
102        self.verify_binding()?;
103        self.delegation.verify_delegator_authorization_at(at_ms)
104    }
105
106    #[cfg(test)]
107    /// Construct a deterministic delegation for cross-target wire fixtures.
108    pub(crate) fn from_test_keys(
109        account_key: &SecretKey,
110        delegatee_key: SecretKey,
111        ts_ms: u128,
112        ttl_ms: u64,
113    ) -> Result<Self> {
114        let delegatee_did = Did::from(delegatee_key.address());
115        let delegator = super::Account::Secp256k1(account_key.address().into());
116        let proof = super::model::pack_delegation(&delegator, delegatee_did, ts_ms, ttl_ms);
117        let delegation = Delegation {
118            delegatee_did,
119            delegator,
120            ttl_ms,
121            ts_ms,
122            delegator_signature: account_key.sign(&proof)?.to_vec(),
123        };
124        delegation.verify_delegator_authorization_at(ts_ms)?;
125        Ok(Self::from_parts(delegation, delegatee_key))
126    }
127
128    /// Generate a self-delegated key from an existing private key. Only use this for unit tests.
129    ///
130    /// To protect account private keys in production, use [`DelegationBuilder`] instead.
131    pub fn new_with_seckey(key: &SecretKey) -> Result<Self> {
132        Self::new_with_seckey_at(
133            key,
134            crate::consts::DEFAULT_DELEGATION_TTL_MS,
135            crate::utils::get_epoch_ms(),
136        )
137    }
138
139    /// Mint a fresh [`DelegateeKey`] authorized by `key` for `ttl_ms` starting at `ts_ms`.
140    pub fn new_with_seckey_at(key: &SecretKey, ttl_ms: u64, ts_ms: u128) -> Result<Self> {
141        let account_entity = Did::from(key.address()).to_string();
142        let account_type = "secp256k1".to_string();
143        let builder = DelegationBuilder::new(account_entity, account_type)
144            .set_ttl(ttl_ms)
145            .set_ts(ts_ms);
146        let sig = key.sign(&builder.unsigned_proof())?;
147        builder
148            .set_delegator_signature(sig.to_vec())
149            .build_at(ts_ms)
150    }
151
152    /// Clone the public delegation proof.
153    pub fn delegation(&self) -> Delegation {
154        self.delegation.clone()
155    }
156
157    /// Return the secp256k1 delegatee public key used for encryption.
158    pub fn delegatee_public_key(&self) -> PublicKey<33> {
159        self.delegatee_secret_key.pubkey()
160    }
161
162    /// Decrypt an ElGamal-AEAD envelope with this delegatee key.
163    pub fn decrypt_elgamal_aead(
164        &self,
165        sealed: &crate::ecc::elgamal::impls::secp256k1::AeadCiphertext,
166        aad: &[u8],
167    ) -> Result<Vec<u8>> {
168        crate::ecc::elgamal::impls::secp256k1::decrypt_aead(sealed, aad, &self.delegatee_secret_key)
169    }
170
171    /// The Diffie–Hellman shared secret `x(P·d)` of a peer element `P` and the delegatee secret
172    /// `d`, zeroized on drop.
173    ///
174    /// Law: for every `x ∈ Z_n^*`, `diffie_hellman(x·G) = (d·G)·x` in its x-coordinate, so a
175    /// sender holding `x` and [`Self::delegatee_public_key`] derives the same secret. `P ≠ O` by
176    /// its type, and the secret scalar is only ever held in a zeroizing `Z_n^*` value.
177    pub fn diffie_hellman(
178        &self,
179        peer: &NonIdentityPoint<Secp256k1>,
180    ) -> Zeroizing<[u8; SHARED_SECRET_BYTES]> {
181        peer.shared_secret(&NonZeroScalar::from_secret_key(&self.delegatee_secret_key))
182    }
183
184    /// Sign a message with this delegatee key.
185    pub fn sign(&self, msg: &[u8]) -> Result<Vec<u8>> {
186        let h = keccak256(msg);
187        Ok(signers::secp256k1::sign(&self.delegatee_secret_key, &h)?.to_vec())
188    }
189
190    /// Get the DID of the delegator.
191    pub fn delegator_did(&self) -> Did {
192        self.delegation.delegator_did()
193    }
194
195    /// Get the delegator account verifier from this delegation.
196    pub fn delegator_verifier(&self) -> AccountVerifier {
197        self.delegation.delegator_verifier()
198    }
199
200    /// Encode this delegatee key for storage in a configuration file.
201    ///
202    /// Restore it with [`DelegateeKey::from_str`].
203    pub fn dump(&self) -> Result<String> {
204        let s = serde_json::to_string(self).map_err(|_| Error::SerializeError)?;
205        base58_monero::encode_check(s.as_bytes()).map_err(|_| Error::Encode)
206    }
207}