zc2 0.0.53

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
//! Binding a `/peer/earn` to the hub's receipt for the requester's debit
//! (ADR ZC-0012 earn binding, ZC-0026).
//!
//! The executor remembers the jobs it ran (`earn_expect`). A requester that
//! forwarded a job straight to a remote worker (`/execute`, `/execute/batch`,
//! `/infer`) never went through the executor's offer path, so the executor has
//! no record and the earn read `unknown_job`. The requester now attaches the
//! `receipt_hash` the hub answered when it stored the debit (delivery waits
//! for the debit to be committed at the hub, so the hash is known by then).
//! The executor fetches that receipt from the hub, verifies it offline against
//! the hub's keys (`receipt_verify`), and checks what the signature can prove:
//!
//! * it is a `transaction` receipt, settled (not refunded, failed...);
//! * the earn is at most the amount the hub settled for that debit;
//! * the debit names THIS broker: `executor.node_key` (new receipts, present
//!   when the hub could resolve the reporting broker) is the 16-hex node
//!   fingerprint and must equal ours; when it is present the worker check is
//!   advisory, since worker names are not unique across nodes. Without it
//!   (older receipts, unresolved node) the worker rule below still applies;
//! * the debit names one of THIS broker's workers: `executor.worker` is
//!   `sha256("worker:" + worker_id)[..32]` (`job_receipts._fp`), and the
//!   requester's debit carries the worker NAME the executor advertised
//!   (`WorkerName::of`), which the hub keeps as `unresolved_worker_id` for a
//!   worker of another account;
//! * one receipt backs one earn (`ExpectedEarns::bind_receipt`): a requester
//!   cannot spend a single real debit on many invented jobs.
//!
//! What the receipt cannot say: the request id. It is signed only as a salted
//! commitment (`job.ref`) that the account owner opens, and `executor.node` is
//! the hash of the debit's `source_node`, which the requester posts as ITS OWN
//! node name. So the earn is bound to a real, settled, sufficiently large debit
//! on one of this node's workers, once; not to a particular request id.

use std::sync::Arc;
use std::time::Duration;

use dashmap::DashMap;
use serde_json::Value;

use crate::receipt_verify::{self, FetchError, Signed, TrustedKey, VerifyError};

/// How long the executor waits for the hub while it answers `/peer/earn`.
pub const FETCH_TIMEOUT: Duration = Duration::from_secs(5);
/// A verified receipt never changes (the signed bytes are immutable): keep it.
const OK_TTL_SECS: u64 = 3600;
/// A failed fetch is not retried at once, so a requester cannot make the
/// executor hammer the hub by resending.
const FETCH_FAIL_TTL_SECS: u64 = 15;
/// Cache bound; on overflow it is emptied (it only saves round trips).
const CACHE_CAP: usize = 4096;

/// `sha256("worker:" + worker_id)`, first 32 hex chars: the hub's `_fp("worker", ..)`.
pub fn worker_fingerprint(worker_id: &str) -> String {
    let d = ring::digest::digest(
        &ring::digest::SHA256,
        format!("worker:{worker_id}").as_bytes(),
    );
    hex::encode(&d.as_ref()[..16])
}

/// 64 lowercase hex characters.
pub fn is_receipt_hash(s: &str) -> bool {
    s.len() == 64
        && s.bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// What the executor reads from a verified `transaction` receipt.
#[derive(Debug, Clone, PartialEq)]
pub struct ReceiptFacts {
    /// `settlement.amount`.
    pub amount: f64,
    pub status: String,
    /// `executor.worker`, `None` when the debit named no worker.
    pub executor_worker: Option<String>,
    /// `executor.node_key`, the 16-hex fingerprint of the broker that reported
    /// the worker; `None` for receipts that predate it or an unresolved node.
    pub executor_node_key: Option<String>,
}

/// What bound the receipt to this node (for the `/health` counters).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Binding {
    /// `executor.node_key` equals this node's fingerprint.
    NodeKey,
    /// No node key on the receipt; one of this node's worker fingerprints.
    Worker,
}

/// Why a receipt did not bind an earn.
#[derive(Debug, Clone, PartialEq)]
pub enum Reject {
    /// The hub could not be asked, or did not have it.
    Fetch(String),
    /// Bad signature, unknown key, malformed.
    Unverified(String),
    /// A receipt of another kind (a Spaces batch, a forge job...).
    NotATransaction,
    /// The settlement was refunded, reversed, failed...
    NotSettled(String),
    /// The earn is more than the hub settled.
    Amount { earn: f64, receipt: f64 },
    /// The debit is not for one of this node's workers.
    WrongExecutor,
    /// The receipt already backs another earn.
    Reused,
}

impl Reject {
    pub fn code(&self) -> &'static str {
        match self {
            Self::Fetch(_) => "fetch_failed",
            Self::Unverified(_) => "unverified",
            Self::NotATransaction | Self::NotSettled(_) => "not_settled",
            Self::Amount { .. } => "amount",
            Self::WrongExecutor => "wrong_executor",
            Self::Reused => "reused",
        }
    }
}

impl std::fmt::Display for Reject {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Fetch(e) => write!(f, "receipt not fetched: {e}"),
            Self::Unverified(e) => write!(f, "receipt does not verify: {e}"),
            Self::NotATransaction => write!(f, "not a transaction receipt"),
            Self::NotSettled(s) => write!(f, "settlement is {s}"),
            Self::Amount { earn, receipt } => {
                write!(f, "earn {earn:.6} exceeds the settled {receipt:.6}")
            }
            Self::WrongExecutor => write!(f, "the debit is not for one of this node's workers"),
            Self::Reused => write!(f, "the receipt already backs another earn"),
        }
    }
}

/// Settlement words that mean the money was not (or is no longer) taken.
fn settled(status: &str) -> bool {
    !matches!(
        status.trim().to_ascii_lowercase().as_str(),
        "failed" | "refunded" | "reversed" | "cancelled" | "canceled" | "pending"
    )
}

/// Read the facts out of a receipt body the signature has already covered.
pub fn facts_of(body: &Value) -> Result<ReceiptFacts, Reject> {
    if body.get("kind").and_then(Value::as_str) != Some("transaction") {
        return Err(Reject::NotATransaction);
    }
    let amount = body
        .pointer("/settlement/amount")
        .and_then(Value::as_str)
        .and_then(|a| a.trim().parse::<f64>().ok())
        .filter(|a| a.is_finite() && *a >= 0.0)
        .ok_or_else(|| Reject::Unverified("no settlement amount".into()))?;
    let status = body
        .pointer("/settlement/status")
        .and_then(Value::as_str)
        .unwrap_or("completed")
        .to_string();
    if !settled(&status) {
        return Err(Reject::NotSettled(status));
    }
    let executor_worker = body
        .pointer("/executor/worker")
        .and_then(Value::as_str)
        .map(str::to_string);
    let executor_node_key = body
        .pointer("/executor/node_key")
        .and_then(Value::as_str)
        .filter(|k| !k.is_empty())
        .map(|k| k.to_ascii_lowercase());
    Ok(ReceiptFacts {
        amount,
        status,
        executor_worker,
        executor_node_key,
    })
}

/// Fetch (or recall) the receipt `hash` and read its facts.
pub struct ReceiptCache {
    ok: DashMap<String, (u64, Arc<ReceiptFacts>)>,
    failed: DashMap<String, (u64, Reject)>,
}

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

impl ReceiptCache {
    pub fn new() -> Self {
        Self {
            ok: DashMap::new(),
            failed: DashMap::new(),
        }
    }

    /// The facts of receipt `hash`. `fetch` asks the hub for the signed bytes;
    /// `keys(refresh)` returns the trusted hub keys, `refresh = true` once a
    /// key the receipt names was not among the cached ones.
    pub fn facts(
        &self,
        hash: &str,
        now: u64,
        fetch: &dyn Fn(&str) -> Result<Signed, FetchError>,
        keys: &dyn Fn(bool) -> Vec<TrustedKey>,
    ) -> Result<Arc<ReceiptFacts>, Reject> {
        if let Some(e) = self.ok.get(hash) {
            if now.saturating_sub(e.0) < OK_TTL_SECS {
                return Ok(e.1.clone());
            }
        }
        if let Some(e) = self.failed.get(hash) {
            if now.saturating_sub(e.0) < FETCH_FAIL_TTL_SECS {
                return Err(e.1.clone());
            }
        }
        let signed = fetch(hash).map_err(|e| {
            // The hub answered no (4xx): it does not have that receipt, and
            // asking again will not change it. Anything else may clear.
            let r = if e.permanent() {
                Reject::Unverified(format!("the hub has no such receipt ({})", e.message))
            } else {
                Reject::Fetch(e.message)
            };
            self.note_failed(hash, now, &r);
            r
        })?;
        // The hash is the receipt's address: whatever the hub (or anything in
        // front of it) served must hash to it.
        if receipt_verify::sha256_hex(signed.receipt_json.as_bytes()) != hash {
            return Err(Reject::Unverified("served bytes do not hash to it".into()));
        }
        let mut verdict = receipt_verify::verify(&signed, &keys(false));
        if matches!(verdict, Err(VerifyError::UnknownKey(_))) {
            verdict = receipt_verify::verify(&signed, &keys(true));
        }
        let verified = verdict.map_err(|e| Reject::Unverified(e.to_string()))?;
        let facts = Arc::new(facts_of(&verified.body)?);
        if self.ok.len() >= CACHE_CAP {
            self.ok.clear();
        }
        self.ok.insert(hash.to_string(), (now, facts.clone()));
        Ok(facts)
    }

    fn note_failed(&self, hash: &str, now: u64, r: &Reject) {
        if self.failed.len() >= CACHE_CAP {
            self.failed.clear();
        }
        self.failed.insert(hash.to_string(), (now, r.clone()));
    }
}

/// The amount and executor checks, given facts that already verified.
/// `local_worker_fps` are [`worker_fingerprint`]s of this broker's workers
/// (names and ids); `own_fp` is this node's fingerprint.
pub fn judge(
    facts: &ReceiptFacts,
    earn_amount: f64,
    local_worker_fps: &[String],
    own_fp: &str,
) -> Result<Binding, Reject> {
    if earn_amount > facts.amount + super::earn_expect::epsilon(facts.amount) {
        return Err(Reject::Amount {
            earn: earn_amount,
            receipt: facts.amount,
        });
    }
    if let Some(k) = facts.executor_node_key.as_deref() {
        // Signed by the hub: names the node, so a same-named worker on
        // another node cannot claim it. The worker name is advisory here.
        return if k.eq_ignore_ascii_case(own_fp) {
            Ok(Binding::NodeKey)
        } else {
            Err(Reject::WrongExecutor)
        };
    }
    match facts.executor_worker.as_deref() {
        Some(w) if local_worker_fps.iter().any(|f| f == w) => Ok(Binding::Worker),
        _ => Err(Reject::WrongExecutor),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::receipt_verify::testkit::Hub;
    use std::cell::Cell;

    const OWN: &str = "aaaaaaaaaaaaaaaa";

    fn fps(names: &[&str]) -> Vec<String> {
        names.iter().map(|n| worker_fingerprint(n)).collect()
    }

    fn hash_of(s: &Signed) -> String {
        receipt_verify::sha256_hex(s.receipt_json.as_bytes())
    }

    #[test]
    fn worker_fingerprint_is_the_hubs_fp_of_the_name() {
        // `_fp("worker", "w1")` = sha256("worker:w1").hexdigest()[:32]
        assert_eq!(worker_fingerprint("w1"), "7d5fae5e9503a782301d74c397506cbc");
        assert_eq!(worker_fingerprint("w1").len(), 32);
        assert_ne!(worker_fingerprint("w1"), worker_fingerprint("w2"));
        assert!(is_receipt_hash(&"a".repeat(64)));
        assert!(!is_receipt_hash(&"A".repeat(64)) && !is_receipt_hash("abc"));
    }

    #[test]
    fn a_settled_debit_for_one_of_our_workers_binds_an_earn_up_to_its_amount() {
        let hub = Hub::new();
        let r = hub.transaction_receipt(Some("w1"), "1.500000", "completed");
        let h = hash_of(&r);
        let cache = ReceiptCache::new();
        let fetched = Cell::new(0);
        let fetch = |_: &str| -> Result<Signed, FetchError> {
            fetched.set(fetched.get() + 1);
            Ok(r.clone())
        };
        let keys = |_: bool| vec![hub.trusted()];
        let f = cache.facts(&h, 100, &fetch, &keys).unwrap();
        assert_eq!(f.amount, 1.5);
        assert!(judge(&f, 1.2, &fps(&["w1", "other"]), OWN).is_ok());
        assert!(judge(&f, 1.5, &fps(&["w1"]), OWN).is_ok());
        assert_eq!(
            judge(&f, 2.0, &fps(&["w1"]), OWN),
            Err(Reject::Amount {
                earn: 2.0,
                receipt: 1.5
            })
        );
        assert_eq!(
            judge(&f, 1.0, &fps(&["not-w1"]), OWN),
            Err(Reject::WrongExecutor)
        );
        // cached: no second fetch
        cache.facts(&h, 101, &fetch, &keys).unwrap();
        assert_eq!(fetched.get(), 1);
    }

    #[test]
    fn a_node_key_binds_by_node_and_a_same_named_worker_elsewhere_does_not() {
        let hub = Hub::new();
        let facts = |node: Option<&str>, w: Option<&str>| {
            let r = hub.transaction_receipt_on(node, w, "1.000000", "completed");
            facts_of(&serde_json::from_str(&r.receipt_json).unwrap()).unwrap()
        };
        // our node key: bound, even when the worker name is not one of ours
        let f = facts(Some(OWN), Some("w0"));
        assert_eq!(judge(&f, 1.0, &fps(&["w0"]), OWN), Ok(Binding::NodeKey));
        assert_eq!(judge(&f, 1.0, &fps(&["zzz"]), OWN), Ok(Binding::NodeKey));
        assert_eq!(judge(&f, 1.0, &[], OWN), Ok(Binding::NodeKey));
        // another node's key with a worker named like ours: refused
        let f = facts(Some("bbbbbbbbbbbbbbbb"), Some("w0"));
        assert_eq!(
            judge(&f, 1.0, &fps(&["w0"]), OWN),
            Err(Reject::WrongExecutor)
        );
        // no node key: today's worker-name rule
        let f = facts(None, Some("w0"));
        assert_eq!(judge(&f, 1.0, &fps(&["w0"]), OWN), Ok(Binding::Worker));
        assert_eq!(
            judge(&f, 1.0, &fps(&["w9"]), OWN),
            Err(Reject::WrongExecutor)
        );
        // the amount check still applies
        let f = facts(Some(OWN), Some("w0"));
        assert!(matches!(
            judge(&f, 5.0, &fps(&["w0"]), OWN),
            Err(Reject::Amount { .. })
        ));
    }

    #[test]
    fn a_debit_that_names_no_worker_binds_nothing() {
        let hub = Hub::new();
        let r = hub.transaction_receipt(None, "1.000000", "completed");
        let f = facts_of(&serde_json::from_str(&r.receipt_json).unwrap()).unwrap();
        assert_eq!(
            judge(&f, 0.5, &fps(&["w1"]), OWN),
            Err(Reject::WrongExecutor)
        );
    }

    #[test]
    fn what_the_signature_does_not_cover_or_the_hub_refunded_is_refused() {
        let hub = Hub::new();
        let other = Hub::new();
        let keys = |_: bool| vec![hub.trusted()];
        let cache = ReceiptCache::new();

        // signed by a key the hub does not publish
        let forged = other.transaction_receipt(Some("w1"), "9.000000", "completed");
        let fh = hash_of(&forged);
        let calls = Cell::new(0);
        let r = cache.facts(&fh, 1, &|_| Ok(forged.clone()), &|refresh| {
            calls.set(calls.get() + 1);
            let _ = refresh;
            vec![hub.trusted()]
        });
        assert!(matches!(r, Err(Reject::Unverified(_))), "{r:?}");
        assert_eq!(calls.get(), 2, "an unknown key refreshes the key set once");

        // the bytes served are not the ones addressed
        let good = hub.transaction_receipt(Some("w1"), "1.000000", "completed");
        let r = cache.facts(&"0".repeat(64), 1, &|_| Ok(good.clone()), &keys);
        assert!(matches!(r, Err(Reject::Unverified(_))), "{r:?}");

        // a tampered body under a real signature
        let mut t = good.clone();
        t.receipt_json = t.receipt_json.replace("1.000000", "9.000000");
        let r = cache.facts(&hash_of(&t), 1, &|_| Ok(t.clone()), &keys);
        assert!(matches!(r, Err(Reject::Unverified(_))), "{r:?}");

        // refunded
        let refunded = hub.transaction_receipt(Some("w1"), "1.000000", "refunded");
        let r = cache.facts(&hash_of(&refunded), 1, &|_| Ok(refunded.clone()), &keys);
        assert_eq!(r, Err(Reject::NotSettled("refunded".into())));

        // another kind of receipt
        let batch = hub.batch_receipt(&["a".repeat(64)], "5.000000");
        let r = cache.facts(&hash_of(&batch), 1, &|_| Ok(batch.clone()), &keys);
        assert_eq!(r, Err(Reject::NotATransaction));
    }

    #[test]
    fn a_hub_that_has_no_such_receipt_is_final_and_a_hub_that_is_down_is_not() {
        let hub = Hub::new();
        let keys = |_: bool| vec![hub.trusted()];
        let cache = ReceiptCache::new();
        let missing = |_: &str| -> Result<Signed, FetchError> {
            Err(FetchError {
                status: Some(404),
                message: "HTTP 404".into(),
            })
        };
        assert!(matches!(
            cache.facts(&"d".repeat(64), 1, &missing, &keys),
            Err(Reject::Unverified(_))
        ));
        let down = |_: &str| -> Result<Signed, FetchError> {
            Err(FetchError {
                status: Some(503),
                message: "HTTP 503".into(),
            })
        };
        assert!(matches!(
            cache.facts(&"e".repeat(64), 1, &down, &keys),
            Err(Reject::Fetch(_))
        ));
    }

    #[test]
    fn a_failed_fetch_is_not_repeated_at_once() {
        let hub = Hub::new();
        let cache = ReceiptCache::new();
        let calls = Cell::new(0);
        let fetch = |_: &str| {
            calls.set(calls.get() + 1);
            Err(FetchError {
                status: None,
                message: "hub down".into(),
            })
        };
        let keys = |_: bool| vec![hub.trusted()];
        let h = "b".repeat(64);
        assert!(matches!(
            cache.facts(&h, 10, &fetch, &keys),
            Err(Reject::Fetch(_))
        ));
        assert!(cache.facts(&h, 12, &fetch, &keys).is_err());
        assert_eq!(calls.get(), 1);
        assert!(cache
            .facts(&h, 10 + FETCH_FAIL_TTL_SECS, &fetch, &keys)
            .is_err());
        assert_eq!(calls.get(), 2);
    }
}