zc2 0.0.52

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//! Publish-lock task distribution for P2P broker mesh.
//!
//! Instead of brokers calling remote workers directly, a broker that receives a
//! request it cannot serve locally **publishes** the task to its peers.  A peer
//! whose local worker matches the requirements and whose price aligns **locks**
//! the task, executes it on its own verified worker, and returns the result.
//!
//! This guarantees that only brokers with real, verified workers can execute
//! tasks — eliminating phantom-worker and phantom-owner problems by design.

use serde::{Deserialize, Serialize};

/// Task offer broadcast by the originating broker to peers.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskOffer {
    /// Unique task identifier (same as the original request_id)
    pub task_id: String,
    /// Serialised request body (opaque bytes, base64-encoded for JSON transport)
    pub payload_b64: String,
    /// Maximum price the requester is willing to pay (yen/hr).
    /// A peer will only accept if its worker's price_per_hour ≤ this value.
    pub max_price_per_hour: f64,
    /// Estimated duration in seconds (used for cost estimation)
    pub estimated_duration_secs: f64,
    /// Hard timeout — peer must abort execution after this many seconds.
    pub timeout_secs: f64,
    /// Minimum CPU cores required
    #[serde(default = "default_cpus")]
    pub cpus: f64,
    /// Minimum memory in bytes
    #[serde(default = "default_memory")]
    pub memory_bytes: u64,
    /// GPUs required
    #[serde(default)]
    pub gpus: u32,
    /// Minimum VRAM per GPU in GiB. Absent (every offer before this field)
    /// means no floor; a receiver that does not know it ignores it, so the
    /// router's own VRAM match stays the only check there.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_vram_gb: Option<u32>,
    /// Required worker type (optional tag filter)
    #[serde(default)]
    pub worker_type: Option<String>,
    /// Required tags (all must match)
    #[serde(default)]
    pub tags: Vec<String>,
    /// The user_id being charged for this task
    pub requester_user_id: String,
    /// The originating broker's node name (for audit)
    pub source_broker: String,
    /// Shared peer secret (ZAKURO_PEER_KEY) for in-protocol QUIC auth.
    /// Empty when no key is configured; validated by the receiving broker.
    #[serde(default)]
    pub peer_key: String,
    /// Two-phase offer: when true the receiver RESERVES (does not execute) and
    /// returns a TaskAccept, awaiting a commit/cancel. False/absent = today's
    /// execute-on-offer. Set true only for two-phase-capable peers when the
    /// ZAKURO_TWO_PHASE_OFFERS flag is on.
    #[serde(default)]
    pub two_phase: bool,
    /// Dashboard-signed job voucher authorizing this task's spend (verbatim JSON
    /// bytes the dashboard signed). Empty/absent when the requester has no
    /// dashboard (local/standalone) or vouchers are not in use.
    #[serde(default)]
    pub voucher_signed_json: String,
    /// Ed25519 signature (b64) over `voucher_signed_json`.
    #[serde(default)]
    pub voucher_sig: String,
    /// Pin execution to this worker (bare name). A receiving peer accepts the
    /// offer only if it owns this worker. Empty = normal strategy routing.
    #[serde(default)]
    pub target_worker: String,
    /// Pin execution to this NODE, as `zc://node-<fp>` or the bare
    /// fingerprint. Empty = any peer may take it.
    ///
    /// Unlike [`target_worker`](Self::target_worker) — which is a client
    /// naming someone else's worker, and is deliberately ignored — this names
    /// a whole broker, which is the one thing a requester legitimately
    /// chooses. The dispatcher offers a pinned task to that peer alone, and
    /// the receiving peer refuses an offer pinned to a node it is not, so the
    /// pin holds even if a relay sends it to the wrong place.
    #[serde(default)]
    pub target_node: String,
    /// Sender's per-node signature (ZC-0007) for an offer that travels over
    /// QUIC, where there are no `X-Node-*` headers to carry it. Additive and
    /// optional (frozen wire, ZC-0009): absent on HTTP offers and from older
    /// senders, and ignored by older receivers. See [`TaskOffer::sign_for_quic`].
    /// The money unit the sender settles in (ADR 0027). A QUIC offer without
    /// `"jpy"` comes from a pre-yen node and is refused.
    #[serde(default)]
    pub currency: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node_sig: Option<OfferNodeSig>,
}

/// The four `X-Node-*` header values of a signed `/peer/*` request, carried
/// inside a QUIC [`TaskOffer`] instead.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OfferNodeSig {
    pub node_id: String,
    pub sig: String,
    pub nonce: String,
    pub ts: u64,
}

/// Path a QUIC offer signature is made over, in place of the HTTP route. It is
/// distinct from `/peer/tasks/offer` so a QUIC signature never verifies as an
/// HTTP request signature, or the reverse.
pub const QUIC_OFFER_SIGN_PATH: &str = "/quic/tasks/offer";

/// The bytes a QUIC offer signature covers: the offer's JSON as sent, minus the
/// `node_sig` member, with object keys sorted and no whitespace. Sender and
/// receiver both derive it from the serialized message, so fields one side does
/// not know about are still covered. `None` if `raw` is not a JSON object.
pub fn quic_offer_sign_bytes(raw: &[u8]) -> Option<Vec<u8>> {
    let mut v: serde_json::Value = serde_json::from_slice(raw).ok()?;
    v.as_object_mut()?.remove("node_sig");
    v.sort_all_objects();
    serde_json::to_vec(&v).ok()
}

impl TaskOffer {
    /// The offer hash a voucher binds (`Voucher::offer_hash`): lowercase hex
    /// SHA-256 over this canonical byte string, which both sides compute from
    /// the offer fields they see.
    ///
    /// ```text
    /// zakuro-offer:v1\n
    /// task_id=<len>:<task_id>\n
    /// payload_sha256=64:<sha256 hex of the UTF-8 bytes of payload_b64>\n
    /// max_price_per_hour=16:<f64 bits, 16 lowercase hex>\n
    /// estimated_duration_secs=16:<f64 bits, 16 lowercase hex>\n
    /// requester_user_id=<len>:<requester_user_id>\n
    /// currency=<len>:<currency>\n
    /// ```
    ///
    /// `<len>` is the byte length of the value in decimal, so no value can run
    /// into the next field. Floats go in as their IEEE-754 bits (the exact
    /// value both sides parsed, no text formatting to disagree on). The
    /// voucher fields themselves, `two_phase`, `target_*`, `peer_key` and
    /// `node_sig` are NOT covered: the voucher travels inside the offer, and
    /// the rest are set per send. The requester mints after building the offer
    /// with these fields final (they do not change in dispatch).
    pub fn binding_hash(&self) -> String {
        fn field(out: &mut String, name: &str, value: &str) {
            out.push_str(&format!("{name}={}:{value}\n", value.len()));
        }
        let mut c = String::from("zakuro-offer:v1\n");
        field(&mut c, "task_id", &self.task_id);
        field(
            &mut c,
            "payload_sha256",
            &super::node_identity::sha256_hex(self.payload_b64.as_bytes()),
        );
        field(
            &mut c,
            "max_price_per_hour",
            &format!("{:016x}", self.max_price_per_hour.to_bits()),
        );
        field(
            &mut c,
            "estimated_duration_secs",
            &format!("{:016x}", self.estimated_duration_secs.to_bits()),
        );
        field(&mut c, "requester_user_id", &self.requester_user_id);
        field(&mut c, "currency", &self.currency);
        super::node_identity::sha256_hex(c.as_bytes())
    }

    /// Sign this offer for QUIC with this node's key, the way `PeerClient`
    /// signs an HTTP `/peer/*` request (`NodeKey::sign_headers`), over
    /// [`quic_offer_sign_bytes`] and [`QUIC_OFFER_SIGN_PATH`]. Replaces any
    /// earlier signature, so set every other field first.
    pub fn sign_for_quic(&mut self, key: &super::node_identity::NodeKey) {
        self.node_sig = None;
        let raw = serde_json::to_vec(self).unwrap_or_default();
        let Some(body) = quic_offer_sign_bytes(&raw) else {
            return;
        };
        let hdrs = key.sign_headers("POST", QUIC_OFFER_SIGN_PATH, &body);
        let get = |name: &str| {
            hdrs.iter()
                .find(|(k, _)| k == name)
                .map(|(_, v)| v.clone())
                .unwrap_or_default()
        };
        self.node_sig = Some(OfferNodeSig {
            node_id: get("X-Node-Id"),
            sig: get("X-Node-Sig"),
            nonce: get("X-Node-Nonce"),
            ts: get("X-Node-Ts").parse().unwrap_or(0),
        });
    }

    /// The offer's QUIC signature as the `X-Node-*` headers the HTTP gate
    /// reads. Empty when the offer is unsigned.
    pub fn quic_sig_headers(&self) -> Vec<(String, String)> {
        match &self.node_sig {
            Some(s) => vec![
                ("X-Node-Id".to_string(), s.node_id.clone()),
                ("X-Node-Sig".to_string(), s.sig.clone()),
                ("X-Node-Nonce".to_string(), s.nonce.clone()),
                ("X-Node-Ts".to_string(), s.ts.to_string()),
            ],
            None => Vec::new(),
        }
    }
}

/// Normalize a zc:// target to its bare name (`zc://worker-x` → `worker-x`,
/// `zc://node-i9` → `node-i9`). Pass-through for a bare name.
pub fn norm_target(s: &str) -> String {
    s.strip_prefix("zc://").unwrap_or(s).to_string()
}

fn default_cpus() -> f64 {
    1.0
}
fn default_memory() -> u64 {
    1024 * 1024 * 1024
}

/// Result returned by the peer that locked and executed the task.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskResult {
    /// Echoed task identifier
    pub task_id: String,
    /// Response payload (base64-encoded)
    pub payload_b64: String,
    /// Actual wall-clock execution time (ms)
    pub duration_ms: f64,
    /// Actual cost charged (yen)
    pub actual_cost: f64,
    /// Name of the worker that executed the task
    pub worker_name: String,
    /// IP-free key-derived handle of the worker that executed the task
    /// (`zc://worker-<node_fp>-<slot>`, i.e. `Worker::zc_uri()`).
    /// Kept under its historical name — it has no `#[serde(default)]`, so an
    /// older peer would fail to deserialize a result that omitted it. The
    /// VALUE changed; the schema did not.
    pub worker_uri: String,
    /// Worker's price_per_hour (yen/hr)
    pub price_per_hour: f64,
    /// The peer broker's verified owner_user_id (the entity that earns money)
    pub executor_owner: String,
    /// Worker process ID (from response header X-Zakuro-Pid, if present)
    #[serde(default)]
    pub worker_pid: Option<String>,
    /// Executing node's key-derived identity (`zc://node-<fp>`). Empty from a
    /// pre-identity peer; settlement then falls back to the locally-stamped
    /// `Worker::node_fp` (see `server.rs::executor_fp`).
    ///
    /// # UNSIGNED — attacker-controlled. Never a settlement input as-is.
    ///
    /// This field sits OUTSIDE the frozen [`receipt_bytes`], so `executor_sig`
    /// does not cover it: a malicious peer can put **any** node's identity here
    /// for free, at no cost and with no detectable tampering. It is a *claim*,
    /// not a proof. Treating it as an identity would let a peer redirect another
    /// node's earnings to itself.
    ///
    /// As of this commit nothing consumes it and settlement resolves via the
    /// locally-stamped `Worker::node_fp` (`server.rs::executor_fp`), so the
    /// exposure is latent, not live. The first consumer MUST apply both guards:
    ///
    /// 1. **Derive trust from the signature, not the claim.** Verify that this
    ///    value's fingerprint equals
    ///    `node_identity::fingerprint_of_pubkey_b64(executor_node_id)` — the key
    ///    that actually signed `executor_sig` (see [`verify_receipt`]). If they
    ///    disagree, the claim is forged: reject it, do not fall back to it.
    /// 2. **Resolving is now safe in either form.**
    ///    `PeerManager::get_url_for_fingerprint` normalizes its query with
    ///    `strip_node_arg`, so passing this field's canonical `zc://node-<fp>`
    ///    form resolves identically to bare hex. (It previously stripped only the
    ///    STORED side, so the canonical form returned a silent `None` that landed
    ///    settlement in the pay-nobody / free-work arm — a silent revenue loss,
    ///    not a loud error. Fixed; pinned by
    ///    `peer.rs::get_url_for_fingerprint_matches_cached_identity_not_host`.)
    ///    Guard 1 is still required, and is still on the consumer.
    ///
    /// Do NOT add this field to [`receipt_bytes`] to "fix" the signing gap: that
    /// would invalidate every existing peer's signature across the version
    /// boundary. The cross-check in guard 1 is the intended remedy.
    #[serde(default)]
    pub executor_node_uri: String,
    /// Executor's node identity public key (b64), used to verify `executor_sig`.
    /// None for peers that don't yet sign receipts (backward-compatible).
    #[serde(default)]
    pub executor_node_id: Option<String>,
    /// Ed25519 signature (b64) over `receipt_bytes(self)`, proving the executor
    /// node identified by `executor_node_id` produced this settlement data.
    #[serde(default)]
    pub executor_sig: Option<String>,
    /// Lowercase hex SHA-256 of the result bytes (`payload_b64` decoded), as the
    /// executor sent them. Covered by the receipt signature when present
    /// (`zc-receipt-v2`), so a requester can tell a payload tampered with in
    /// transit from the one the executor produced. `None` from 0.0.46 and
    /// older executors, whose receipts keep verifying under the v1 bytes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result_digest: Option<String>,
}

/// Canonical, stable byte encoding of the settlement-relevant fields of a
/// `TaskResult`, used as the message both signed by the executor and checked
/// by the verifier. Deliberately excludes `payload_b64` (big, irrelevant to
/// settlement) and `executor_sig`/`executor_node_id` themselves.
///
/// Versioned by the digest: a result with no `result_digest` is encoded exactly
/// as before (`zc-receipt-v1`, so a 0.0.46 receipt still verifies); with one,
/// `zc-receipt-v2` adds the digest as a last line. Stripping the digest from a
/// v2 receipt therefore changes the signed bytes and fails verification.
pub fn receipt_bytes(r: &TaskResult) -> Vec<u8> {
    let v1 = |tag: &str| {
        format!(
            "{tag}\n{}\n{}\n{}\n{}\n{}\n{}",
            r.task_id,
            r.duration_ms,
            r.actual_cost,
            r.price_per_hour,
            r.executor_owner,
            r.worker_name
        )
    };
    match &r.result_digest {
        None => v1("zc-receipt-v1").into_bytes(),
        Some(d) => format!("{}\n{d}", v1("zc-receipt-v2")).into_bytes(),
    }
}

/// Verify the proof-of-execution receipt on a `TaskResult`: the signature must
/// be valid over `receipt_bytes(r)` under `executor_node_id`, and that node's
/// key fingerprint must be authorized in `roster`. Never panics; any missing
/// field or verification failure returns `false`.
pub fn verify_receipt(r: &TaskResult, roster: &super::roster_cache::RosterCache) -> bool {
    verify_receipt_with(r, &|node_id| {
        super::node_identity::fingerprint_of_pubkey_b64(node_id)
            .is_some_and(|fp| roster.fingerprint_authorized(&fp))
    })
}

/// [`verify_receipt`] with the roster check abstracted: `authorized(pubkey_b64)`
/// says whether the signing node may produce receipts.
pub fn verify_receipt_with(r: &TaskResult, authorized: &dyn Fn(&str) -> bool) -> bool {
    let (node_id, sig) = match (&r.executor_node_id, &r.executor_sig) {
        (Some(n), Some(s)) => (n, s),
        _ => return false,
    };
    super::node_identity::verify_sig(node_id, &receipt_bytes(r), sig) && authorized(node_id)
}

/// Does `r.result_digest`, when present, match `r.payload_b64`? `true` for a
/// result with no digest (nothing to check).
pub fn result_digest_matches(r: &TaskResult) -> bool {
    let Some(want) = &r.result_digest else {
        return true;
    };
    match base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &r.payload_b64) {
        Ok(bytes) => super::node_identity::sha256_hex(&bytes) == *want,
        Err(_) => false,
    }
}

/// Rejection returned when a peer cannot accept a task offer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskReject {
    pub task_id: String,
    pub reason: String,
}

/// Two-phase: a peer accepts a reserve offer (reserved a worker slot, did NOT
/// execute) and awaits a commit or cancel.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskAccept {
    pub task_id: String,
    pub estimated_cost: f64,
    pub worker_name: String,
    pub executor_owner: String,
    pub price_per_hour: f64,
}

/// Two-phase: tell the winning peer to execute its reserved offer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskCommit {
    pub task_id: String,
}

/// Two-phase: tell a losing peer to release its reserved offer (no execution).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskCancel {
    pub task_id: String,
}

/// Control message: broker with workers subscribes to a peer to receive task offers (push).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubscribeMessage {
    pub action: String,
    /// Subscriber's own broker URL (so the publisher can identify and push offers).
    pub peer_url: String,
    /// Shared peer secret (ZAKURO_PEER_KEY) for in-protocol QUIC auth.
    #[serde(default)]
    pub peer_key: String,
    /// Subscriber's per-node signature, same shape and meaning as
    /// [`TaskOffer::node_sig`], made over [`QUIC_SUBSCRIBE_SIGN_PATH`]. Additive
    /// and optional (ZC-0009): absent from older subscribers, ignored by older
    /// publishers. See [`SubscribeMessage::sign_for_quic`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node_sig: Option<OfferNodeSig>,
}

/// Path a QUIC subscribe signature is made over: distinct from the offer path
/// and from every HTTP route, so a signature made for one never verifies as
/// another.
pub const QUIC_SUBSCRIBE_SIGN_PATH: &str = "/quic/tasks/subscribe";

impl SubscribeMessage {
    /// Sign this subscribe with this node's key, as [`TaskOffer::sign_for_quic`]
    /// signs an offer, over [`quic_offer_sign_bytes`] (the JSON without
    /// `node_sig`, keys sorted, no whitespace) and [`QUIC_SUBSCRIBE_SIGN_PATH`].
    pub fn sign_for_quic(&mut self, key: &super::node_identity::NodeKey) {
        self.node_sig = None;
        let raw = serde_json::to_vec(self).unwrap_or_default();
        let Some(body) = quic_offer_sign_bytes(&raw) else {
            return;
        };
        let hdrs = key.sign_headers("POST", QUIC_SUBSCRIBE_SIGN_PATH, &body);
        let get = |name: &str| {
            hdrs.iter()
                .find(|(k, _)| k == name)
                .map(|(_, v)| v.clone())
                .unwrap_or_default()
        };
        self.node_sig = Some(OfferNodeSig {
            node_id: get("X-Node-Id"),
            sig: get("X-Node-Sig"),
            nonce: get("X-Node-Nonce"),
            ts: get("X-Node-Ts").parse().unwrap_or(0),
        });
    }

    /// The subscribe's signature as the `X-Node-*` headers the node-signature
    /// check reads. Empty when unsigned.
    pub fn quic_sig_headers(&self) -> Vec<(String, String)> {
        match &self.node_sig {
            Some(s) => vec![
                ("X-Node-Id".to_string(), s.node_id.clone()),
                ("X-Node-Sig".to_string(), s.sig.clone()),
                ("X-Node-Nonce".to_string(), s.nonce.clone()),
                ("X-Node-Ts".to_string(), s.ts.to_string()),
            ],
            None => Vec::new(),
        }
    }
}

/// Identity exchanged during peer handshake.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeerIdentity {
    /// Broker's verified owner_user_id (validated against dashboard at startup)
    pub owner_user_id: String,
    /// Human-readable node name
    pub node_name: String,
    /// Whether this broker's owner was verified against the dashboard
    pub verified: bool,
    /// Summary of available workers and their pricing
    pub workers: Vec<WorkerSummary>,
    /// QUIC UDP port for task offers (0 = not available)
    #[serde(default)]
    pub quic_port: u16,
    /// Whether this broker supports the two-phase (reserve→commit/cancel) offer
    /// protocol. Old peers omit it → false → sender uses one-phase with them.
    #[serde(default)]
    pub supports_two_phase: bool,
    /// Which zc binary the peer is running (zc#305). `None` from a peer built
    /// before build disclosure — which is exactly the peer whose behaviour the
    /// capability flags above are guessing at.
    #[serde(default)]
    pub build: Option<crate::build_id::BuildId>,
    /// The money unit this broker settles in (ADR 0027). Empty from a pre-yen
    /// peer, which this build refuses to settle with.
    #[serde(default)]
    pub currency: String,
}

/// Lightweight worker descriptor shared during handshake.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerSummary {
    pub name: String,
    pub price_per_hour: f64,
    pub status: String,
    pub cpus: f64,
    pub memory_bytes: u64,
    pub gpus: u32,
}

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

    #[test]
    fn new_types_round_trip() {
        let a = TaskAccept {
            task_id: "t".into(),
            estimated_cost: 1.5,
            worker_name: "w".into(),
            executor_owner: "o".into(),
            price_per_hour: 3.6,
        };
        let s = serde_json::to_string(&a).unwrap();
        let back: TaskAccept = serde_json::from_str(&s).unwrap();
        assert_eq!(back.task_id, "t");
        assert_eq!(back.estimated_cost, 1.5);
        let c: TaskCommit = serde_json::from_str(r#"{"task_id":"t"}"#).unwrap();
        assert_eq!(c.task_id, "t");
        let x: TaskCancel = serde_json::from_str(r#"{"task_id":"t"}"#).unwrap();
        assert_eq!(x.task_id, "t");
    }

    fn hashed_offer() -> TaskOffer {
        serde_json::from_str(
            r#"{"task_id":"t-1","payload_b64":"aGVsbG8=","max_price_per_hour":10.0,
            "estimated_duration_secs":1.5,"timeout_secs":10.0,"requester_user_id":"u1",
            "source_broker":"n","currency":"jpy"}"#,
        )
        .unwrap()
    }

    /// The documented encoding, pinned: another implementation (or a later
    /// build) that hashes the same fields the same way gets this value.
    #[test]
    fn the_offer_binding_hash_is_the_documented_encoding() {
        assert_eq!(
            hashed_offer().binding_hash(),
            "8b3165e7ff155811d9656493ee3e139294464bdff9d938171d3bb13276085f4d"
        );
    }

    /// Every field the voucher binds changes the hash; the ones set per send
    /// or carried beside it do not (the voucher travels inside the offer).
    #[test]
    fn the_offer_binding_hash_covers_the_bound_fields_and_nothing_else() {
        let base = hashed_offer();
        let h = base.binding_hash();
        let mut cases: Vec<TaskOffer> = Vec::new();
        for edit in [
            |o: &mut TaskOffer| o.task_id = "t-2".into(),
            |o: &mut TaskOffer| o.payload_b64 = "aGVsbG9v".into(),
            |o: &mut TaskOffer| o.max_price_per_hour = 10.000000001,
            |o: &mut TaskOffer| o.estimated_duration_secs = 1.6,
            |o: &mut TaskOffer| o.requester_user_id = "u2".into(),
            |o: &mut TaskOffer| o.currency = "zkcr".into(),
        ] {
            let mut o = base.clone();
            edit(&mut o);
            cases.push(o);
        }
        for o in &cases {
            assert_ne!(o.binding_hash(), h);
        }
        let mut same = base.clone();
        same.voucher_signed_json = "{\"v\":2}".into();
        same.voucher_sig = "sig".into();
        same.two_phase = true;
        same.target_node = "zc://node-abc".into();
        same.timeout_secs = 99.0;
        same.peer_key = "k".into();
        assert_eq!(same.binding_hash(), h);
        // The field boundaries are unambiguous: moving a character between two
        // adjacent string fields changes the hash.
        let mut a = base.clone();
        a.task_id = "ab".into();
        a.requester_user_id = "c".into();
        let mut b = base.clone();
        b.task_id = "a".into();
        b.requester_user_id = "bc".into();
        assert_ne!(a.binding_hash(), b.binding_hash());
        // f64::MAX (an uncapped offer) survives the wire exactly.
        let mut uncapped = base.clone();
        uncapped.max_price_per_hour = f64::MAX;
        let wire: TaskOffer =
            serde_json::from_str(&serde_json::to_string(&uncapped).unwrap()).unwrap();
        assert_eq!(wire.binding_hash(), uncapped.binding_hash());
    }

    #[test]
    fn task_offer_two_phase_defaults_false_for_old_senders() {
        // An offer JSON without `two_phase` (old sender) → false (execute-on-offer).
        let json = r#"{"task_id":"t","payload_b64":"","max_price_per_hour":1.0,
            "estimated_duration_secs":1.0,"timeout_secs":10.0,
            "requester_user_id":"u","source_broker":"n"}"#;
        let offer: TaskOffer = serde_json::from_str(json).unwrap();
        assert!(!offer.two_phase);
    }

    #[test]
    fn target_worker_defaults_empty_and_strips_scheme() {
        // An offer JSON without `target_worker` (old sender) → empty (no pin).
        let json = r#"{"task_id":"t","payload_b64":"","max_price_per_hour":1.0,
            "estimated_duration_secs":1.0,"timeout_secs":10.0,
            "requester_user_id":"u","source_broker":"n"}"#;
        let offer: TaskOffer = serde_json::from_str(json).unwrap();
        assert!(offer.target_worker.is_empty());
        // norm_target strips the zc:// scheme, passes bare names through.
        assert_eq!(norm_target("zc://worker-abc"), "worker-abc");
        assert_eq!(norm_target("zc://node-i9"), "node-i9");
        assert_eq!(norm_target("worker-abc"), "worker-abc");
    }

    #[test]
    fn peer_identity_supports_two_phase_defaults_false_for_old_peers() {
        let json = r#"{"owner_user_id":"o","node_name":"n","verified":true,"workers":[]}"#;
        let id: PeerIdentity = serde_json::from_str(json).unwrap();
        assert!(!id.supports_two_phase);
    }

    fn sample_result() -> TaskResult {
        TaskResult {
            task_id: "t1".into(),
            payload_b64: "irrelevant-to-settlement".into(),
            duration_ms: 1234.5,
            actual_cost: 0.789,
            worker_name: "worker-x".into(),
            worker_uri: "http://127.0.0.1:9000".into(),
            price_per_hour: 3.6,
            executor_owner: "owner-1".into(),
            worker_pid: None,
            executor_node_uri: String::new(),
            executor_node_id: None,
            executor_sig: None,
            result_digest: None,
        }
    }

    /// The PRE-change shape of `TaskResult` as an un-upgraded peer sees it.
    /// This is a deliberate model of the *other side of the version boundary*
    /// (that code no longer exists in-tree), not a re-implementation of any
    /// production expression: field names and serde attributes are copied
    /// verbatim from the previous revision of `TaskResult`.
    #[derive(Debug, Deserialize)]
    #[allow(dead_code)]
    struct OldPeerTaskResult {
        task_id: String,
        payload_b64: String,
        duration_ms: f64,
        actual_cost: f64,
        worker_name: String,
        worker_uri: String,
        price_per_hour: f64,
        executor_owner: String,
        #[serde(default)]
        worker_pid: Option<String>,
        #[serde(default)]
        worker_ip: Option<String>,
        #[serde(default)]
        executor_node_id: Option<String>,
        #[serde(default)]
        executor_sig: Option<String>,
    }

    #[test]
    fn task_result_carries_identity_not_addresses() {
        let mut r = sample_result();
        r.worker_uri = "zc://worker-aaaaaaaaaaaaaaaa-3960".into();
        r.executor_node_uri = "zc://node-aaaaaaaaaaaaaaaa".into();
        let json = serde_json::to_string(&r).unwrap();
        assert!(
            !json.contains("worker_ip"),
            "worker_ip must be off the wire: {json}"
        );
        assert!(
            !json.contains("http://"),
            "no scheme+host on the wire: {json}"
        );
        assert!(
            !json.contains("10.13.13."),
            "no mesh address on the wire: {json}"
        );
        assert!(json.contains("zc://node-aaaaaaaaaaaaaaaa"));

        // Wire-compat, OLD → NEW (guaranteed): an old peer's result still has
        // worker_ip and no executor_node_uri. Unknown fields are ignored and the
        // new field defaults to empty.
        let old = r#"{"task_id":"t","payload_b64":"","duration_ms":1.0,"actual_cost":0.1,
            "worker_name":"w","worker_uri":"http://10.13.13.7:3960","price_per_hour":3.6,
            "executor_owner":"o","worker_ip":"10.13.13.7"}"#;
        let back: TaskResult = serde_json::from_str(old).unwrap();
        assert!(back.executor_node_uri.is_empty());

        // Wire-compat, NEW → OLD (guaranteed at the schema level): every field
        // the old shape requires is still emitted, and the two fields we changed
        // or added are tolerated (worker_ip has #[serde(default)]; the extra
        // executor_node_uri is an unknown field the old struct ignores).
        let old_view: OldPeerTaskResult = serde_json::from_str(&json)
            .expect("an un-upgraded peer must still deserialize a new-shape result");
        assert!(old_view.worker_ip.is_none());
        // The old peer reads worker_uri, but the VALUE is now an identity handle,
        // not a dialable address — semantic, not wire, incompatibility.
        assert_eq!(old_view.worker_uri, "zc://worker-aaaaaaaaaaaaaaaa-3960");
    }

    #[test]
    fn receipt_bytes_stable_and_sensitive_to_settlement_fields() {
        let a = sample_result();
        let b = sample_result();
        assert_eq!(receipt_bytes(&a), receipt_bytes(&b));

        let mut c = sample_result();
        c.actual_cost = 999.0;
        assert_ne!(receipt_bytes(&a), receipt_bytes(&c));

        // payload_b64 is excluded from the receipt.
        let mut d = sample_result();
        d.payload_b64 = "totally-different-payload".into();
        assert_eq!(receipt_bytes(&a), receipt_bytes(&d));
    }

    #[test]
    fn verify_receipt_true_for_rostered_signer() {
        use super::super::node_identity::NodeKey;
        use super::super::roster_cache::RosterCache;

        let key = NodeKey::generate();
        let mut r = sample_result();
        r.executor_node_id = Some(key.public_b64());
        r.executor_sig = Some(key.sign(&receipt_bytes(&r)));

        let roster = RosterCache::from_entries(vec![(key.public_b64(), false)]);
        assert!(verify_receipt(&r, &roster));
    }

    #[test]
    fn verify_receipt_false_for_unrostered_signer() {
        use super::super::node_identity::NodeKey;
        use super::super::roster_cache::RosterCache;

        let key = NodeKey::generate();
        let other = NodeKey::generate();
        let mut r = sample_result();
        r.executor_node_id = Some(key.public_b64());
        r.executor_sig = Some(key.sign(&receipt_bytes(&r)));

        // Roster only authorizes a distinct key, not the signer.
        let roster = RosterCache::from_entries(vec![(other.public_b64(), false)]);
        assert!(!verify_receipt(&r, &roster));

        // Empty roster also rejects.
        let empty = RosterCache::from_entries(vec![]);
        assert!(!verify_receipt(&r, &empty));
    }

    #[test]
    fn verify_receipt_false_when_tampered_after_signing() {
        use super::super::node_identity::NodeKey;
        use super::super::roster_cache::RosterCache;

        let key = NodeKey::generate();
        let mut r = sample_result();
        r.executor_node_id = Some(key.public_b64());
        r.executor_sig = Some(key.sign(&receipt_bytes(&r)));
        let roster = RosterCache::from_entries(vec![(key.public_b64(), false)]);
        assert!(verify_receipt(&r, &roster));

        r.actual_cost += 1000.0; // tamper after signing
        assert!(!verify_receipt(&r, &roster));
    }

    #[test]
    fn verify_receipt_false_when_sig_or_node_id_missing() {
        use super::super::node_identity::NodeKey;
        use super::super::roster_cache::RosterCache;

        let key = NodeKey::generate();
        let roster = RosterCache::from_entries(vec![(key.public_b64(), false)]);

        let mut r = sample_result();
        assert!(!verify_receipt(&r, &roster)); // both missing

        r.executor_node_id = Some(key.public_b64());
        assert!(!verify_receipt(&r, &roster)); // sig missing

        r.executor_node_id = None;
        r.executor_sig = Some(key.sign(&receipt_bytes(&r)));
        assert!(!verify_receipt(&r, &roster)); // node_id missing
    }

    /// A receipt from 0.0.46 (no digest) is encoded as it always was, and
    /// verifies; a receipt with a digest signs the digest too, and stripping it
    /// breaks the signature.
    #[test]
    fn receipt_digest_is_versioned_and_covered_by_the_signature() {
        use super::super::node_identity::NodeKey;
        use super::super::roster_cache::RosterCache;

        let key = NodeKey::generate();
        let roster = RosterCache::from_entries(vec![(key.public_b64(), false)]);

        // v1: byte-for-byte what 0.0.46 signs
        let mut old = sample_result();
        assert!(receipt_bytes(&old).starts_with(b"zc-receipt-v1\n"));
        old.executor_node_id = Some(key.public_b64());
        old.executor_sig = Some(key.sign(&receipt_bytes(&old)));
        assert!(verify_receipt(&old, &roster));
        // the v1 wire has no digest member at all
        assert!(!serde_json::to_string(&old)
            .unwrap()
            .contains("result_digest"));

        // v2
        let mut r = sample_result();
        r.payload_b64 =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, b"hello");
        r.result_digest = Some(crate::broker::node_identity::sha256_hex(b"hello"));
        assert!(receipt_bytes(&r).starts_with(b"zc-receipt-v2\n"));
        r.executor_node_id = Some(key.public_b64());
        r.executor_sig = Some(key.sign(&receipt_bytes(&r)));
        assert!(verify_receipt(&r, &roster));
        assert!(result_digest_matches(&r));

        // digest stripped after signing: signature no longer verifies
        let mut stripped = r.clone();
        stripped.result_digest = None;
        assert!(!verify_receipt(&stripped, &roster));
        // digest swapped: also fails
        let mut swapped = r.clone();
        swapped.result_digest = Some(crate::broker::node_identity::sha256_hex(b"other"));
        assert!(!verify_receipt(&swapped, &roster));
    }

    #[test]
    fn digest_check_compares_the_payload_as_received() {
        let mut r = sample_result();
        assert!(result_digest_matches(&r), "no digest: nothing to check");
        r.payload_b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, b"abc");
        r.result_digest = Some(crate::broker::node_identity::sha256_hex(b"abc"));
        assert!(result_digest_matches(&r));
        r.payload_b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, b"abd");
        assert!(!result_digest_matches(&r));
        r.payload_b64 = "!!not base64!!".into();
        assert!(!result_digest_matches(&r));
    }

    // NOTE: this file used to carry `mesh_facing_payloads_never_disclose_an_address`,
    // which built `TaskResult`/`PeerIdentity` by hand with `zc://…` already
    // substituted in and asserted on that literal. It never called a real
    // producer, so no production regression could fail it (proven: mutating
    // `server.rs`'s `run_offer_on` back to `worker_uri: worker.uri.clone()`
    // left it green 6/6). It has been removed in favor of tests that drive
    // the REAL producers and assert on what they actually emit:
    //   - `server.rs::task_result_producer_tests::producer_emits_no_address_in_task_result`
    //     drives `run_offer_on` against a stub worker for `TaskResult`.
    //   - `server.rs::task_result_producer_tests::producer_emits_no_address_in_peer_identity`
    //     drives `handle_peer_identity` against a registered worker for
    //     `PeerIdentity`/`WorkerSummary`.
    // See task-5-report.md in the sdd folder for the mutation evidence.
}

#[cfg(test)]
mod quic_offer_sig_tests {
    use super::{quic_offer_sign_bytes, TaskOffer};

    const OFFER: &str = r#"{"task_id":"t","payload_b64":"","max_price_per_hour":100.0,"estimated_duration_secs":1.0,"timeout_secs":10.0,"requester_user_id":"u","source_broker":"n"}"#;

    /// Frozen wire (ZC-0009): an unsigned offer, as sent over HTTP, carries no
    /// `node_sig` member, and an old sender's offer parses with none.
    #[test]
    fn an_unsigned_offer_has_no_node_sig_on_the_wire() {
        let offer: TaskOffer = serde_json::from_str(OFFER).unwrap();
        assert!(offer.node_sig.is_none());
        assert!(!serde_json::to_string(&offer).unwrap().contains("node_sig"));
    }

    #[test]
    fn a_signed_offer_round_trips_its_node_sig() {
        let mut offer: TaskOffer = serde_json::from_str(OFFER).unwrap();
        offer.sign_for_quic(&crate::broker::node_identity::NodeKey::generate());
        let back: TaskOffer = serde_json::from_slice(&serde_json::to_vec(&offer).unwrap()).unwrap();
        assert_eq!(back.node_sig, offer.node_sig);
        assert!(back.node_sig.is_some());
    }

    #[test]
    fn sign_bytes_drop_node_sig_and_sort_keys() {
        let a = br#"{"b":1,"a":{"y":2,"x":1},"node_sig":{"sig":"s"}}"#;
        let b = br#"{ "a": {"x":1,"y":2}, "b": 1 }"#;
        assert_eq!(quic_offer_sign_bytes(a), quic_offer_sign_bytes(b));
        assert_eq!(
            quic_offer_sign_bytes(b).unwrap(),
            br#"{"a":{"x":1,"y":2},"b":1}"#.to_vec()
        );
        assert_eq!(quic_offer_sign_bytes(b"[1]"), None);
    }
}