fedimint-core 0.12.0-beta.2

fedimint-core provides common code used by both client and server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use bitcoin::hashes::{Hash, sha256};
use bitcoin::secp256k1::Message;
use fedimint_core::encoding::{Decodable, DecodeError, Encodable};
use serde::{Deserialize, Serialize};

use crate::util::SafeUrl;

const GUARDIAN_METADATA_MESSAGE_TAG: &[u8] = b"fedimint-guardian-metadata";
/// Allow messages with timestamps up to 1 hour in the future
const MAX_FUTURE_TIMESTAMP_SECS: u64 = 3600;

#[derive(Debug, Serialize, Deserialize, Clone, Eq, Hash, PartialEq)]
pub struct GuardianMetadata {
    pub api_urls: Vec<SafeUrl>,
    /// z-base32 encoded Pkarr id
    pub pkarr_id_z32: String,
    pub timestamp_secs: u64,
    /// Iroh-next 1.0-compatible API endpoint node ID (public key) when enabled
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub iroh_next_endpoint: Option<String>,
}

#[derive(Debug, Clone, Eq, Hash, PartialEq)]
pub struct SignedGuardianMetadata {
    /// The raw bytes that were signed (JSON-encoded GuardianMetadata)
    pub bytes: Vec<u8>,
    /// The parsed GuardianMetadata value
    pub value: GuardianMetadata,
    pub signature: secp256k1::schnorr::Signature,
}

#[derive(Debug, Serialize, Deserialize, Clone, Eq, Hash, PartialEq, Encodable, Decodable)]
pub struct SignedGuardianMetadataSubmission {
    #[serde(flatten)]
    pub signed_guardian_metadata: SignedGuardianMetadata,
    pub peer_id: crate::PeerId,
}

// Implement Serialize/Deserialize for SignedGuardianMetadata for JSON
//
// Format: {"content": "<json string>", "signature": "<hex-encoded signature>"}
// The `content` field contains the exact JSON string that was signed (preserved
// byte-for-byte). The `signature` field contains the hex-encoded Schnorr
// signature over the content bytes.
impl Serialize for SignedGuardianMetadata {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;
        let mut state = serializer.serialize_struct("SignedGuardianMetadata", 2)?;

        // Serialize bytes as a UTF-8 string (content field)
        let content = String::from_utf8(self.bytes.clone())
            .map_err(|e| serde::ser::Error::custom(format!("Invalid UTF-8 in bytes: {e}")))?;
        state.serialize_field("content", &content)?;

        // Serialize signature as hex string
        state.serialize_field("signature", &hex::encode(self.signature.as_ref()))?;
        state.end()
    }
}

impl<'de> Deserialize<'de> for SignedGuardianMetadata {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Error;

        #[derive(Deserialize)]
        struct SignedGuardianMetadataHelper {
            content: String,
            signature: String,
        }

        let helper = SignedGuardianMetadataHelper::deserialize(deserializer)?;

        let bytes = helper.content.into_bytes();
        let value: GuardianMetadata = serde_json::from_slice(&bytes).map_err(D::Error::custom)?;
        let signature_bytes = hex::decode(&helper.signature).map_err(D::Error::custom)?;
        let signature = secp256k1::schnorr::Signature::from_slice(&signature_bytes)
            .map_err(D::Error::custom)?;

        Ok(Self {
            bytes,
            value,
            signature,
        })
    }
}

// Implement Encodable/Decodable for SignedGuardianMetadata only
impl Encodable for SignedGuardianMetadata {
    fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
        // Encode the bytes and signature (value is derived from bytes)
        self.bytes.consensus_encode(writer)?;
        self.signature.consensus_encode(writer)?;
        Ok(())
    }
}

impl Decodable for SignedGuardianMetadata {
    fn consensus_decode_partial_from_finite_reader<R: std::io::Read>(
        reader: &mut R,
        modules: &fedimint_core::module::registry::ModuleDecoderRegistry,
    ) -> Result<Self, DecodeError> {
        let bytes = Vec::<u8>::consensus_decode_partial_from_finite_reader(reader, modules)?;
        let value: GuardianMetadata = serde_json::from_slice(&bytes)
            .map_err(|e| DecodeError::new_custom(anyhow::anyhow!("Invalid JSON: {e}")))?;
        let signature = secp256k1::schnorr::Signature::consensus_decode_partial_from_finite_reader(
            reader, modules,
        )?;

        Ok(Self {
            bytes,
            value,
            signature,
        })
    }
}

fn compute_tagged_hash(json_bytes: &[u8]) -> sha256::Hash {
    use bitcoin::hashes::HashEngine;
    let mut engine = sha256::HashEngine::default();
    engine.input(GUARDIAN_METADATA_MESSAGE_TAG);
    engine.input(json_bytes);
    sha256::Hash::from_engine(engine)
}

#[derive(Debug, thiserror::Error)]
pub enum VerificationError {
    #[error("Invalid signature")]
    InvalidSignature,
    #[error("Timestamp {timestamp_secs} is too far in the future (max allowed: {max_allowed})")]
    TimestampTooFarInFuture {
        timestamp_secs: u64,
        max_allowed: u64,
    },
}

impl GuardianMetadata {
    pub fn new(api_urls: Vec<SafeUrl>, pkarr_id_z32: String, timestamp_secs: u64) -> Self {
        Self {
            api_urls,
            pkarr_id_z32,
            timestamp_secs,
            iroh_next_endpoint: None,
        }
    }

    /// Set the iroh-next 1.0-compatible API endpoint node ID.
    pub fn with_iroh_next_endpoint(mut self, endpoint: String) -> Self {
        self.iroh_next_endpoint = Some(endpoint);
        self
    }

    pub fn sign<C: secp256k1::Signing>(
        &self,
        ctx: &secp256k1::Secp256k1<C>,
        key: &secp256k1::Keypair,
    ) -> SignedGuardianMetadata {
        // Serialize to JSON and compute tagged hash
        let bytes = serde_json::to_vec(self).expect("JSON serialization should not fail");
        let tagged_hash = compute_tagged_hash(&bytes);

        let msg = Message::from_digest(*tagged_hash.as_ref());
        let signature = ctx.sign_schnorr(&msg, key);

        SignedGuardianMetadata {
            bytes,
            value: self.clone(),
            signature,
        }
    }
}

impl SignedGuardianMetadata {
    /// Returns the parsed GuardianMetadata value
    pub fn guardian_metadata(&self) -> &GuardianMetadata {
        &self.value
    }

    /// Compute the tagged hash from the stored bytes
    pub fn tagged_hash(&self) -> sha256::Hash {
        compute_tagged_hash(&self.bytes)
    }

    /// Verifies the signature and timestamp validity.
    ///
    /// Returns `Ok(())` if the signature is valid for the given public key and
    /// the timestamp is not too far in the future relative to `now`.
    pub fn verify<C: secp256k1::Verification>(
        &self,
        ctx: &secp256k1::Secp256k1<C>,
        pk: &secp256k1::PublicKey,
        now: std::time::Duration,
    ) -> Result<(), VerificationError> {
        // First check the signature
        let msg = Message::from_digest(*self.tagged_hash().as_ref());
        ctx.verify_schnorr(&self.signature, &msg, &pk.x_only_public_key().0)
            .map_err(|_| VerificationError::InvalidSignature)?;

        // Then check the timestamp isn't too far in the future
        let current_secs = now.as_secs();
        let max_allowed_timestamp = current_secs.saturating_add(MAX_FUTURE_TIMESTAMP_SECS);

        if max_allowed_timestamp < self.value.timestamp_secs {
            return Err(VerificationError::TimestampTooFarInFuture {
                timestamp_secs: self.value.timestamp_secs,
                max_allowed: max_allowed_timestamp,
            });
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;
    use crate::module::registry::ModuleRegistry;

    #[test]
    fn signed_guardian_metadata_json_roundtrip() {
        let ctx = secp256k1::Secp256k1::new();
        let keypair = secp256k1::Keypair::new(&ctx, &mut secp256k1::rand::thread_rng());
        let public_key = secp256k1::PublicKey::from_keypair(&keypair);

        let timestamp_secs = 1000;
        let metadata = GuardianMetadata::new(
            vec!["wss://example.com/api".parse().unwrap()],
            "test_pkarr_id".to_string(),
            timestamp_secs,
        );

        let signed = metadata.sign(&ctx, &keypair);

        // Serialize to JSON
        let json = serde_json::to_string(&signed).expect("serialization should succeed");

        // Verify JSON structure
        let json_value: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(
            json_value.get("content").is_some(),
            "should have content field"
        );
        assert!(
            json_value.get("signature").is_some(),
            "should have signature field"
        );

        // Deserialize from JSON
        let deserialized: SignedGuardianMetadata =
            serde_json::from_str(&json).expect("deserialization should succeed");

        // Compare original and deserialized
        assert_eq!(signed.bytes, deserialized.bytes);
        assert_eq!(signed.value, deserialized.value);
        assert_eq!(signed.signature, deserialized.signature);
        assert_eq!(signed, deserialized);

        // Verify signature still works after roundtrip
        let now = Duration::from_secs(timestamp_secs);
        deserialized
            .verify(&ctx, &public_key, now)
            .expect("signature should verify after roundtrip");

        // Verify extracted metadata matches original
        assert_eq!(*deserialized.guardian_metadata(), metadata);
    }

    #[test]
    fn signed_guardian_metadata_encodable_roundtrip() {
        let ctx = secp256k1::Secp256k1::new();
        let keypair = secp256k1::Keypair::new(&ctx, &mut secp256k1::rand::thread_rng());
        let public_key = secp256k1::PublicKey::from_keypair(&keypair);

        let timestamp_secs = 1000;
        let metadata = GuardianMetadata::new(
            vec!["wss://example.com/api".parse().unwrap()],
            "test_pkarr_id".to_string(),
            timestamp_secs,
        );

        let signed = metadata.sign(&ctx, &keypair);

        // Encode to bytes
        let encoded = signed.consensus_encode_to_vec();

        // Decode from bytes
        let deserialized: SignedGuardianMetadata =
            Decodable::consensus_decode_whole(&encoded, &ModuleRegistry::default())
                .expect("decoding should succeed");

        // Compare original and deserialized
        assert_eq!(signed.bytes, deserialized.bytes);
        assert_eq!(signed.value, deserialized.value);
        assert_eq!(signed.signature, deserialized.signature);
        assert_eq!(signed, deserialized);

        // Verify signature still works after roundtrip
        let now = Duration::from_secs(timestamp_secs);
        deserialized
            .verify(&ctx, &public_key, now)
            .expect("signature should verify after roundtrip");

        // Verify extracted metadata matches original
        assert_eq!(*deserialized.guardian_metadata(), metadata);
    }

    #[test]
    fn verify_valid_signature_and_timestamp() {
        let ctx = secp256k1::Secp256k1::new();
        let keypair = secp256k1::Keypair::new(&ctx, &mut secp256k1::rand::thread_rng());
        let public_key = secp256k1::PublicKey::from_keypair(&keypair);

        let timestamp_secs = 10000;
        let metadata = GuardianMetadata::new(
            vec!["wss://example.com/api".parse().unwrap()],
            "test_pkarr_id".to_string(),
            timestamp_secs,
        );
        let signed = metadata.sign(&ctx, &keypair);

        // Verify succeeds when now == timestamp
        signed
            .verify(&ctx, &public_key, Duration::from_secs(timestamp_secs))
            .expect("should verify with matching timestamp");

        // Verify succeeds when now is after timestamp (metadata from the past)
        signed
            .verify(
                &ctx,
                &public_key,
                Duration::from_secs(timestamp_secs + 1000),
            )
            .expect("should verify with past timestamp");

        // Verify succeeds when timestamp is slightly in the future (within allowed
        // window)
        signed
            .verify(
                &ctx,
                &public_key,
                Duration::from_secs(timestamp_secs - MAX_FUTURE_TIMESTAMP_SECS),
            )
            .expect("should verify when timestamp is within allowed future window");
    }

    #[test]
    fn verify_rejects_invalid_signature() {
        let ctx = secp256k1::Secp256k1::new();
        let keypair = secp256k1::Keypair::new(&ctx, &mut secp256k1::rand::thread_rng());
        let wrong_keypair = secp256k1::Keypair::new(&ctx, &mut secp256k1::rand::thread_rng());
        let wrong_public_key = secp256k1::PublicKey::from_keypair(&wrong_keypair);

        let timestamp_secs = 1000;
        let metadata = GuardianMetadata::new(
            vec!["wss://example.com/api".parse().unwrap()],
            "test_pkarr_id".to_string(),
            timestamp_secs,
        );
        let signed = metadata.sign(&ctx, &keypair);

        // Verify fails with wrong public key
        let result = signed.verify(&ctx, &wrong_public_key, Duration::from_secs(timestamp_secs));
        assert!(
            matches!(result, Err(VerificationError::InvalidSignature)),
            "should reject invalid signature"
        );
    }

    #[test]
    fn verify_rejects_timestamp_too_far_in_future() {
        let ctx = secp256k1::Secp256k1::new();
        let keypair = secp256k1::Keypair::new(&ctx, &mut secp256k1::rand::thread_rng());
        let public_key = secp256k1::PublicKey::from_keypair(&keypair);

        let timestamp_secs = 10000;
        let metadata = GuardianMetadata::new(
            vec!["wss://example.com/api".parse().unwrap()],
            "test_pkarr_id".to_string(),
            timestamp_secs,
        );
        let signed = metadata.sign(&ctx, &keypair);

        // Verify fails when timestamp is too far in the future
        let now_secs = timestamp_secs - MAX_FUTURE_TIMESTAMP_SECS - 1;
        let result = signed.verify(&ctx, &public_key, Duration::from_secs(now_secs));
        assert!(
            matches!(
                result,
                Err(VerificationError::TimestampTooFarInFuture {
                    timestamp_secs: ts,
                    ..
                }) if ts == timestamp_secs
            ),
            "should reject timestamp too far in future"
        );
    }
}