cory-core 0.1.1

Core domain logic for Cory: Bitcoin RPC adapter, ancestry graph builder, labels, and caching.
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! `LabelStore` — the central in-memory store for BIP-329 label data.
//!
//! Manages three kinds of label files:
//! - **PersistentRw** — on-disk labels loaded from `--labels-rw` dirs,
//!   editable and auto-flushed to disk on mutation.
//! - **PersistentRo** — on-disk labels loaded from `--labels-ro` dirs,
//!   read-only.
//! - **BrowserRw** — browser-only labels created/imported/exported via
//!   the UI, editable but ephemeral.
//!
//! Queries merge results across all loaded files with deterministic
//! precedence: PersistentRw → BrowserRw → PersistentRo.

use std::collections::{HashMap, HashSet};
use std::path::Path;

use crate::error::CoreError;

use super::jsonl::{export_map_to_jsonl, parse_jsonl_records, parse_local_file_name};
use super::pack::walk_label_dir;
use super::types::{Bip329Record, Bip329Type, LabelFile, LabelFileKind, LabelStoreError};

pub struct LabelStore {
    persistent_rw_files: Vec<LabelFile>,
    browser_rw_files: Vec<LabelFile>,
    persistent_ro_files: Vec<LabelFile>,
}

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

impl LabelStore {
    pub fn new() -> Self {
        Self {
            persistent_rw_files: Vec::new(),
            browser_rw_files: Vec::new(),
            persistent_ro_files: Vec::new(),
        }
    }

    // ========================================================================
    // Directory loading
    // ========================================================================

    /// Load a `--labels-rw` directory. Files are editable and auto-flushed
    /// to their on-disk `source_path` on mutation.
    pub fn load_rw_dir(&mut self, dir: &Path) -> Result<(), CoreError> {
        if !dir.is_dir() {
            return Err(CoreError::Io(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("labels-rw directory not found: {}", dir.display()),
            )));
        }

        let mut seen_ids = self.all_ids();
        walk_label_dir(
            dir,
            dir,
            LabelFileKind::PersistentRw,
            &mut self.persistent_rw_files,
            &mut seen_ids,
        )
    }

    /// Load a `--labels-ro` directory. Files are read-only in the UI.
    pub fn load_ro_dir(&mut self, dir: &Path) -> Result<(), CoreError> {
        if !dir.is_dir() {
            return Err(CoreError::Io(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("labels-ro directory not found: {}", dir.display()),
            )));
        }

        let mut seen_ids = self.all_ids();
        walk_label_dir(
            dir,
            dir,
            LabelFileKind::PersistentRo,
            &mut self.persistent_ro_files,
            &mut seen_ids,
        )
    }

    // ========================================================================
    // Browser file lifecycle (create, import, remove, replace)
    // ========================================================================

    pub fn create_browser_file(&mut self, name: &str) -> Result<String, LabelStoreError> {
        let parsed = parse_local_file_name(name)?;
        if self.find_file_by_id(&parsed.id).is_some() {
            return Err(LabelStoreError::DuplicateFileId(parsed.id));
        }

        let file = LabelFile {
            id: parsed.id.clone(),
            name: parsed.name,
            kind: LabelFileKind::BrowserRw,
            editable: true,
            source_path: None,
            labels: HashMap::new(),
        };
        self.browser_rw_files.push(file);
        Ok(parsed.id)
    }

    pub fn import_browser_file(
        &mut self,
        name: &str,
        content: &str,
    ) -> Result<String, LabelStoreError> {
        let parsed = parse_local_file_name(name)?;
        if self.find_file_by_id(&parsed.id).is_some() {
            return Err(LabelStoreError::DuplicateFileId(parsed.id));
        }

        let labels = parse_jsonl_records(content)?;

        let file = LabelFile {
            id: parsed.id.clone(),
            name: parsed.name,
            kind: LabelFileKind::BrowserRw,
            editable: true,
            source_path: None,
            labels,
        };
        self.browser_rw_files.push(file);

        Ok(parsed.id)
    }

    pub fn replace_browser_file_content(
        &mut self,
        file_id: &str,
        content: &str,
    ) -> Result<(), LabelStoreError> {
        let file = self
            .find_file_mut(file_id)
            .ok_or_else(|| LabelStoreError::FileNotFound(file_id.to_string()))?;

        if file.kind != LabelFileKind::BrowserRw {
            return Err(LabelStoreError::NotBrowserFile(file_id.to_string()));
        }

        let labels = parse_jsonl_records(content)?;
        file.labels = labels;
        Ok(())
    }

    pub fn remove_browser_file(&mut self, file_id: &str) -> Result<(), LabelStoreError> {
        // Check if the file exists at all.
        let file = self
            .find_file_by_id(file_id)
            .ok_or_else(|| LabelStoreError::FileNotFound(file_id.to_string()))?;

        if file.kind != LabelFileKind::BrowserRw {
            return Err(LabelStoreError::NotBrowserFile(file_id.to_string()));
        }

        let idx = self
            .browser_rw_files
            .iter()
            .position(|f| f.id == file_id)
            .expect("file verified to exist above");
        self.browser_rw_files.remove(idx);
        Ok(())
    }

    // ========================================================================
    // Export (works on all kinds)
    // ========================================================================

    pub fn export_file(&self, file_id: &str) -> Result<String, LabelStoreError> {
        let file = self
            .find_file_by_id(file_id)
            .ok_or_else(|| LabelStoreError::FileNotFound(file_id.to_string()))?;
        Ok(export_map_to_jsonl(&file.labels))
    }

    // ========================================================================
    // Label mutation (PersistentRw + BrowserRw only)
    // ========================================================================

    pub fn set_label(
        &mut self,
        file_id: &str,
        label_type: Bip329Type,
        ref_id: String,
        label: String,
    ) -> Result<(), LabelStoreError> {
        if ref_id.trim().is_empty() {
            return Err(LabelStoreError::EmptyRef);
        }
        if label.trim().is_empty() {
            return Err(LabelStoreError::EmptyLabel);
        }

        let file = self
            .find_file_mut(file_id)
            .ok_or_else(|| LabelStoreError::FileNotFound(file_id.to_string()))?;

        if !file.editable {
            return Err(LabelStoreError::ReadOnlyFile(file_id.to_string()));
        }

        let key = (label_type, ref_id.clone());
        file.labels.insert(
            key,
            Bip329Record {
                label_type,
                ref_id,
                label,
                origin: None,
                spendable: None,
            },
        );

        // Auto-flush PersistentRw files to disk.
        self.flush_file(file_id)?;
        Ok(())
    }

    pub fn delete_label(
        &mut self,
        file_id: &str,
        label_type: Bip329Type,
        ref_id: &str,
    ) -> Result<(), LabelStoreError> {
        let file = self
            .find_file_mut(file_id)
            .ok_or_else(|| LabelStoreError::FileNotFound(file_id.to_string()))?;

        if !file.editable {
            return Err(LabelStoreError::ReadOnlyFile(file_id.to_string()));
        }

        let key = (label_type, ref_id.to_string());
        file.labels.remove(&key);

        self.flush_file(file_id)?;
        Ok(())
    }

    // ========================================================================
    // Query
    // ========================================================================

    pub fn list_files(&self) -> Vec<&LabelFile> {
        self.persistent_rw_files
            .iter()
            .chain(self.browser_rw_files.iter())
            .chain(self.persistent_ro_files.iter())
            .collect()
    }

    pub fn get_file(&self, file_id: &str) -> Option<&LabelFile> {
        self.find_file_by_id(file_id)
    }

    /// Returns labels for a specific `(type, ref)` in deterministic
    /// precedence order: PersistentRw → BrowserRw → PersistentRo.
    pub fn get_all_labels_for(
        &self,
        label_type: Bip329Type,
        ref_id: &str,
    ) -> Vec<(&LabelFile, &Bip329Record)> {
        let key = (label_type, ref_id.to_string());
        let mut results = Vec::new();

        for file in self
            .persistent_rw_files
            .iter()
            .chain(self.browser_rw_files.iter())
            .chain(self.persistent_ro_files.iter())
        {
            if let Some(record) = file.labels.get(&key) {
                results.push((file, record));
            }
        }

        results
    }

    // ========================================================================
    // Internal helpers
    // ========================================================================

    /// Collect all IDs across the three vecs for uniqueness checks.
    fn all_ids(&self) -> HashSet<String> {
        self.persistent_rw_files
            .iter()
            .chain(self.browser_rw_files.iter())
            .chain(self.persistent_ro_files.iter())
            .map(|f| f.id.clone())
            .collect()
    }

    fn find_file_by_id(&self, file_id: &str) -> Option<&LabelFile> {
        self.persistent_rw_files
            .iter()
            .chain(self.browser_rw_files.iter())
            .chain(self.persistent_ro_files.iter())
            .find(|f| f.id == file_id)
    }

    fn find_file_mut(&mut self, file_id: &str) -> Option<&mut LabelFile> {
        self.persistent_rw_files
            .iter_mut()
            .chain(self.browser_rw_files.iter_mut())
            .chain(self.persistent_ro_files.iter_mut())
            .find(|f| f.id == file_id)
    }

    /// Flush a file to disk if it has a `source_path` (PersistentRw).
    /// BrowserRw and PersistentRo files are no-ops as they have source_path None
    fn flush_file(&self, file_id: &str) -> Result<(), LabelStoreError> {
        let file = self
            .find_file_by_id(file_id)
            .ok_or_else(|| LabelStoreError::FileNotFound(file_id.to_string()))?;

        let Some(path) = &file.source_path else {
            return Ok(());
        };

        let content = export_map_to_jsonl(&file.labels);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(CoreError::Io)?;
        }
        std::fs::write(path, content).map_err(CoreError::Io)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::labels::jsonl::normalize_label_file_id;

    #[test]
    fn normalize_file_id_minimal() {
        // The new normalization only strips .jsonl and normalizes backslashes.
        assert_eq!(normalize_label_file_id("My Wallet"), "My Wallet");
        assert_eq!(normalize_label_file_id("wallet.jsonl"), "wallet");
        assert_eq!(
            normalize_label_file_id("Exchanges/Binance Hot"),
            "Exchanges/Binance Hot"
        );
        assert_eq!(
            normalize_label_file_id("path\\to\\file.jsonl"),
            "path/to/file"
        );
    }

    #[test]
    fn browser_file_lifecycle_and_export() {
        let mut store = LabelStore::new();
        let created = store
            .create_browser_file("wallet-a")
            .expect("create browser file should succeed");
        assert_eq!(created, "wallet-a");

        store
            .set_label(
                "wallet-a",
                Bip329Type::Tx,
                "txid1".to_string(),
                "Label 1".to_string(),
            )
            .expect("set label should succeed");

        let exported = store
            .export_file("wallet-a")
            .expect("export should succeed");
        assert!(exported.contains("\"label\":\"Label 1\""));

        store
            .remove_browser_file("wallet-a")
            .expect("delete browser file should succeed");
        assert!(
            store
                .list_files()
                .into_iter()
                .filter(|f| f.kind == LabelFileKind::BrowserRw)
                .count()
                == 0
        );
    }

    #[test]
    fn three_way_resolution_order() {
        let mut store = LabelStore::new();

        // Create a BrowserRw file with a label.
        store
            .import_browser_file(
                "browser-file",
                r#"{"type":"tx","ref":"txid1","label":"Browser label"}"#,
            )
            .expect("browser import should succeed");

        // Inject a PersistentRw file directly (simulating disk load).
        let rw_labels =
            parse_jsonl_records(r#"{"type":"tx","ref":"txid1","label":"PersistentRw label"}"#)
                .expect("rw parse should succeed");
        store.persistent_rw_files.push(LabelFile {
            id: "rw-file".into(),
            name: "rw-file".into(),
            kind: LabelFileKind::PersistentRw,
            editable: true,
            source_path: None,
            labels: rw_labels,
        });

        // Inject a PersistentRo file directly.
        let ro_labels =
            parse_jsonl_records(r#"{"type":"tx","ref":"txid1","label":"PersistentRo label"}"#)
                .expect("ro parse should succeed");
        store.persistent_ro_files.push(LabelFile {
            id: "ro-file".into(),
            name: "ro-file".into(),
            kind: LabelFileKind::PersistentRo,
            editable: false,
            source_path: None,
            labels: ro_labels,
        });

        let labels = store.get_all_labels_for(Bip329Type::Tx, "txid1");
        assert_eq!(labels.len(), 3);
        assert_eq!(labels[0].0.kind, LabelFileKind::PersistentRw);
        assert_eq!(labels[1].0.kind, LabelFileKind::BrowserRw);
        assert_eq!(labels[2].0.kind, LabelFileKind::PersistentRo);
    }

    #[test]
    fn typed_lookup_ignores_other_label_types() {
        let mut store = LabelStore::new();
        let file_id = store.create_browser_file("wallet").expect("create file");

        store
            .set_label(
                &file_id,
                Bip329Type::Tx,
                "abc".to_string(),
                "tx label".to_string(),
            )
            .expect("set tx label");
        store
            .set_label(
                &file_id,
                Bip329Type::Addr,
                "abc".to_string(),
                "addr label".to_string(),
            )
            .expect("set addr label");

        let tx_labels = store.get_all_labels_for(Bip329Type::Tx, "abc");
        assert_eq!(tx_labels.len(), 1);
        assert_eq!(tx_labels[0].1.label, "tx label");

        let addr_labels = store.get_all_labels_for(Bip329Type::Addr, "abc");
        assert_eq!(addr_labels.len(), 1);
        assert_eq!(addr_labels[0].1.label, "addr label");
    }

    #[test]
    fn set_label_on_persistent_ro_returns_error() {
        let mut store = LabelStore::new();

        let ro_labels =
            parse_jsonl_records(r#"{"type":"tx","ref":"txid1","label":"Read-only label"}"#)
                .expect("ro parse should succeed");
        store.persistent_ro_files.push(LabelFile {
            id: "ro-file".into(),
            name: "ro-file".into(),
            kind: LabelFileKind::PersistentRo,
            editable: false,
            source_path: None,
            labels: ro_labels,
        });

        let result = store.set_label(
            "ro-file",
            Bip329Type::Tx,
            "txid1".to_string(),
            "new label".to_string(),
        );
        assert!(matches!(result, Err(LabelStoreError::ReadOnlyFile(_))));
    }

    #[test]
    fn remove_persistent_rw_file_returns_not_browser_file() {
        let mut store = LabelStore::new();

        store.persistent_rw_files.push(LabelFile {
            id: "rw-file".into(),
            name: "rw-file".into(),
            kind: LabelFileKind::PersistentRw,
            editable: true,
            source_path: None,
            labels: HashMap::new(),
        });

        let result = store.remove_browser_file("rw-file");
        assert!(matches!(result, Err(LabelStoreError::NotBrowserFile(_))));
    }

    // -- error cases ----------------------------------------------------------

    #[test]
    fn create_file_with_empty_name_fails() {
        let mut store = LabelStore::new();
        assert!(matches!(
            store.create_browser_file(""),
            Err(LabelStoreError::EmptyFileName)
        ));
    }

    #[test]
    fn create_duplicate_file_fails() {
        let mut store = LabelStore::new();
        store.create_browser_file("wallet").expect("first create");
        assert!(matches!(
            store.create_browser_file("wallet"),
            Err(LabelStoreError::DuplicateFileId(_))
        ));
    }

    #[test]
    fn set_label_with_empty_ref_fails() {
        let mut store = LabelStore::new();
        store.create_browser_file("wallet").expect("create");
        assert!(matches!(
            store.set_label(
                "wallet",
                Bip329Type::Tx,
                "  ".to_string(),
                "label".to_string()
            ),
            Err(LabelStoreError::EmptyRef)
        ));
    }

    #[test]
    fn set_label_with_empty_label_fails() {
        let mut store = LabelStore::new();
        store.create_browser_file("wallet").expect("create");
        assert!(matches!(
            store.set_label(
                "wallet",
                Bip329Type::Tx,
                "txid1".to_string(),
                "  ".to_string()
            ),
            Err(LabelStoreError::EmptyLabel)
        ));
    }

    #[test]
    fn remove_nonexistent_file_fails() {
        let mut store = LabelStore::new();
        assert!(matches!(
            store.remove_browser_file("no-such-file"),
            Err(LabelStoreError::FileNotFound(_))
        ));
    }

    #[test]
    fn export_nonexistent_file_fails() {
        let store = LabelStore::new();
        assert!(matches!(
            store.export_file("no-such-file"),
            Err(LabelStoreError::FileNotFound(_))
        ));
    }
}