hubert 0.5.0

Secure distributed substrate for multiparty transactions using write-once key-value storage with ARID-based addressing
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use std::sync::{Arc, RwLock};

use bc_components::ARID;
use bc_envelope::Envelope;
use bc_ur::UREncodable;
use dcbor::CBOREncodable;
use ipfs_api_backend_hyper::{IpfsApi, IpfsClient};
use ipfs_api_prelude::request::KeyType;
use tokio::time::{Duration, Instant, sleep};

use super::{
    error::Error as IpfsError,
    value::{add_bytes, cat_bytes, pin_cid},
};
use crate::{
    Error, KvStore, Result,
    arid_derivation::{derive_ipfs_key_name, obfuscate_with_arid},
};

/// IPFS-backed key-value store using IPNS for ARID-based addressing.
///
/// This implementation uses:
/// - ARID → IPNS key name derivation (deterministic)
/// - IPFS content addressing (CID) for immutable storage
/// - IPNS for publish-once mutable names
/// - Write-once semantics (publish fails if name already exists)
///
/// # Requirements
///
/// Requires a running Kubo daemon (or compatible IPFS node) with RPC API
/// available at the configured endpoint (default: http://127.0.0.1:5001).
///
/// # Example
///
/// ```no_run
/// use bc_components::ARID;
/// use bc_envelope::Envelope;
/// use hubert::{KvStore, ipfs::IpfsKv};
///
/// # async fn example() {
/// let store = IpfsKv::new("http://127.0.0.1:5001");
/// let arid = ARID::new();
/// let envelope = Envelope::new("Hello, IPFS!");
///
/// // Put envelope (write-once)
/// store.put(&arid, &envelope, None, false).await.unwrap();
///
/// // Get envelope with verbose logging
/// if let Some(retrieved) = store.get(&arid, None, true).await.unwrap() {
///     assert_eq!(retrieved, envelope);
/// }
/// # }
/// ```
pub struct IpfsKv {
    client: IpfsClient,
    key_cache: Arc<RwLock<std::collections::HashMap<String, KeyInfo>>>,
    max_envelope_size: usize,
    resolve_timeout: Duration,
    pin_content: bool,
}

#[derive(Clone, Debug)]
struct KeyInfo {
    peer_id: String,
}

impl IpfsKv {
    /// Create a new IPFS KV store with default settings.
    ///
    /// # Parameters
    ///
    /// - `rpc_url`: IPFS RPC endpoint (e.g., "http://127.0.0.1:5001")
    pub fn new(_rpc_url: &str) -> Self {
        Self {
            client: IpfsClient::default(),
            key_cache: Arc::new(RwLock::new(std::collections::HashMap::new())),
            max_envelope_size: 10 * 1024 * 1024, // 10 MB
            resolve_timeout: Duration::from_secs(30),
            pin_content: false,
        }
    }

    /// Set the maximum envelope size (default: 10 MB).
    pub fn with_max_size(mut self, size: usize) -> Self {
        self.max_envelope_size = size;
        self
    }

    /// Set the IPNS resolve timeout (default: 30 seconds).
    pub fn with_resolve_timeout(mut self, timeout: Duration) -> Self {
        self.resolve_timeout = timeout;
        self
    }

    /// Set whether to pin content (default: false).
    pub fn with_pin_content(mut self, pin: bool) -> Self {
        self.pin_content = pin;
        self
    }

    /// Get or create an IPNS key for the given ARID.
    async fn get_or_create_key(&self, arid: &ARID) -> Result<KeyInfo> {
        let key_name = derive_ipfs_key_name(arid);

        // Check cache first
        {
            let cache = self.key_cache.read().unwrap();
            if let Some(info) = cache.get(&key_name) {
                return Ok(info.clone());
            }
        }

        // List existing keys to see if it already exists
        let keys = self.client.key_list().await.map_err(IpfsError::from)?;

        if let Some(key) = keys.keys.iter().find(|k| k.name == key_name) {
            let info = KeyInfo { peer_id: key.id.clone() };
            // Update cache
            self.key_cache
                .write()
                .unwrap()
                .insert(key_name, info.clone());
            return Ok(info);
        }

        // Generate new key
        let key_info = self
            .client
            .key_gen(&key_name, KeyType::Ed25519, 0)
            .await
            .map_err(IpfsError::from)?;

        let info = KeyInfo { peer_id: key_info.id };

        // Update cache
        self.key_cache
            .write()
            .unwrap()
            .insert(key_name, info.clone());

        Ok(info)
    }

    /// Check if an IPNS name is already published.
    async fn is_published(&self, peer_id: &str) -> Result<bool> {
        match self.client.name_resolve(Some(peer_id), false, false).await {
            Ok(_) => Ok(true),
            Err(e) => {
                let err_str = e.to_string();
                // IPNS name not found errors indicate unpublished name
                if err_str.contains("could not resolve name")
                    || err_str.contains("no link named")
                    || err_str.contains("not found")
                {
                    Ok(false)
                } else {
                    Err(IpfsError::DaemonError(e).into())
                }
            }
        }
    }

    /// Publish a CID to an IPNS name (write-once).
    async fn publish_once(
        &self,
        key_name: &str,
        peer_id: &str,
        cid: &str,
        ttl_seconds: Option<u64>,
        arid: &ARID,
    ) -> crate::Result<()> {
        // Check if already published
        if self.is_published(peer_id).await? {
            return Err(Error::AlreadyExists { arid: arid.ur_string() });
        }

        // Convert TTL seconds to lifetime string for IPNS
        // Format: "Ns" for seconds, "Nm" for minutes, "Nh" for hours, "Nd" for
        // days
        let lifetime = ttl_seconds.map(|secs| {
            if secs < 60 {
                format!("{}s", secs)
            } else if secs < 3600 {
                format!("{}m", secs / 60)
            } else if secs < 86400 {
                format!("{}h", secs / 3600)
            } else {
                format!("{}d", secs / 86400)
            }
        });

        // Publish to IPNS
        self.client
            .name_publish(
                &format!("/ipfs/{}", cid),
                false,
                lifetime.as_deref(), // IPNS record lifetime (TTL)
                None,                // Cache TTL hint
                Some(key_name),
            )
            .await
            .map_err(IpfsError::from)?;
        Ok(())
    }

    /// Resolve an IPNS name to a CID with polling and custom timeout.
    async fn resolve_with_retry_timeout(
        &self,
        peer_id: &str,
        timeout: Duration,
        verbose: bool,
    ) -> crate::Result<Option<String>> {
        use crate::logging::verbose_print_dot;

        let deadline = Instant::now() + timeout;
        // Changed to 1000ms for verbose mode polling
        let poll_interval = Duration::from_millis(1000);

        loop {
            match self.client.name_resolve(Some(peer_id), false, false).await {
                Ok(res) => {
                    // Extract CID from path (e.g., "/ipfs/bafy..." ->
                    // "bafy...")
                    if let Some(cid) = res.path.strip_prefix("/ipfs/") {
                        return Ok(Some(cid.to_string()));
                    } else {
                        return Err(IpfsError::UnexpectedIpnsPathFormat(
                            res.path,
                        )
                        .into());
                    }
                }
                Err(e) => {
                    let err_str = e.to_string();
                    // Check if name simply doesn't exist (not published)
                    if err_str.contains("could not resolve name")
                        || err_str.contains("no link named")
                        || err_str.contains("not found")
                    {
                        return Ok(None);
                    }

                    // Check if we've timed out
                    if Instant::now() >= deadline {
                        return Err(IpfsError::Timeout.into());
                    }

                    // Print polling dot if verbose
                    if verbose {
                        verbose_print_dot();
                    }

                    // Retry after interval (now 1000ms)
                    sleep(poll_interval).await;
                }
            }
        }
    }
}

#[async_trait::async_trait(?Send)]
impl KvStore for IpfsKv {
    async fn put(
        &self,
        arid: &ARID,
        envelope: &Envelope,
        ttl_seconds: Option<u64>,
        verbose: bool,
    ) -> Result<String> {
        self.put_impl(arid, envelope, ttl_seconds, verbose).await
    }

    async fn get(
        &self,
        arid: &ARID,
        timeout_seconds: Option<u64>,
        verbose: bool,
    ) -> Result<Option<Envelope>> {
        self.get_impl(arid, timeout_seconds, verbose).await
    }

    async fn exists(&self, arid: &ARID) -> Result<bool> {
        self.exists_impl(arid).await
    }
}

impl IpfsKv {
    /// Internal put implementation with typed errors.
    async fn put_impl(
        &self,
        arid: &ARID,
        envelope: &Envelope,
        ttl_seconds: Option<u64>,
        verbose: bool,
    ) -> crate::Result<String> {
        use crate::logging::verbose_println;

        if verbose {
            verbose_println("Starting IPFS put operation");
        }

        // Serialize envelope
        let bytes = envelope.to_cbor_data();

        if verbose {
            verbose_println(&format!("Envelope size: {} bytes", bytes.len()));
        }

        // Obfuscate with ARID-derived key so it appears as random data
        let obfuscated = obfuscate_with_arid(arid, &bytes);

        // Check size after obfuscation (same size, but check anyway)
        if obfuscated.len() > self.max_envelope_size {
            return Err(
                IpfsError::EnvelopeTooLarge { size: obfuscated.len() }.into()
            );
        }

        if verbose {
            verbose_println("Obfuscated envelope data");
        }

        // Get or create IPNS key
        if verbose {
            verbose_println("Getting or creating IPNS key");
        }
        let key_info = self.get_or_create_key(arid).await?;

        let key_name = derive_ipfs_key_name(arid);

        // Add obfuscated data to IPFS
        if verbose {
            verbose_println("Adding content to IPFS");
        }
        let cid = add_bytes(&self.client, obfuscated).await?;

        if verbose {
            verbose_println(&format!("Content CID: {}", cid));
        }

        // Pin if requested
        if self.pin_content {
            if verbose {
                verbose_println("Pinning content");
            }
            pin_cid(&self.client, &cid, true).await?;
        }

        // Publish to IPNS (write-once)
        if verbose {
            verbose_println("Publishing to IPNS (write-once check)");
        }
        self.publish_once(
            &key_name,
            &key_info.peer_id,
            &cid,
            ttl_seconds,
            arid,
        )
        .await?;

        if verbose {
            verbose_println("IPFS put operation completed");
        }

        Ok(format!("ipns://{} -> ipfs://{}", key_info.peer_id, cid))
    }

    /// Internal get implementation with typed errors.
    async fn get_impl(
        &self,
        arid: &ARID,
        timeout_seconds: Option<u64>,
        verbose: bool,
    ) -> crate::Result<Option<Envelope>> {
        use crate::logging::{verbose_newline, verbose_println};

        if verbose {
            verbose_println("Starting IPFS get operation");
        }

        let key_name = derive_ipfs_key_name(arid);

        // Get key info from cache or daemon
        if verbose {
            verbose_println("Looking up IPNS key");
        }
        let keys = self.client.key_list().await.map_err(IpfsError::from)?;

        let key = keys.keys.iter().find(|k| k.name == key_name);
        if key.is_none() {
            // Key doesn't exist, so nothing published
            if verbose {
                verbose_println("Key not found");
            }
            return Ok(None);
        }

        let peer_id = &key.unwrap().id;

        // Resolve IPNS to CID with specified timeout
        if verbose {
            verbose_println("Resolving IPNS name (polling)");
        }
        let timeout = timeout_seconds
            .map(Duration::from_secs)
            .unwrap_or(self.resolve_timeout);
        let cid = self
            .resolve_with_retry_timeout(peer_id, timeout, verbose)
            .await?;

        if verbose {
            verbose_newline();
        }

        if cid.is_none() {
            if verbose {
                verbose_println("IPNS name not published");
            }
            return Ok(None);
        }

        let cid = cid.unwrap();

        if verbose {
            verbose_println(&format!("Resolved to CID: {}", cid));
        }

        // Cat CID to get obfuscated bytes
        if verbose {
            verbose_println("Fetching content from IPFS");
        }
        let obfuscated_bytes = cat_bytes(&self.client, &cid).await?;

        // Deobfuscate using ARID-derived key
        let deobfuscated = obfuscate_with_arid(arid, &obfuscated_bytes);

        if verbose {
            verbose_println("Deobfuscated envelope data");
        }

        // Deserialize envelope from deobfuscated data
        let envelope = Envelope::try_from_cbor_data(deobfuscated)?;

        if verbose {
            verbose_println("IPFS get operation completed");
        }

        Ok(Some(envelope))
    }

    /// Internal exists implementation with typed errors.
    async fn exists_impl(&self, arid: &ARID) -> crate::Result<bool> {
        let key_name = derive_ipfs_key_name(arid);

        // List keys to check if key exists
        let keys = self.client.key_list().await.map_err(IpfsError::from)?;

        let key = keys.keys.iter().find(|k| k.name == key_name);
        if key.is_none() {
            return Ok(false);
        }

        let peer_id = &key.unwrap().id;

        // Check if published (quick resolve)
        match self.client.name_resolve(Some(peer_id), false, false).await {
            Ok(_) => Ok(true),
            Err(e) => {
                let err_str = e.to_string();
                if err_str.contains("could not resolve name")
                    || err_str.contains("no link named")
                    || err_str.contains("not found")
                {
                    Ok(false)
                } else {
                    Err(IpfsError::DaemonError(e).into())
                }
            }
        }
    }
}