blossom-rs 0.5.6

Full-featured Blossom (BUD-01) blob storage library for Rust — embeddable server, async client, BIP-340 Nostr auth
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
//! Iroh QUIC client for Blossom blob operations.
//!
//! Connects to a Blossom peer by node ID and performs blob operations
//! over the `/blossom/1` ALPN protocol.

use std::collections::HashMap;
use std::sync::Mutex;

use iroh::endpoint::{Connection, Endpoint};
use iroh::{EndpointAddr, EndpointId};
use tracing::{info, instrument};

use super::iroh_transport::BLOSSOM_ALPN;
use super::wire::{self, Op, Request, Response, Status};
use crate::auth::{
    auth_header_value, build_blossom_auth, build_blossom_auth_with_extra_tags, BlossomSigner,
};
use crate::locks::LockRecord;
use crate::protocol::{sha256_hex, BlobDescriptor};

/// Iroh-based Blossom client.
///
/// Connects to peers by iroh node ID over QUIC. Caches connections
/// per node ID for reuse across operations.
pub struct IrohBlossomClient {
    endpoint: Endpoint,
    signer: Box<dyn BlossomSigner>,
    /// Cached connections by node endpoint ID.
    connections: Mutex<HashMap<EndpointId, Connection>>,
}

impl IrohBlossomClient {
    /// Create a new iroh client with the given endpoint and signer.
    pub fn new(endpoint: Endpoint, signer: impl BlossomSigner + 'static) -> Self {
        Self {
            endpoint,
            signer: Box::new(signer),
            connections: Mutex::new(HashMap::new()),
        }
    }

    /// Connect to a remote Blossom peer, reusing cached connections.
    async fn connect(&self, addr: EndpointAddr) -> Result<Connection, String> {
        let node_id = addr.id;

        // Check cache.
        if let Some(conn) = self.connections.lock().unwrap().get(&node_id) {
            // Verify connection is still alive.
            if conn.close_reason().is_none() {
                return Ok(conn.clone());
            }
        }

        // New connection.
        let conn = self
            .endpoint
            .connect(addr, BLOSSOM_ALPN)
            .await
            .map_err(|e| format!("iroh connect: {e}"))?;

        self.connections
            .lock()
            .unwrap()
            .insert(node_id, conn.clone());

        Ok(conn)
    }

    /// Upload a blob to a remote peer.
    #[instrument(name = "blossom.iroh.client.upload", skip_all, fields(blob.size = data.len()))]
    pub async fn upload(&self, addr: EndpointAddr, data: &[u8]) -> Result<BlobDescriptor, String> {
        self.upload_with_type(addr, data, "application/octet-stream")
            .await
    }

    /// Upload a blob with an explicit content type.
    #[instrument(name = "blossom.iroh.client.upload", skip_all, fields(blob.size = data.len()))]
    pub async fn upload_with_type(
        &self,
        addr: EndpointAddr,
        data: &[u8],
        content_type: &str,
    ) -> Result<BlobDescriptor, String> {
        let our_sha256 = sha256_hex(data);
        let auth_event =
            build_blossom_auth(self.signer.as_ref(), "upload", Some(&our_sha256), None, "");
        let auth_header = auth_header_value(&auth_event);

        let conn = self.connect(addr).await?;
        let (mut send, mut recv) = conn
            .open_bi()
            .await
            .map_err(|e| format!("open stream: {e}"))?;

        // Send request.
        let req = Request {
            op: Op::Upload,
            sha256: String::new(),
            pubkey: String::new(),
            auth: auth_header,
            content_type: content_type.to_string(),
            body_len: data.len() as u64,
            ..Default::default()
        };
        send.write_all(&wire::encode_request(&req))
            .await
            .map_err(|e| format!("write request: {e}"))?;
        send.write_all(data)
            .await
            .map_err(|e| format!("write body: {e}"))?;
        send.finish().map_err(|e| format!("finish: {e}"))?;

        // Read response.
        let (resp, _leftover) = read_response(&mut recv).await?;
        if resp.status != Status::Ok {
            return Err(format!("upload failed: {}", resp.error));
        }

        let desc: BlobDescriptor =
            serde_json::from_value(resp.descriptor.ok_or("no descriptor in upload response")?)
                .map_err(|e| format!("parse descriptor: {e}"))?;

        if desc.sha256 != our_sha256 {
            return Err(format!(
                "SHA256 mismatch: server={}, ours={}",
                desc.sha256, our_sha256
            ));
        }

        info!(blob.sha256 = %desc.sha256, blob.size = desc.size, "blob uploaded via iroh");
        Ok(desc)
    }

    #[allow(clippy::too_many_arguments)]
    #[instrument(name = "blossom.iroh.client.upload_lfs", skip_all, fields(
        blob.size = data.len(),
        blob.sha256,
        lfs.path = path,
        lfs.repo = repo,
    ))]
    pub async fn upload_lfs(
        &self,
        addr: EndpointAddr,
        data: &[u8],
        content_type: &str,
        path: &str,
        repo: &str,
        base_sha256: Option<&str>,
        is_manifest: bool,
    ) -> Result<BlobDescriptor, String> {
        let our_sha256 = sha256_hex(data);
        tracing::Span::current().record("blob.sha256", our_sha256.as_str());

        let mut extra_tags = vec![
            vec!["t".into(), "lfs".into()],
            vec!["path".into(), path.into()],
            vec!["repo".into(), repo.into()],
        ];
        if let Some(base) = base_sha256 {
            extra_tags.push(vec!["base".into(), base.into()]);
        }
        if is_manifest {
            extra_tags.push(vec!["manifest".into()]);
        }

        let auth_event = build_blossom_auth_with_extra_tags(
            self.signer.as_ref(),
            "upload",
            Some(&our_sha256),
            None,
            "",
            &extra_tags,
        );
        let auth_header = auth_header_value(&auth_event);

        let conn = self.connect(addr).await?;
        let (mut send, mut recv) = conn
            .open_bi()
            .await
            .map_err(|e| format!("open stream: {e}"))?;

        let req = Request {
            op: Op::Upload,
            auth: auth_header,
            content_type: content_type.to_string(),
            body_len: data.len() as u64,
            lfs_path: path.to_string(),
            lfs_repo: repo.to_string(),
            lfs_base: base_sha256.unwrap_or("").to_string(),
            lfs_manifest: is_manifest,
            ..Default::default()
        };
        send.write_all(&wire::encode_request(&req))
            .await
            .map_err(|e| format!("write request: {e}"))?;
        send.write_all(data)
            .await
            .map_err(|e| format!("write body: {e}"))?;
        send.finish().map_err(|e| format!("finish: {e}"))?;

        let (resp, _) = read_response(&mut recv).await?;
        if resp.status != Status::Ok {
            return Err(format!("upload_lfs failed: {}", resp.error));
        }

        let desc: BlobDescriptor = serde_json::from_value(
            resp.descriptor
                .ok_or("no descriptor in upload_lfs response")?,
        )
        .map_err(|e| format!("parse descriptor: {e}"))?;

        if desc.sha256 != our_sha256 {
            return Err(format!(
                "SHA256 mismatch: server={}, ours={}",
                desc.sha256, our_sha256
            ));
        }

        info!(
            blob.sha256 = %desc.sha256,
            blob.size = desc.size,
            lfs.path = %path,
            "LFS blob uploaded via iroh"
        );
        Ok(desc)
    }

    /// Download a blob from a remote peer.
    #[instrument(name = "blossom.iroh.client.download", skip_all, fields(blob.sha256 = %sha256))]
    pub async fn download(&self, addr: EndpointAddr, sha256: &str) -> Result<Vec<u8>, String> {
        let auth_event = build_blossom_auth(self.signer.as_ref(), "get", None, None, "");
        let _auth_header = auth_header_value(&auth_event);

        let conn = self.connect(addr).await?;
        let (mut send, mut recv) = conn
            .open_bi()
            .await
            .map_err(|e| format!("open stream: {e}"))?;

        let req = Request {
            op: Op::Get,
            sha256: sha256.to_string(),
            pubkey: String::new(),
            auth: String::new(),
            content_type: String::new(),
            body_len: 0,
            ..Default::default()
        };
        send.write_all(&wire::encode_request(&req))
            .await
            .map_err(|e| format!("write: {e}"))?;
        send.finish().map_err(|e| format!("finish: {e}"))?;

        let (resp, leftover) = read_response(&mut recv).await?;
        if resp.status != Status::Ok {
            return Err(format!("download failed: {}", resp.error));
        }

        // Combine leftover bytes (read past newline) with remaining body.
        let mut data = leftover;
        let remaining = (resp.body_len as usize).saturating_sub(data.len());
        if remaining > 0 {
            let mut rest = vec![0u8; remaining];
            recv.read_exact(&mut rest)
                .await
                .map_err(|e| format!("read body: {e}"))?;
            data.extend_from_slice(&rest);
        }
        data.truncate(resp.body_len as usize);

        // Verify integrity.
        let actual = sha256_hex(&data);
        if actual != sha256 {
            return Err(format!(
                "SHA256 mismatch: expected={}, actual={}",
                sha256, actual
            ));
        }

        info!(blob.sha256 = %sha256, blob.size = data.len(), "blob downloaded via iroh");
        Ok(data)
    }

    /// Check if a blob exists on a remote peer.
    #[instrument(name = "blossom.iroh.client.exists", skip_all, fields(blob.sha256 = %sha256))]
    pub async fn exists(&self, addr: EndpointAddr, sha256: &str) -> Result<bool, String> {
        let conn = self.connect(addr).await?;
        let (mut send, mut recv) = conn
            .open_bi()
            .await
            .map_err(|e| format!("open stream: {e}"))?;

        let req = Request {
            op: Op::Head,
            sha256: sha256.to_string(),
            pubkey: String::new(),
            auth: String::new(),
            content_type: String::new(),
            body_len: 0,
            ..Default::default()
        };
        send.write_all(&wire::encode_request(&req))
            .await
            .map_err(|e| format!("write: {e}"))?;
        send.finish().map_err(|e| format!("finish: {e}"))?;

        let (resp, _leftover) = read_response(&mut recv).await?;
        Ok(resp.status == Status::Ok)
    }

    /// Delete a blob on a remote peer (requires auth).
    #[instrument(name = "blossom.iroh.client.delete", skip_all, fields(blob.sha256 = %sha256))]
    pub async fn delete(&self, addr: EndpointAddr, sha256: &str) -> Result<bool, String> {
        let auth_event = build_blossom_auth(self.signer.as_ref(), "delete", None, None, "");
        let auth_header = auth_header_value(&auth_event);

        let conn = self.connect(addr).await?;
        let (mut send, mut recv) = conn
            .open_bi()
            .await
            .map_err(|e| format!("open stream: {e}"))?;

        let req = Request {
            op: Op::Delete,
            sha256: sha256.to_string(),
            pubkey: String::new(),
            auth: auth_header,
            content_type: String::new(),
            body_len: 0,
            ..Default::default()
        };
        send.write_all(&wire::encode_request(&req))
            .await
            .map_err(|e| format!("write: {e}"))?;
        send.finish().map_err(|e| format!("finish: {e}"))?;

        let (resp, _leftover) = read_response(&mut recv).await?;
        Ok(resp.status == Status::Ok)
    }

    /// List blobs uploaded by a pubkey on a remote peer.
    #[instrument(name = "blossom.iroh.client.list", skip_all, fields(list.pubkey = %pubkey))]
    pub async fn list(
        &self,
        addr: EndpointAddr,
        pubkey: &str,
    ) -> Result<Vec<BlobDescriptor>, String> {
        let conn = self.connect(addr).await?;
        let (mut send, mut recv) = conn
            .open_bi()
            .await
            .map_err(|e| format!("open stream: {e}"))?;

        let req = Request {
            op: Op::List,
            sha256: String::new(),
            pubkey: pubkey.to_string(),
            auth: String::new(),
            content_type: String::new(),
            body_len: 0,
            ..Default::default()
        };
        send.write_all(&wire::encode_request(&req))
            .await
            .map_err(|e| format!("write: {e}"))?;
        send.finish().map_err(|e| format!("finish: {e}"))?;

        let (resp, leftover) = read_response(&mut recv).await?;
        if resp.status != Status::Ok {
            return Err(format!("list failed: {}", resp.error));
        }

        let mut data = leftover;
        let remaining = (resp.body_len as usize).saturating_sub(data.len());
        if remaining > 0 {
            let mut rest = vec![0u8; remaining];
            recv.read_exact(&mut rest)
                .await
                .map_err(|e| format!("read body: {e}"))?;
            data.extend_from_slice(&rest);
        }
        data.truncate(resp.body_len as usize);

        info!(list.pubkey = %pubkey, "list via iroh");
        serde_json::from_slice(&data).map_err(|e| format!("parse list: {e}"))
    }

    /// Upload a file from disk without buffering in memory.
    ///
    /// First pass computes SHA256. Second pass streams file to QUIC
    /// in 256KB chunks.
    #[instrument(name = "blossom.iroh.client.upload_file", skip_all, fields(
        file.path = %path.display(),
        blob.sha256,
        blob.size,
    ))]
    pub async fn upload_file(
        &self,
        addr: EndpointAddr,
        path: &std::path::Path,
        content_type: &str,
    ) -> Result<BlobDescriptor, String> {
        use crate::protocol::STREAM_CHUNK_SIZE;
        use tokio::io::AsyncReadExt;

        let file_meta = tokio::fs::metadata(path)
            .await
            .map_err(|e| format!("stat file: {e}"))?;
        let file_size = file_meta.len();

        // First pass: compute SHA256.
        let our_sha256 = tokio::task::block_in_place(|| {
            let mut f = std::fs::File::open(path).map_err(|e| format!("open file: {e}"))?;
            let (hash, _) =
                crate::protocol::sha256_stream(&mut f).map_err(|e| format!("hash file: {e}"))?;
            Ok::<_, String>(hash)
        })?;

        tracing::Span::current().record("blob.sha256", our_sha256.as_str());
        tracing::Span::current().record("blob.size", file_size);

        let auth_event =
            build_blossom_auth(self.signer.as_ref(), "upload", Some(&our_sha256), None, "");
        let auth_header = auth_header_value(&auth_event);

        let conn = self.connect(addr).await?;
        let (mut send, mut recv) = conn
            .open_bi()
            .await
            .map_err(|e| format!("open stream: {e}"))?;

        // Send request header.
        let req = Request {
            op: Op::Upload,
            sha256: String::new(),
            pubkey: String::new(),
            auth: auth_header,
            content_type: content_type.to_string(),
            body_len: file_size,
            ..Default::default()
        };
        send.write_all(&wire::encode_request(&req))
            .await
            .map_err(|e| format!("write request: {e}"))?;

        // Second pass: stream file in chunks.
        let mut file = tokio::fs::File::open(path)
            .await
            .map_err(|e| format!("open file: {e}"))?;
        let mut buf = vec![0u8; STREAM_CHUNK_SIZE];
        loop {
            let n = file
                .read(&mut buf)
                .await
                .map_err(|e| format!("read file: {e}"))?;
            if n == 0 {
                break;
            }
            send.write_all(&buf[..n])
                .await
                .map_err(|e| format!("write body: {e}"))?;
        }
        send.finish().map_err(|e| format!("finish: {e}"))?;

        // Read response.
        let (resp, _leftover) = read_response(&mut recv).await?;
        if resp.status != Status::Ok {
            return Err(format!("upload failed: {}", resp.error));
        }

        let desc: BlobDescriptor =
            serde_json::from_value(resp.descriptor.ok_or("no descriptor in upload response")?)
                .map_err(|e| format!("parse descriptor: {e}"))?;

        if desc.sha256 != our_sha256 {
            return Err(format!(
                "SHA256 mismatch: server={}, ours={}",
                desc.sha256, our_sha256
            ));
        }

        info!(blob.sha256 = %desc.sha256, blob.size = desc.size, "file uploaded via iroh (streaming)");
        Ok(desc)
    }
}

impl crate::traits::BlobClient for IrohBlossomClient {
    type Address = EndpointAddr;

    async fn upload(
        &self,
        addr: &EndpointAddr,
        data: &[u8],
        content_type: &str,
    ) -> Result<BlobDescriptor, String> {
        self.upload_with_type(addr.clone(), data, content_type)
            .await
    }

    async fn download(&self, addr: &EndpointAddr, sha256: &str) -> Result<Vec<u8>, String> {
        self.download(addr.clone(), sha256).await
    }

    async fn exists(&self, addr: &EndpointAddr, sha256: &str) -> Result<bool, String> {
        self.exists(addr.clone(), sha256).await
    }

    async fn delete(&self, addr: &EndpointAddr, sha256: &str) -> Result<bool, String> {
        self.delete(addr.clone(), sha256).await
    }

    async fn list(&self, addr: &EndpointAddr, pubkey: &str) -> Result<Vec<BlobDescriptor>, String> {
        self.list(addr.clone(), pubkey).await
    }

    async fn upload_file(
        &self,
        addr: &EndpointAddr,
        path: &std::path::Path,
        content_type: &str,
    ) -> Result<BlobDescriptor, String> {
        self.upload_file(addr.clone(), path, content_type).await
    }
}

impl IrohBlossomClient {
    pub async fn create_lock(
        &self,
        addr: &EndpointAddr,
        repo_id: &str,
        path: &str,
    ) -> Result<LockRecord, String> {
        let auth_event = build_blossom_auth(self.signer.as_ref(), "lock", None, None, "");
        let auth_header = auth_header_value(&auth_event);

        let conn = self.connect(addr.clone()).await?;
        let (mut send, mut recv) = conn.open_bi().await.map_err(|e| format!("open_bi: {e}"))?;

        let req = Request {
            op: Op::LockCreate,
            auth: auth_header,
            repo_id: repo_id.to_string(),
            lock_path: path.to_string(),
            ..Default::default()
        };
        send.write_all(&wire::encode_request(&req))
            .await
            .map_err(|e| format!("send: {e}"))?;
        send.finish().map_err(|e| format!("finish: {e}"))?;

        let (resp, _) = read_response(&mut recv).await?;
        match resp.status {
            Status::Ok => resp
                .descriptor
                .ok_or_else(|| "missing descriptor".to_string())
                .and_then(|v| {
                    serde_json::from_value::<LockRecord>(v).map_err(|e| format!("parse lock: {e}"))
                }),
            Status::Conflict => Err("path already locked".to_string()),
            Status::Unauthorized => Err("unauthorized".to_string()),
            Status::Forbidden => Err("forbidden".to_string()),
            Status::NotFound => Err("lock support not configured".to_string()),
            Status::Error => Err(resp.error.clone()),
        }
    }

    pub async fn delete_lock(
        &self,
        addr: &EndpointAddr,
        repo_id: &str,
        lock_id: &str,
        force: bool,
    ) -> Result<LockRecord, String> {
        let auth_event = build_blossom_auth(self.signer.as_ref(), "lock", None, None, "");
        let auth_header = auth_header_value(&auth_event);

        let conn = self.connect(addr.clone()).await?;
        let (mut send, mut recv) = conn.open_bi().await.map_err(|e| format!("open_bi: {e}"))?;

        let req = Request {
            op: Op::LockDelete,
            auth: auth_header,
            repo_id: repo_id.to_string(),
            lock_id: lock_id.to_string(),
            force,
            ..Default::default()
        };
        send.write_all(&wire::encode_request(&req))
            .await
            .map_err(|e| format!("send: {e}"))?;
        send.finish().map_err(|e| format!("finish: {e}"))?;

        let (resp, _) = read_response(&mut recv).await?;
        match resp.status {
            Status::Ok => resp
                .descriptor
                .ok_or_else(|| "missing descriptor".to_string())
                .and_then(|v| {
                    serde_json::from_value::<LockRecord>(v).map_err(|e| format!("parse lock: {e}"))
                }),
            Status::NotFound => Err("lock not found".to_string()),
            Status::Forbidden => Err(resp.error.clone()),
            Status::Unauthorized => Err("unauthorized".to_string()),
            Status::Error => Err(resp.error.clone()),
            _ => Err(format!("unexpected status: {:?}", resp.status)),
        }
    }

    pub async fn list_locks(
        &self,
        addr: &EndpointAddr,
        repo_id: &str,
        cursor: Option<&str>,
        limit: Option<u32>,
    ) -> Result<(Vec<LockRecord>, Option<String>), String> {
        let req = Request {
            op: Op::LockList,
            repo_id: repo_id.to_string(),
            cursor: cursor.unwrap_or("").to_string(),
            limit: limit.unwrap_or(0),
            ..Default::default()
        };

        let conn = self.connect(addr.clone()).await?;
        let (mut send, mut recv) = conn.open_bi().await.map_err(|e| format!("open_bi: {e}"))?;

        send.write_all(&wire::encode_request(&req))
            .await
            .map_err(|e| format!("send: {e}"))?;
        send.finish().map_err(|e| format!("finish: {e}"))?;

        let (resp, _) = read_response(&mut recv).await?;
        match resp.status {
            Status::Ok => {
                let desc = resp
                    .descriptor
                    .ok_or_else(|| "missing descriptor".to_string())?;
                let locks: Vec<LockRecord> = desc
                    .get("locks")
                    .ok_or_else(|| "missing locks field".to_string())
                    .and_then(|v| {
                        serde_json::from_value(v.clone()).map_err(|e| format!("parse: {e}"))
                    })?;
                let next_cursor = desc
                    .get("next_cursor")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());
                Ok((locks, next_cursor))
            }
            Status::NotFound => Err("lock support not configured".to_string()),
            Status::Error => Err(resp.error.clone()),
            _ => Err(format!("unexpected status: {:?}", resp.status)),
        }
    }

    pub async fn verify_locks(
        &self,
        addr: &EndpointAddr,
        repo_id: &str,
        cursor: Option<&str>,
        limit: Option<u32>,
    ) -> Result<(Vec<LockRecord>, Vec<LockRecord>, Option<String>), String> {
        let auth_event = build_blossom_auth(self.signer.as_ref(), "lock", None, None, "");
        let auth_header = auth_header_value(&auth_event);

        let conn = self.connect(addr.clone()).await?;
        let (mut send, mut recv) = conn.open_bi().await.map_err(|e| format!("open_bi: {e}"))?;

        let req = Request {
            op: Op::LockVerify,
            auth: auth_header,
            repo_id: repo_id.to_string(),
            cursor: cursor.unwrap_or("").to_string(),
            limit: limit.unwrap_or(0),
            ..Default::default()
        };
        send.write_all(&wire::encode_request(&req))
            .await
            .map_err(|e| format!("send: {e}"))?;
        send.finish().map_err(|e| format!("finish: {e}"))?;

        let (resp, _) = read_response(&mut recv).await?;
        match resp.status {
            Status::Ok => {
                let desc = resp
                    .descriptor
                    .ok_or_else(|| "missing descriptor".to_string())?;
                let ours: Vec<LockRecord> = desc
                    .get("ours")
                    .ok_or_else(|| "missing ours field".to_string())
                    .and_then(|v| {
                        serde_json::from_value(v.clone()).map_err(|e| format!("parse ours: {e}"))
                    })?;
                let theirs: Vec<LockRecord> = desc
                    .get("theirs")
                    .ok_or_else(|| "missing theirs field".to_string())
                    .and_then(|v| {
                        serde_json::from_value(v.clone()).map_err(|e| format!("parse theirs: {e}"))
                    })?;
                let next_cursor = desc
                    .get("next_cursor")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());
                Ok((ours, theirs, next_cursor))
            }
            Status::NotFound => Err("lock support not configured".to_string()),
            Status::Unauthorized => Err("unauthorized".to_string()),
            Status::Error => Err(resp.error.clone()),
            _ => Err(format!("unexpected status: {:?}", resp.status)),
        }
    }
}

/// Read a response from a QUIC recv stream.
/// Returns the parsed response and any leftover bytes (body data read past the newline).
async fn read_response(
    recv: &mut iroh::endpoint::RecvStream,
) -> Result<(Response, Vec<u8>), String> {
    let mut buf = Vec::with_capacity(4096);
    let mut tmp = [0u8; 4096];
    loop {
        match recv.read(&mut tmp).await {
            Ok(Some(n)) => {
                buf.extend_from_slice(&tmp[..n]);
                if buf.contains(&b'\n') {
                    break;
                }
            }
            Ok(None) => break,
            Err(e) => return Err(format!("read response: {e}")),
        }
    }

    let (resp, consumed) = wire::decode_line::<Response>(&buf)?;
    let leftover = buf[consumed..].to_vec();
    Ok((resp, leftover))
}