jax-common 0.1.11

Core data structures and cryptography for JaxBucket - end-to-end encrypted P2P storage
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
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use uuid::Uuid;

use super::provider::{BucketLogError, BucketLogProvider};
use crate::linked_data::Link;

/// In-memory bucket log provider using HashMaps
#[derive(Debug, Clone)]
pub struct MemoryBucketLogProvider {
    inner: Arc<RwLock<MemoryBucketLogProviderInner>>,
}

#[derive(Debug, Default)]
struct MemoryBucketLogProviderInner {
    /// Store log entries: bucket_id -> height -> Vec<Link>
    /// Multiple links at same height represent forks
    entries: HashMap<Uuid, HashMap<u64, Vec<Link>>>,
    /// Track the maximum height for each bucket
    max_heights: HashMap<Uuid, u64>,
    /// Index for quick lookup: bucket_id -> link -> Vec<heights>
    link_index: HashMap<Uuid, HashMap<Link, Vec<u64>>>,
    /// Store bucket names (optional, for caching)
    names: HashMap<Uuid, String>,
    /// Track published status: bucket_id -> link -> published
    published: HashMap<Uuid, HashMap<Link, bool>>,
}

#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum MemoryBucketLogProviderError {
    #[error("memory provider error: {0}")]
    Internal(String),
}

impl MemoryBucketLogProvider {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(MemoryBucketLogProviderInner::default())),
        }
    }
}

impl Default for MemoryBucketLogProvider {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl BucketLogProvider for MemoryBucketLogProvider {
    type Error = MemoryBucketLogProviderError;

    async fn exists(&self, id: Uuid) -> Result<bool, BucketLogError<Self::Error>> {
        let inner = self.inner.read().map_err(|e| {
            BucketLogError::Provider(MemoryBucketLogProviderError::Internal(format!(
                "failed to acquire read lock: {}",
                e
            )))
        })?;

        Ok(inner.entries.contains_key(&id))
    }

    async fn heads(&self, id: Uuid, height: u64) -> Result<Vec<Link>, BucketLogError<Self::Error>> {
        let inner = self.inner.read().map_err(|e| {
            BucketLogError::Provider(MemoryBucketLogProviderError::Internal(format!(
                "failed to acquire read lock: {}",
                e
            )))
        })?;

        Ok(inner
            .entries
            .get(&id)
            .and_then(|heights| heights.get(&height))
            .cloned()
            .unwrap_or_default())
    }

    async fn append(
        &self,
        id: Uuid,
        name: String,
        current: Link,
        previous: Option<Link>,
        height: u64,
        published: bool,
    ) -> Result<(), BucketLogError<Self::Error>> {
        let mut inner = self.inner.write().map_err(|e| {
            BucketLogError::Provider(MemoryBucketLogProviderError::Internal(format!(
                "failed to acquire write lock: {}",
                e
            )))
        })?;

        // Update bucket name
        inner.names.insert(id, name);

        // Get or create bucket entries
        let bucket_entries = inner.entries.entry(id).or_insert_with(HashMap::new);

        // Check for conflict: same link at same height already exists
        if let Some(existing_links) = bucket_entries.get(&height) {
            if existing_links.contains(&current) {
                return Err(BucketLogError::Conflict);
            }
        }

        // Validate the append based on previous link
        if let Some(prev_link) = &previous {
            // If there's a previous link, it should exist at height - 1
            if height == 0 {
                return Err(BucketLogError::InvalidAppend(
                    current,
                    prev_link.clone(),
                    height,
                ));
            }

            let expected_prev_height = height - 1;
            let prev_exists = bucket_entries
                .get(&expected_prev_height)
                .map(|links| links.contains(prev_link))
                .unwrap_or(false);

            if !prev_exists {
                return Err(BucketLogError::InvalidAppend(
                    current,
                    prev_link.clone(),
                    expected_prev_height,
                ));
            }
        } else {
            // If no previous link, this must be genesis (height 0)
            if height != 0 {
                // For non-genesis entries, we need a previous link
                return Err(BucketLogError::InvalidAppend(
                    current,
                    Link::default(), // placeholder for error
                    height,
                ));
            }
        }

        // Add the entry
        bucket_entries
            .entry(height)
            .or_insert_with(Vec::new)
            .push(current.clone());

        // Update max height
        let current_max = inner.max_heights.get(&id).copied();
        if current_max.is_none() || height > current_max.unwrap() {
            inner.max_heights.insert(id, height);
        }

        // Update link index
        inner
            .link_index
            .entry(id)
            .or_insert_with(HashMap::new)
            .entry(current.clone())
            .or_insert_with(Vec::new)
            .push(height);

        // Store published status
        inner
            .published
            .entry(id)
            .or_insert_with(HashMap::new)
            .insert(current, published);

        Ok(())
    }

    async fn height(&self, id: Uuid) -> Result<u64, BucketLogError<Self::Error>> {
        let inner = self.inner.read().map_err(|e| {
            BucketLogError::Provider(MemoryBucketLogProviderError::Internal(format!(
                "failed to acquire read lock: {}",
                e
            )))
        })?;

        inner
            .max_heights
            .get(&id)
            .copied()
            .ok_or(BucketLogError::HeadNotFound(0))
    }

    async fn has(&self, id: Uuid, link: Link) -> Result<Vec<u64>, BucketLogError<Self::Error>> {
        let inner = self.inner.read().map_err(|e| {
            BucketLogError::Provider(MemoryBucketLogProviderError::Internal(format!(
                "failed to acquire read lock: {}",
                e
            )))
        })?;

        Ok(inner
            .link_index
            .get(&id)
            .and_then(|links| links.get(&link))
            .cloned()
            .unwrap_or_default())
    }

    async fn list_buckets(&self) -> Result<Vec<Uuid>, BucketLogError<Self::Error>> {
        let inner = self.inner.read().map_err(|e| {
            BucketLogError::Provider(MemoryBucketLogProviderError::Internal(format!(
                "failed to acquire read lock: {}",
                e
            )))
        })?;

        Ok(inner.entries.keys().copied().collect())
    }

    async fn latest_published(
        &self,
        id: Uuid,
    ) -> Result<Option<(Link, u64)>, BucketLogError<Self::Error>> {
        let inner = self.inner.read().map_err(|e| {
            BucketLogError::Provider(MemoryBucketLogProviderError::Internal(format!(
                "failed to acquire read lock: {}",
                e
            )))
        })?;

        // Get the published status map for this bucket
        let Some(published_map) = inner.published.get(&id) else {
            return Ok(None);
        };

        // Get all entries for this bucket
        let Some(entries) = inner.entries.get(&id) else {
            return Ok(None);
        };

        // Find the highest height with a published link
        let mut best: Option<(Link, u64)> = None;
        for (height, links) in entries.iter() {
            for link in links {
                if published_map.get(link).copied().unwrap_or(false)
                    && (best.is_none() || *height > best.as_ref().unwrap().1)
                {
                    best = Some((link.clone(), *height));
                }
            }
        }

        Ok(best)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use iroh_blobs::Hash;

    #[tokio::test]
    async fn test_genesis_append() {
        let provider = MemoryBucketLogProvider::new();
        let id = Uuid::new_v4();
        let link = Link::new(0x55, Hash::from_bytes([1; 32]));

        // Genesis append should succeed
        let result = provider
            .append(id, "test".to_string(), link.clone(), None, 0, false)
            .await;
        assert!(result.is_ok());

        // Check height
        let height = provider.height(id).await.unwrap();
        assert_eq!(height, 0);

        // Check heads
        let heads = provider.heads(id, 0).await.unwrap();
        assert_eq!(heads, vec![link]);
    }

    #[tokio::test]
    async fn test_conflict() {
        let provider = MemoryBucketLogProvider::new();
        let id = Uuid::new_v4();
        let link = Link::new(0x55, Hash::from_bytes([1; 32]));

        // First append succeeds
        provider
            .append(id, "test".to_string(), link.clone(), None, 0, false)
            .await
            .unwrap();

        // Same link at same height should conflict
        let result = provider
            .append(id, "test".to_string(), link, None, 0, false)
            .await;
        assert!(matches!(result, Err(BucketLogError::Conflict)));
    }

    #[tokio::test]
    async fn test_invalid_append() {
        let provider = MemoryBucketLogProvider::new();
        let id = Uuid::new_v4();
        let link1 = Link::new(0x55, Hash::from_bytes([1; 32]));
        let link2 = Link::new(0x55, Hash::from_bytes([2; 32]));

        // Genesis
        provider
            .append(id, "test".to_string(), link1, None, 0, false)
            .await
            .unwrap();

        // Append with non-existent previous should fail
        let result = provider
            .append(id, "test".to_string(), link2.clone(), Some(link2), 1, false)
            .await;
        assert!(matches!(
            result,
            Err(BucketLogError::InvalidAppend(_, _, _))
        ));
    }

    #[tokio::test]
    async fn test_valid_chain() {
        let provider = MemoryBucketLogProvider::new();
        let id = Uuid::new_v4();
        let link1 = Link::new(0x55, Hash::from_bytes([1; 32]));
        let link2 = Link::new(0x55, Hash::from_bytes([2; 32]));

        // Genesis
        provider
            .append(id, "test".to_string(), link1.clone(), None, 0, false)
            .await
            .unwrap();

        // Valid append
        provider
            .append(id, "test".to_string(), link2.clone(), Some(link1), 1, false)
            .await
            .unwrap();

        // Check height
        let height = provider.height(id).await.unwrap();
        assert_eq!(height, 1);

        // Check has
        let heights = provider.has(id, link2).await.unwrap();
        assert_eq!(heights, vec![1]);
    }

    #[tokio::test]
    async fn test_latest_published() {
        let provider = MemoryBucketLogProvider::new();
        let id = Uuid::new_v4();
        let link1 = Link::new(0x55, Hash::from_bytes([1; 32]));
        let link2 = Link::new(0x55, Hash::from_bytes([2; 32]));
        let link3 = Link::new(0x55, Hash::from_bytes([3; 32]));

        // Genesis (unpublished)
        provider
            .append(id, "test".to_string(), link1.clone(), None, 0, false)
            .await
            .unwrap();

        // No published version yet
        assert!(provider.latest_published(id).await.unwrap().is_none());

        // Second version (published)
        provider
            .append(
                id,
                "test".to_string(),
                link2.clone(),
                Some(link1.clone()),
                1,
                true,
            )
            .await
            .unwrap();

        // Should return the published version
        let (link, height) = provider.latest_published(id).await.unwrap().unwrap();
        assert_eq!(link, link2);
        assert_eq!(height, 1);

        // Third version (unpublished)
        provider
            .append(
                id,
                "test".to_string(),
                link3.clone(),
                Some(link2.clone()),
                2,
                false,
            )
            .await
            .unwrap();

        // Should still return the published version at height 1
        let (link, height) = provider.latest_published(id).await.unwrap().unwrap();
        assert_eq!(link, link2);
        assert_eq!(height, 1);
    }
}