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.
@@ -0,0 +1,410 @@
1
+ """In-memory Mock Settlement Service test double for offline L402 testing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ from dataclasses import dataclass, field
7
+ from enum import Enum
8
+ import hashlib
9
+ import hmac
10
+ import json
11
+ import secrets
12
+ import threading
13
+ import time
14
+ from typing import Any, Dict, List, Optional, Tuple, Union
15
+
16
+ from matrix_contracts.schemas.settlement import (
17
+ CreateHodlInvoiceRequest,
18
+ CreateHodlInvoiceResponse,
19
+ SettlePaymentRequest,
20
+ )
21
+
22
+
23
+ class InvoiceStatus(str, Enum):
24
+ UNPAID = "UNPAID"
25
+ HELD = "HELD"
26
+ SETTLED = "SETTLED"
27
+ CANCELLED = "CANCELLED"
28
+
29
+
30
+ class MockInvoiceResponse(CreateHodlInvoiceResponse):
31
+ """
32
+ Response model compatible with both Pydantic attribute access (resp.payment_hash)
33
+ and dict-like subscription (resp["payment_hash"], resp.get("preimage")).
34
+ """
35
+ preimage: Optional[str] = None
36
+
37
+ def __getitem__(self, item: str) -> Any:
38
+ try:
39
+ return getattr(self, item)
40
+ except AttributeError:
41
+ raise KeyError(item)
42
+
43
+ def get(self, item: str, default: Any = None) -> Any:
44
+ return getattr(self, item, default)
45
+
46
+ def __contains__(self, item: str) -> bool:
47
+ return hasattr(self, item)
48
+
49
+
50
+ @dataclass
51
+ class InvoiceRecord:
52
+ task_id: str
53
+ payment_hash: str
54
+ total_compute_sats: int
55
+ platform_fee_percent: float
56
+ platform_fee_sats: int
57
+ worker_payout_sats: int
58
+ worker_lightning_address: str
59
+ payment_request: str
60
+ macaroon: str
61
+ status: InvoiceStatus = InvoiceStatus.UNPAID
62
+ preimage: Optional[str] = None
63
+ created_at: float = field(default_factory=time.time)
64
+ expires_at: float = 0.0
65
+ max_gflops: float = 100.0
66
+ task_ids: Optional[List[str]] = None
67
+ job_id: Optional[str] = None
68
+
69
+
70
+ class MockSettlementService:
71
+ """
72
+ Hermetic in-memory Settlement Service and L402 Macaroon issuer.
73
+ Simulates the Lightning HODL invoice lifecycle: UNPAID -> HELD -> SETTLED.
74
+ """
75
+
76
+ def __init__(self, verification_key: str = "settlement-secret-verification-key-12345"):
77
+ self.verification_key = verification_key
78
+ self._lock = threading.Lock()
79
+ self._invoices: Dict[str, InvoiceRecord] = {} # payment_hash -> record
80
+ self._task_index: Dict[str, str] = {} # task_id -> payment_hash
81
+ self.query_count: int = 0
82
+
83
+ def _mint_macaroon(
84
+ self,
85
+ payment_hash: str,
86
+ task_id: str,
87
+ expires_at: int,
88
+ max_gflops: float,
89
+ locked_sats: int = 100,
90
+ task_ids: Optional[List[str]] = None,
91
+ job_id: Optional[str] = None,
92
+ ) -> str:
93
+ """Mints an HMAC-SHA256 authenticated L402 Macaroon token."""
94
+ caveats: Dict[str, Any] = {
95
+ "expiry": int(expires_at),
96
+ "locked_sats": locked_sats,
97
+ "max_gflops": float(max_gflops),
98
+ "payment_hash": payment_hash,
99
+ "task_id": task_id,
100
+ }
101
+ if task_ids is not None:
102
+ caveats["task_ids"] = [str(t).strip() for t in task_ids if str(t).strip()]
103
+ if job_id is not None:
104
+ caveats["job_id"] = str(job_id).strip()
105
+
106
+ caveat_str = json.dumps(caveats, sort_keys=True)
107
+ sig = hmac.new(
108
+ self.verification_key.encode("utf-8"),
109
+ caveat_str.encode("utf-8"),
110
+ hashlib.sha256,
111
+ ).hexdigest()
112
+ payload = {"caveats": caveats, "signature": sig}
113
+ return base64.b64encode(json.dumps(payload).encode("utf-8")).decode("utf-8")
114
+
115
+ def verify_macaroon(
116
+ self,
117
+ macaroon_raw: str,
118
+ expected_task_id: str,
119
+ required_gflops: float,
120
+ current_time: Optional[float] = None,
121
+ ) -> Tuple[bool, str]:
122
+ """
123
+ Verifies an L402 Macaroon:
124
+ 1. Validates HMAC-SHA256 signature against verification key.
125
+ 2. Asserts caveat task containment (expected_task_id in task_ids or == task_id).
126
+ 3. Asserts caveat expiry > current_time.
127
+ 4. Asserts caveat max_gflops >= required_gflops.
128
+ """
129
+ try:
130
+ raw_bytes = base64.b64decode(macaroon_raw)
131
+ payload = json.loads(raw_bytes.decode("utf-8"))
132
+ if not isinstance(payload, dict):
133
+ return False, "Malformed macaroon token: payload must be a JSON object"
134
+ if "caveats" not in payload or "signature" not in payload:
135
+ return False, "Malformed macaroon token: missing caveats or signature"
136
+ caveats = payload["caveats"]
137
+ signature = payload["signature"]
138
+ if not isinstance(signature, str):
139
+ return False, "Malformed macaroon signature"
140
+ if not isinstance(caveats, dict):
141
+ return False, "Malformed macaroon token: caveats must be a JSON object"
142
+
143
+ # 1. Verify HMAC signature
144
+ caveat_str = json.dumps(caveats, sort_keys=True)
145
+ expected_sig = hmac.new(
146
+ self.verification_key.encode("utf-8"),
147
+ caveat_str.encode("utf-8"),
148
+ hashlib.sha256,
149
+ ).hexdigest()
150
+
151
+ if not hmac.compare_digest(signature, expected_sig):
152
+ return False, "Invalid macaroon HMAC signature"
153
+
154
+ # 2. Check task_id containment
155
+ allowed_tasks: List[str] = []
156
+ caveat_tasks = caveats.get("task_ids") or caveats.get("task_batch") or caveats.get("tasks")
157
+ if caveat_tasks is not None:
158
+ if isinstance(caveat_tasks, list):
159
+ allowed_tasks.extend(str(t).strip() for t in caveat_tasks if str(t).strip())
160
+ elif isinstance(caveat_tasks, str):
161
+ allowed_tasks.extend(t.strip() for t in caveat_tasks.split(",") if t.strip())
162
+
163
+ caveat_task = caveats.get("task_id")
164
+ if caveat_task is not None:
165
+ clean_single = str(caveat_task).strip()
166
+ if clean_single and clean_single not in allowed_tasks:
167
+ allowed_tasks.append(clean_single)
168
+
169
+ clean_expected = expected_task_id.strip()
170
+ if not any(hmac.compare_digest(clean_expected, allowed) for allowed in allowed_tasks):
171
+ return False, f"Caveat task_id mismatch: task '{expected_task_id}' not in authorized {allowed_tasks}"
172
+
173
+ # 3. Check expiry caveat
174
+ now = current_time if current_time is not None else time.time()
175
+ expiry = caveats.get("expiry", 0)
176
+ if not isinstance(expiry, (int, float)) or expiry <= now:
177
+ return False, f"Macaroon expired at {expiry} (current: {int(now)})"
178
+
179
+ # 4. Check max_gflops caveat
180
+ max_gflops = caveats.get("max_gflops", 0.0)
181
+ if not isinstance(max_gflops, (int, float)) or max_gflops < required_gflops:
182
+ return False, f"Insufficient GFLOP allowance: {max_gflops} < {required_gflops}"
183
+
184
+ return True, "OK"
185
+ except Exception as ex:
186
+ return False, f"Malformed macaroon token: {ex}"
187
+
188
+ def create_hodl_invoice(
189
+ self,
190
+ task_id_or_request: Union[str, CreateHodlInvoiceRequest] = "",
191
+ total_compute_sats: Optional[int] = None,
192
+ platform_fee_percent: float = 0.05,
193
+ worker_lightning_address: str = "worker@testnode.local",
194
+ payment_hash: Optional[str] = None,
195
+ expiry_seconds: int = 3600,
196
+ max_gflops: float = 100.0,
197
+ task_ids: Optional[List[str]] = None,
198
+ job_id: Optional[str] = None,
199
+ **kwargs: Any,
200
+ ) -> MockInvoiceResponse:
201
+ """
202
+ Creates a HODL invoice in UNPAID status.
203
+ Supports both Pydantic request object and direct keyword arguments,
204
+ with multi-task batch escrow support.
205
+ """
206
+ resolved_task_ids: Optional[List[str]] = task_ids or kwargs.get("task_ids")
207
+ resolved_job_id: Optional[str] = job_id or kwargs.get("job_id")
208
+
209
+ if isinstance(task_id_or_request, CreateHodlInvoiceRequest):
210
+ req = task_id_or_request
211
+ task_id = req.task_id or ""
212
+ if resolved_task_ids is None and hasattr(req, "task_ids"):
213
+ resolved_task_ids = req.task_ids
214
+ if resolved_job_id is None and hasattr(req, "job_id"):
215
+ resolved_job_id = req.job_id
216
+ compute_sats = req.total_compute_sats
217
+ fee_pct = req.platform_fee_percent
218
+ worker_ln = req.worker_lightning_address
219
+ p_hash = req.payment_hash
220
+ else:
221
+ task_id = str(task_id_or_request or kwargs.get("task_id", ""))
222
+ compute_sats = total_compute_sats if total_compute_sats is not None else kwargs.get("total_compute_sats", 100)
223
+ fee_pct = kwargs.get("platform_fee_percent", platform_fee_percent)
224
+ worker_ln = kwargs.get("worker_lightning_address", worker_lightning_address)
225
+ p_hash = payment_hash if payment_hash is not None else kwargs.get("payment_hash")
226
+
227
+ if not task_id and resolved_task_ids:
228
+ task_id = resolved_task_ids[0]
229
+
230
+ # Resolve payment_hash & preimage
231
+ if p_hash:
232
+ final_hash = p_hash.strip().lower()
233
+ preimage = None
234
+ else:
235
+ preimage_bytes = secrets.token_bytes(32)
236
+ preimage = preimage_bytes.hex()
237
+ final_hash = hashlib.sha256(preimage_bytes).hexdigest()
238
+
239
+ with self._lock:
240
+ # Reject duplicate task ID
241
+ if task_id and task_id in self._task_index:
242
+ raise ValueError(f"Task ID already registered: '{task_id}'")
243
+ if resolved_task_ids:
244
+ for tid in resolved_task_ids:
245
+ if tid in self._task_index:
246
+ raise ValueError(f"Task ID already registered: '{tid}'")
247
+
248
+ # Reject duplicate payment hash
249
+ if final_hash in self._invoices:
250
+ raise ValueError(f"Duplicate payment hash '{final_hash}' already exists")
251
+
252
+ platform_fee_sats = int(round(compute_sats * fee_pct))
253
+ worker_payout_sats = compute_sats - platform_fee_sats
254
+ now = time.time()
255
+ expires_at = int(now + expiry_seconds)
256
+
257
+ macaroon_str = self._mint_macaroon(
258
+ payment_hash=final_hash,
259
+ task_id=task_id,
260
+ expires_at=expires_at,
261
+ max_gflops=max_gflops,
262
+ locked_sats=compute_sats,
263
+ task_ids=resolved_task_ids,
264
+ job_id=resolved_job_id,
265
+ )
266
+
267
+ payment_request = f"lnbc{compute_sats}000n1p{final_hash[:20]}mockhodl"
268
+
269
+ record = InvoiceRecord(
270
+ task_id=task_id,
271
+ payment_hash=final_hash,
272
+ total_compute_sats=compute_sats,
273
+ platform_fee_percent=fee_pct,
274
+ platform_fee_sats=platform_fee_sats,
275
+ worker_payout_sats=worker_payout_sats,
276
+ worker_lightning_address=worker_ln,
277
+ payment_request=payment_request,
278
+ macaroon=macaroon_str,
279
+ status=InvoiceStatus.UNPAID,
280
+ preimage=preimage,
281
+ created_at=now,
282
+ expires_at=float(expires_at),
283
+ max_gflops=max_gflops,
284
+ task_ids=resolved_task_ids,
285
+ job_id=resolved_job_id,
286
+ )
287
+
288
+ self._invoices[final_hash] = record
289
+ if task_id:
290
+ self._task_index[task_id] = final_hash
291
+ if resolved_task_ids:
292
+ for tid in resolved_task_ids:
293
+ self._task_index[tid] = final_hash
294
+
295
+ return MockInvoiceResponse(
296
+ payment_hash=final_hash,
297
+ payment_request=payment_request,
298
+ platform_fee_sats=platform_fee_sats,
299
+ worker_payout_sats=worker_payout_sats,
300
+ macaroon=macaroon_str,
301
+ preimage=preimage,
302
+ )
303
+
304
+ def hold_invoice(self, payment_hash: str) -> bool:
305
+ """
306
+ Transitions invoice status from UNPAID -> HELD.
307
+ Simulates consumer locking funds in Lightning routing.
308
+ """
309
+ clean_hash = str(payment_hash).strip().lower()
310
+ with self._lock:
311
+ if clean_hash not in self._invoices:
312
+ raise KeyError(f"Payment hash '{payment_hash}' not found")
313
+ record = self._invoices[clean_hash]
314
+ if record.status != InvoiceStatus.UNPAID:
315
+ raise ValueError(f"Cannot hold invoice in status '{record.status.value}'; must be UNPAID")
316
+ record.status = InvoiceStatus.HELD
317
+ return True
318
+
319
+ def is_held(self, payment_hash: str) -> bool:
320
+ """Returns True if and only if invoice status is HELD."""
321
+ clean_hash = str(payment_hash).strip().lower()
322
+ with self._lock:
323
+ record = self._invoices.get(clean_hash)
324
+ return record is not None and record.status == InvoiceStatus.HELD
325
+
326
+ def get_status(self, payment_hash: str) -> Optional[str]:
327
+ """Returns the current invoice status string ('UNPAID', 'HELD', 'SETTLED', 'CANCELLED')."""
328
+ clean_hash = str(payment_hash).strip().lower()
329
+ with self._lock:
330
+ self.query_count += 1
331
+ record = self._invoices.get(clean_hash)
332
+ return record.status.value if record else None
333
+
334
+ def get_invoice_status(self, payment_hash: str) -> Optional[str]:
335
+ """Alias for get_status."""
336
+ return self.get_status(payment_hash)
337
+
338
+ def settle_invoice(
339
+ self,
340
+ hash_or_request: Union[str, SettlePaymentRequest],
341
+ preimage: Optional[str] = None,
342
+ ) -> bool:
343
+ """
344
+ Settles HODL payment upon revelation of the secret preimage.
345
+ Transitions invoice status from HELD -> SETTLED.
346
+ Supports both settle_invoice(hash, preimage=...) and settle_invoice(SettlePaymentRequest).
347
+ """
348
+ with self._lock:
349
+ if isinstance(hash_or_request, SettlePaymentRequest):
350
+ task_id = hash_or_request.task_id
351
+ clean_hash = self._task_index.get(task_id)
352
+ if not clean_hash or clean_hash not in self._invoices:
353
+ raise KeyError(f"No invoice found for task ID '{task_id}'")
354
+ clean_preimage = hash_or_request.preimage.strip().lower()
355
+ else:
356
+ first_arg = str(hash_or_request).strip().lower()
357
+ if first_arg in self._invoices:
358
+ clean_hash = first_arg
359
+ elif first_arg in self._task_index:
360
+ clean_hash = self._task_index[first_arg]
361
+ else:
362
+ raise KeyError(f"Payment hash or task ID '{hash_or_request}' not found")
363
+
364
+ clean_preimage = str(preimage).strip().lower() if preimage is not None else None
365
+
366
+ record = self._invoices[clean_hash]
367
+ if record.status != InvoiceStatus.HELD:
368
+ raise ValueError(f"Cannot settle invoice in status '{record.status.value}'; must be HELD")
369
+
370
+ if clean_preimage is None:
371
+ if record.preimage:
372
+ clean_preimage = record.preimage
373
+ else:
374
+ raise ValueError("Preimage is required to settle invoice")
375
+
376
+ try:
377
+ preimage_bytes = bytes.fromhex(clean_preimage)
378
+ except Exception:
379
+ raise ValueError("Preimage is not a valid hexadecimal string")
380
+
381
+ computed_hash = hashlib.sha256(preimage_bytes).hexdigest()
382
+ if computed_hash != record.payment_hash:
383
+ raise ValueError(f"Preimage hash {computed_hash} does not match invoice hash {record.payment_hash}")
384
+
385
+ record.preimage = clean_preimage
386
+ record.status = InvoiceStatus.SETTLED
387
+ return True
388
+
389
+ def cancel_invoice(self, payment_hash: str) -> bool:
390
+ """Cancels an UNPAID or HELD invoice."""
391
+ clean_hash = str(payment_hash).strip().lower()
392
+ with self._lock:
393
+ if clean_hash not in self._invoices:
394
+ raise KeyError(f"Payment hash '{payment_hash}' not found")
395
+ record = self._invoices[clean_hash]
396
+ if record.status == InvoiceStatus.SETTLED:
397
+ raise ValueError("Cannot cancel an already SETTLED invoice")
398
+ record.status = InvoiceStatus.CANCELLED
399
+ return True
400
+
401
+ def reset(self) -> None:
402
+ """Clears all stored invoices for test isolation."""
403
+ with self._lock:
404
+ self._invoices.clear()
405
+ self._task_index.clear()
406
+ self.query_count = 0
407
+
408
+ def clear(self) -> None:
409
+ """Alias for reset."""
410
+ self.reset()