matrix-compute-node 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
src/auth/l402_gate.py ADDED
@@ -0,0 +1,553 @@
1
+ """Strict Pre-Allocation L402 Gate & DoS Protection for matrix-compute-node."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ from collections import OrderedDict
7
+ import hashlib
8
+ import hmac
9
+ import json
10
+ import logging
11
+ import math
12
+ import threading
13
+ import time
14
+ from typing import Any, Dict, List, Optional, Tuple, Union
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class L402PreAllocationGate:
20
+ """
21
+ Strict 5-Step Pre-Allocation Gate enforcing L402 Macaroon validation,
22
+ multi-task caveat authorization, GFLOP bounding, and HODL payment lock status
23
+ BEFORE any GPU VRAM or compute buffer is allocated.
24
+
25
+ Features thread-safe in-memory caching of verified HELD payment states to
26
+ eliminate redundant settlement queries across multi-tile batches.
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ settlement_client_or_url: Optional[Any] = None,
32
+ verification_key: str = "settlement-secret-verification-key-12345",
33
+ min_price_rate: float = 0.0005,
34
+ min_task_sats: int = 10,
35
+ cache_ttl_seconds: float = 300.0,
36
+ max_cache_size: int = 10000,
37
+ cache_ttl: Optional[float] = None,
38
+ is_seed_worker: bool = False,
39
+ worker_pubkey: Optional[str] = None,
40
+ ) -> None:
41
+ self.settlement_client = settlement_client_or_url
42
+ self.verification_key = verification_key
43
+ self.min_price_rate = float(min_price_rate)
44
+ self.min_task_sats = int(min_task_sats)
45
+ self.cache_ttl_seconds = float(cache_ttl if cache_ttl is not None else cache_ttl_seconds)
46
+ self.max_cache_size = int(max_cache_size)
47
+ self.is_seed_worker = bool(is_seed_worker)
48
+ self.worker_pubkey = str(worker_pubkey).strip() if worker_pubkey else None
49
+
50
+ self._lock = threading.RLock()
51
+ # payment_hash -> (status, expires_at)
52
+ self._verified_cache: OrderedDict[str, Tuple[str, float]] = OrderedDict()
53
+
54
+ # Telemetry / metrics counters
55
+ self.remote_query_count: int = 0
56
+ self.cache_hit_count: int = 0
57
+
58
+ @property
59
+ def _status_cache(self) -> OrderedDict[str, Tuple[str, float]]:
60
+ """Backward-compatible alias for _verified_cache."""
61
+ return self._verified_cache
62
+
63
+ @property
64
+ def cache_ttl(self) -> float:
65
+ """Alias for cache_ttl_seconds."""
66
+ return self.cache_ttl_seconds
67
+
68
+ @property
69
+ def _cache_hits(self) -> int:
70
+ return self.cache_hit_count
71
+
72
+ @_cache_hits.setter
73
+ def _cache_hits(self, val: int) -> None:
74
+ self.cache_hit_count = val
75
+
76
+ @property
77
+ def _cache_misses(self) -> int:
78
+ return self.remote_query_count
79
+
80
+ @_cache_misses.setter
81
+ def _cache_misses(self, val: int) -> None:
82
+ self.remote_query_count = val
83
+
84
+ def get_cached_status(self, payment_hash: str, now: Optional[float] = None) -> Optional[str]:
85
+ """Returns cached status if present and unexpired; otherwise evicts and returns None."""
86
+ clean_hash = str(payment_hash).strip().lower()
87
+ current_time = now if now is not None else time.time()
88
+ with self._lock:
89
+ if clean_hash not in self._verified_cache:
90
+ return None
91
+ status, expires_at = self._verified_cache[clean_hash]
92
+ if current_time >= expires_at:
93
+ self._verified_cache.pop(clean_hash, None)
94
+ return None
95
+ self._verified_cache.move_to_end(clean_hash)
96
+ return status
97
+
98
+ def set_cached_status(
99
+ self,
100
+ payment_hash: str,
101
+ status: str,
102
+ expiry: Optional[float] = None,
103
+ now: Optional[float] = None,
104
+ ) -> None:
105
+ """Stores verified status in cache with TTL and capacity bounds."""
106
+ clean_hash = str(payment_hash).strip().lower()
107
+ clean_status = str(status).strip().upper()
108
+ if clean_status != "HELD":
109
+ return
110
+ current_time = now if now is not None else time.time()
111
+ entry_expiry = expiry if expiry is not None else (current_time + self.cache_ttl_seconds)
112
+ entry_expiry = min(entry_expiry, current_time + self.cache_ttl_seconds)
113
+ with self._lock:
114
+ if clean_hash in self._verified_cache:
115
+ self._verified_cache.move_to_end(clean_hash)
116
+ self._verified_cache[clean_hash] = (clean_status, entry_expiry)
117
+ if len(self._verified_cache) > self.max_cache_size:
118
+ self._evict_expired_unlocked(current_time)
119
+ while len(self._verified_cache) > self.max_cache_size:
120
+ self._verified_cache.popitem(last=False)
121
+
122
+ def evict_expired(self, now: Optional[float] = None) -> int:
123
+ """Evicts expired cache entries. Returns count of evicted items."""
124
+ current_time = now if now is not None else time.time()
125
+ with self._lock:
126
+ return self._evict_expired_unlocked(current_time)
127
+
128
+ def _evict_expired_unlocked(self, current_time: float) -> int:
129
+ expired_keys = [
130
+ k for k, (_, exp) in self._verified_cache.items()
131
+ if current_time >= exp
132
+ ]
133
+ for k in expired_keys:
134
+ self._verified_cache.pop(k, None)
135
+ return len(expired_keys)
136
+
137
+ def invalidate(self, payment_hash: str) -> bool:
138
+ """Removes a specific payment hash from cache. Returns True if removed."""
139
+ clean_hash = str(payment_hash).strip().lower()
140
+ with self._lock:
141
+ return self._verified_cache.pop(clean_hash, None) is not None
142
+
143
+ def invalidate_cache(self, payment_hash: Optional[str] = None) -> None:
144
+ """Evicts a single payment hash or purges the entire cache."""
145
+ with self._lock:
146
+ if payment_hash is not None:
147
+ self._verified_cache.pop(str(payment_hash).strip().lower(), None)
148
+ else:
149
+ self._verified_cache.clear()
150
+
151
+ def clear_cache(self) -> None:
152
+ """Clears all cached verification states and resets counters."""
153
+ with self._lock:
154
+ self._verified_cache.clear()
155
+ self.cache_hit_count = 0
156
+ self.remote_query_count = 0
157
+
158
+ def parse_auth_header(self, auth_header: str) -> Tuple[Optional[str], Optional[str]]:
159
+ """
160
+ Parses 'Authorization: L402 <macaroon_b64>:<payment_hash>' header.
161
+ Returns (macaroon_b64, payment_hash) or (None, None) if malformed.
162
+ """
163
+ if not auth_header or not isinstance(auth_header, str):
164
+ return None, None
165
+
166
+ cleaned = auth_header.strip()
167
+ if cleaned.startswith("mc_trial_"):
168
+ if ":" in cleaned:
169
+ parts_c = cleaned.split(":", 1)
170
+ return parts_c[0].strip(), parts_c[1].strip() or ("0" * 64)
171
+ return cleaned, "0" * 64
172
+
173
+ if cleaned.lower().startswith("authorization:"):
174
+ cleaned = cleaned[14:].strip()
175
+ parts = cleaned.split(" ", 1)
176
+ if len(parts) != 2:
177
+ return None, None
178
+
179
+ scheme, credentials = parts[0].upper(), parts[1].strip()
180
+ if scheme not in ("L402", "LSAT"):
181
+ return None, None
182
+
183
+ if credentials.startswith("mc_trial_") and ":" not in credentials:
184
+ return credentials, "0" * 64
185
+
186
+ # Credentials expected format: <macaroon_b64>:<payment_hash>
187
+ cred_parts = credentials.split(":", 1)
188
+ if len(cred_parts) != 2:
189
+ return None, None
190
+
191
+ macaroon_b64, payment_hash = cred_parts[0].strip(), cred_parts[1].strip()
192
+ if not macaroon_b64 or not payment_hash:
193
+ return None, None
194
+
195
+ return macaroon_b64, payment_hash
196
+
197
+ def _query_settlement_backend(self, payment_hash: str) -> Tuple[Optional[str], Optional[str]]:
198
+ """Queries settlement backend for invoice status. Returns (status, error_message)."""
199
+ if not self.settlement_client:
200
+ return None, "Settlement verification is unconfigured (fail-closed)"
201
+
202
+ status = None
203
+ if isinstance(self.settlement_client, str) and (
204
+ self.settlement_client.startswith("http://") or self.settlement_client.startswith("https://")
205
+ ):
206
+ base_url = self.settlement_client.rstrip("/")
207
+ try:
208
+ import httpx
209
+ with httpx.Client(timeout=5.0) as client:
210
+ # Allow up to 3 attempts (0.2s backoff) if invoice is still UNPAID due to WAN/Lightning gossip latency
211
+ for attempt in range(3):
212
+ resp = client.get(f"{base_url}/invoices/{payment_hash}")
213
+ if resp.status_code == 200:
214
+ data = resp.json()
215
+ if isinstance(data, dict):
216
+ raw_status = data.get("status") or data.get("invoice_status")
217
+ status = str(raw_status).strip().upper() if raw_status else None
218
+ elif isinstance(data, str):
219
+ status = data.strip().upper()
220
+ else:
221
+ status = None
222
+ if status == "HELD" or status in ("SETTLED", "CANCELLED") or attempt == 2:
223
+ break
224
+ time.sleep(0.2)
225
+ else:
226
+ status = None
227
+ break
228
+ except Exception as ex:
229
+ logger.warning("HTTP settlement verification query failed: %s", ex)
230
+ return None, f"Settlement HTTP query failed: {ex}"
231
+ elif hasattr(self.settlement_client, "get_status"):
232
+ raw_status = self.settlement_client.get_status(payment_hash)
233
+ status = str(raw_status).strip().upper() if raw_status else None
234
+ elif callable(self.settlement_client):
235
+ raw_status = self.settlement_client(payment_hash)
236
+ status = str(raw_status).strip().upper() if raw_status else None
237
+
238
+ return status, None
239
+
240
+ def mint_trial_macaroon(
241
+ self,
242
+ task_id: str,
243
+ job_id: str = "",
244
+ seed_worker_pubkeys: Optional[List[str]] = None,
245
+ allowed_workers: Optional[List[str]] = None,
246
+ max_matrix_dim: int = 4096,
247
+ expiry_seconds: int = 3600,
248
+ ) -> str:
249
+ """
250
+ Mints a trial macaroon (`mc_trial_<base64>`) bound to `seed_worker_pubkeys` and `max_matrix_dim`.
251
+ """
252
+ workers_raw = allowed_workers if allowed_workers is not None else (seed_worker_pubkeys or [])
253
+ now = int(time.time())
254
+ expires_at = now + int(expiry_seconds)
255
+ payload_dict: Dict[str, Any] = {
256
+ "tier": "FREE_TRIAL",
257
+ "task_id": str(task_id).strip(),
258
+ "job_id": str(job_id or task_id).strip(),
259
+ "allowed_workers": sorted(list({str(w).strip() for w in workers_raw if str(w).strip()})),
260
+ "max_matrix_dim": int(max_matrix_dim),
261
+ "locked_sats": 0,
262
+ "expires_at": expires_at,
263
+ "created_at": now,
264
+ }
265
+ canonical_str = json.dumps(payload_dict, sort_keys=True, separators=(",", ":"))
266
+ sig = hmac.new(
267
+ self.verification_key.encode("utf-8"),
268
+ canonical_str.encode("utf-8"),
269
+ hashlib.sha256,
270
+ ).hexdigest()
271
+ payload_dict["sig"] = sig
272
+ raw_json = json.dumps(payload_dict, separators=(",", ":"))
273
+ b64 = base64.urlsafe_b64encode(raw_json.encode("utf-8")).decode("ascii").rstrip("=")
274
+ return f"mc_trial_{b64}"
275
+
276
+ def verify_trial_macaroon(
277
+ self,
278
+ token: str,
279
+ worker_pubkey: Optional[str] = None,
280
+ m: int = 1,
281
+ k: int = 1,
282
+ n: int = 1,
283
+ current_time: Optional[float] = None,
284
+ ) -> Tuple[bool, str]:
285
+ """
286
+ Verifies a `mc_trial_<base64>` macaroon token.
287
+ Returns `(is_authorized, reason)`.
288
+ """
289
+ if not isinstance(token, str) or not token.strip().startswith("mc_trial_"):
290
+ return False, "INVALID_TOKEN_PREFIX"
291
+
292
+ b64_part = token.strip()[len("mc_trial_") :]
293
+ if not b64_part:
294
+ return False, "MALFORMED_MACAROON_PAYLOAD: empty payload"
295
+
296
+ rem = len(b64_part) % 4
297
+ if rem > 0:
298
+ b64_part += "=" * (4 - rem)
299
+
300
+ try:
301
+ if "-" in b64_part or "_" in b64_part:
302
+ raw_bytes = base64.urlsafe_b64decode(b64_part.encode("ascii"))
303
+ else:
304
+ raw_bytes = base64.b64decode(b64_part.encode("ascii"))
305
+ data = json.loads(raw_bytes.decode("utf-8"))
306
+ except Exception as ex:
307
+ return False, f"MALFORMED_MACAROON_PAYLOAD: {ex}"
308
+
309
+ if not isinstance(data, dict):
310
+ return False, "MALFORMED_MACAROON_PAYLOAD: not a JSON object"
311
+
312
+ if "caveats" in data and isinstance(data["caveats"], dict):
313
+ caveats = dict(data["caveats"])
314
+ sig = data.get("signature")
315
+ canonical_str = json.dumps(caveats, sort_keys=True)
316
+ else:
317
+ caveats = dict(data)
318
+ sig = caveats.pop("sig", None)
319
+ canonical_str = json.dumps(caveats, sort_keys=True, separators=(",", ":"))
320
+
321
+ if not sig or not isinstance(sig, str):
322
+ return False, "MISSING_SIGNATURE"
323
+
324
+ expected_sig = hmac.new(
325
+ self.verification_key.encode("utf-8"),
326
+ canonical_str.encode("utf-8"),
327
+ hashlib.sha256,
328
+ ).hexdigest()
329
+
330
+ if not hmac.compare_digest(sig, expected_sig):
331
+ return False, "SIGNATURE_VERIFICATION_FAILED"
332
+
333
+ now = float(current_time if current_time is not None else time.time())
334
+ exp = caveats.get("expires_at") if "expires_at" in caveats else caveats.get("expiry", 0)
335
+ if not isinstance(exp, (int, float)) or now > float(exp):
336
+ return False, "TOKEN_EXPIRED"
337
+
338
+ eff_worker = worker_pubkey if worker_pubkey is not None else self.worker_pubkey
339
+ allowed_workers = caveats.get("allowed_workers", [])
340
+ if eff_worker is not None:
341
+ clean_w = str(eff_worker).strip().lower()
342
+ if not isinstance(allowed_workers, list) or not any(
343
+ hmac.compare_digest(clean_w, str(w).strip().lower()) for w in allowed_workers
344
+ ):
345
+ return False, "PERMISSION_DENIED: Trial macaroon not authorized on third-party worker"
346
+ elif not self.is_seed_worker:
347
+ return False, "PERMISSION_DENIED: Trial macaroon not authorized on third-party worker"
348
+
349
+ max_dim = int(caveats.get("max_matrix_dim", 4096))
350
+ if max(int(m), int(k), int(n)) > max_dim:
351
+ return False, f"PERMISSION_DENIED: Trial macaroon dimension exceeds {max_dim} cap"
352
+
353
+ return True, "AUTHORIZED"
354
+
355
+ def verify_token(
356
+ self,
357
+ auth_header: str,
358
+ task_id: Optional[str] = None,
359
+ m: int = 1,
360
+ k: int = 1,
361
+ n: int = 1,
362
+ current_time: Optional[float] = None,
363
+ x_task_id: Optional[str] = None,
364
+ worker_pubkey: Optional[str] = None,
365
+ ) -> Tuple[bool, Optional[str], Optional[str]]:
366
+ """
367
+ Executes the 5-Step Pre-Allocation Validation Gate:
368
+ 1. Header Extraction: Parses 'Authorization: L402 <macaroon>:<payment_hash>'.
369
+ 2. HMAC Verification: Cryptographically validates Macaroon against verification_key.
370
+ 3. Task Caveats: Asserts task_id containment, caveat.payment_hash == payment_hash, and caveat.expiry > current_time.
371
+ 4. Workload Bounding: Asserts caveat.max_gflops >= (2*M*N*K)/1e9 and payment sufficiency with min_task_sats floor.
372
+ 5. Settlement Lock Check: Asserts payment_hash status is actively HELD (via in-memory cache hit or settlement backend).
373
+
374
+ Returns:
375
+ (is_valid, error_message, error_code)
376
+ """
377
+ # Step 1: Header Extraction
378
+ macaroon_b64, payment_hash = self.parse_auth_header(auth_header)
379
+ if not macaroon_b64 or not payment_hash:
380
+ return False, "Missing or malformed L402 Authorization header", "UNAUTHENTICATED"
381
+
382
+ clean_payment_hash = payment_hash.strip().lower()
383
+
384
+ # Fast-path for Zero-Drain Trial Macaroons (`mc_trial_<base64>`)
385
+ if macaroon_b64.startswith("mc_trial_"):
386
+ ok, reason = self.verify_trial_macaroon(
387
+ token=macaroon_b64,
388
+ worker_pubkey=worker_pubkey,
389
+ m=m,
390
+ k=k,
391
+ n=n,
392
+ current_time=current_time,
393
+ )
394
+ if not ok:
395
+ err_code = "PERMISSION_DENIED" if "PERMISSION_DENIED" in reason else "UNAUTHENTICATED"
396
+ return False, reason, err_code
397
+ return True, None, "AUTHORIZED"
398
+
399
+ # Step 2: Decode & HMAC Verification
400
+ try:
401
+ raw_bytes = base64.b64decode(macaroon_b64)
402
+ payload = json.loads(raw_bytes.decode("utf-8"))
403
+ except Exception as ex:
404
+ return False, f"Malformed macaroon base64/JSON: {ex}", "UNAUTHENTICATED"
405
+
406
+ if not isinstance(payload, dict) or "caveats" not in payload or "signature" not in payload:
407
+ return False, "Malformed macaroon: missing caveats or signature", "UNAUTHENTICATED"
408
+
409
+ caveats = payload.get("caveats")
410
+ signature = payload.get("signature")
411
+ if not isinstance(caveats, dict) or not isinstance(signature, str):
412
+ return False, "Malformed macaroon structure", "UNAUTHENTICATED"
413
+
414
+ # Verify HMAC-SHA256
415
+ caveat_str = json.dumps(caveats, sort_keys=True)
416
+ expected_sig = hmac.new(
417
+ self.verification_key.encode("utf-8"),
418
+ caveat_str.encode("utf-8"),
419
+ hashlib.sha256,
420
+ ).hexdigest()
421
+
422
+ if not hmac.compare_digest(signature, expected_sig):
423
+ return False, "Invalid macaroon HMAC signature", "UNAUTHENTICATED"
424
+
425
+ # Step 3: Multi-Task Caveat Containment Check (Feature F6)
426
+ allowed_tasks: List[str] = []
427
+ caveat_tasks = caveats.get("task_ids") or caveats.get("task_batch") or caveats.get("tasks")
428
+ if caveat_tasks is not None:
429
+ if isinstance(caveat_tasks, list):
430
+ allowed_tasks.extend(str(t).strip() for t in caveat_tasks if str(t).strip())
431
+ elif isinstance(caveat_tasks, str):
432
+ allowed_tasks.extend(t.strip() for t in caveat_tasks.split(",") if t.strip())
433
+
434
+ caveat_task = caveats.get("task_id")
435
+ if caveat_task is not None:
436
+ clean_single = str(caveat_task).strip()
437
+ if clean_single and clean_single not in allowed_tasks:
438
+ allowed_tasks.append(clean_single)
439
+
440
+ target_task = str(x_task_id or task_id or "").strip()
441
+ if not target_task:
442
+ if len(allowed_tasks) == 1:
443
+ target_task = allowed_tasks[0]
444
+ else:
445
+ return (
446
+ False,
447
+ "Unable to determine task_id from L402 token or metadata",
448
+ "UNAUTHENTICATED",
449
+ )
450
+
451
+ if not allowed_tasks:
452
+ return (
453
+ False,
454
+ f"Macaroon caveats do not authorize requested task '{target_task}'",
455
+ "PERMISSION_DENIED",
456
+ )
457
+
458
+ task_matched = any(hmac.compare_digest(target_task, allowed) for allowed in allowed_tasks)
459
+ if not task_matched:
460
+ return (
461
+ False,
462
+ f"Macaroon caveats do not authorize requested task '{target_task}'",
463
+ "PERMISSION_DENIED",
464
+ )
465
+
466
+ caveat_payment_hash = str(caveats.get("payment_hash", "")).strip().lower()
467
+ if not caveat_payment_hash or not hmac.compare_digest(caveat_payment_hash, clean_payment_hash):
468
+ return (
469
+ False,
470
+ f"Macaroon caveat payment_hash '{caveat_payment_hash}' does not match Authorization payment_hash '{payment_hash}'",
471
+ "PERMISSION_DENIED",
472
+ )
473
+
474
+ now = current_time if current_time is not None else time.time()
475
+ expiry = caveats.get("expiry")
476
+ if expiry is None or not isinstance(expiry, (int, float)) or expiry <= now:
477
+ return False, f"Macaroon expired at {expiry} (current time: {int(now)})", "UNAUTHENTICATED"
478
+
479
+ # Step 4: Workload Bounding & Rate Enforcement
480
+ requested_gflops = (2.0 * float(m) * float(k) * float(n)) / 1e9
481
+ max_gflops = caveats.get("max_gflops")
482
+ if max_gflops is None or not isinstance(max_gflops, (int, float)) or max_gflops < requested_gflops:
483
+ return (
484
+ False,
485
+ f"Insufficient GFLOP allowance in macaroon: permitted {max_gflops}, requested {requested_gflops:.6f}",
486
+ "PERMISSION_DENIED",
487
+ )
488
+
489
+ # Rate check if locked_sats is specified with min_task_sats floor
490
+ if "locked_sats" in caveats:
491
+ locked_sats = caveats["locked_sats"]
492
+ if not isinstance(locked_sats, (int, float)):
493
+ return False, "Malformed locked_sats caveat: must be numeric", "UNAUTHENTICATED"
494
+ computed_sats = math.ceil(requested_gflops * self.min_price_rate)
495
+ required_sats = max(computed_sats, self.min_task_sats)
496
+ if locked_sats < required_sats:
497
+ return (
498
+ False,
499
+ f"Underpayment detected: locked {locked_sats} sats < required {required_sats} sats",
500
+ "FAILED_PRECONDITION",
501
+ )
502
+
503
+ # Step 5: Settlement HODL Lock Verification with Gate Caching (Feature F5)
504
+ # 5a. Check in-memory cache under lock
505
+ with self._lock:
506
+ if clean_payment_hash in self._verified_cache:
507
+ cached_status, expires_at = self._verified_cache[clean_payment_hash]
508
+ if now < expires_at and cached_status == "HELD":
509
+ self.cache_hit_count += 1
510
+ self._verified_cache.move_to_end(clean_payment_hash)
511
+ return True, "Token verified and payment held (cached)", "AUTHORIZED"
512
+ elif now >= expires_at:
513
+ self._verified_cache.pop(clean_payment_hash, None)
514
+
515
+ # 5b. Cache miss: query settlement backend (outside lock to prevent blocking)
516
+ if not self.settlement_client:
517
+ return (
518
+ False,
519
+ "Settlement verification is unconfigured (fail-closed)",
520
+ None,
521
+ )
522
+
523
+ self.remote_query_count += 1
524
+ status, query_err = self._query_settlement_backend(clean_payment_hash)
525
+ if query_err:
526
+ return False, query_err, "FAILED_PRECONDITION"
527
+
528
+ if status != "HELD":
529
+ return (
530
+ False,
531
+ f"Payment hash '{payment_hash}' is in state '{status}', expected 'HELD'",
532
+ "FAILED_PRECONDITION",
533
+ )
534
+
535
+ # 5c. Backend returned HELD: compute expires_at and record in cache under lock
536
+ caveat_expiry = float(expiry) if expiry is not None else float("inf")
537
+ ttl_expiry = now + self.cache_ttl_seconds
538
+ entry_expiry = min(caveat_expiry, ttl_expiry)
539
+
540
+ with self._lock:
541
+ if clean_payment_hash in self._verified_cache:
542
+ self._verified_cache.move_to_end(clean_payment_hash)
543
+ self._verified_cache[clean_payment_hash] = ("HELD", entry_expiry)
544
+
545
+ if len(self._verified_cache) > self.max_cache_size:
546
+ self._evict_expired_unlocked(now)
547
+ while len(self._verified_cache) > self.max_cache_size:
548
+ self._verified_cache.popitem(last=False)
549
+
550
+ return True, None, None
551
+
552
+ # Alias for test compatibility
553
+ verify_request = verify_token
src/config/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """Configuration subsystem for matrix-compute-node."""
2
+ from .settings import NodeConfig
3
+
4
+ __all__ = ["NodeConfig"]