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/p2p/servicer.py ADDED
@@ -0,0 +1,893 @@
1
+ """P2P gRPC Compute Servicer implementation for matrix-compute-node."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import logging
7
+ import threading
8
+ import time
9
+ from collections import OrderedDict
10
+ from typing import Any, Dict, Iterator, Optional, Set
11
+
12
+ import grpc
13
+ import numpy as np
14
+
15
+ from matrix_contracts.v1 import pb2, pb2_grpc
16
+ from src.auth.hashcash import HashcashVerifier
17
+ from src.auth.l402_gate import L402PreAllocationGate
18
+ from src.crypto.signer import WorkerSigner
19
+ from src.engine.compute_core import ComputeEngine
20
+ from src.engine.scheduler import PreemptiveComputeScheduler, PriorityTier
21
+ from src.engine.enclave_compute import (
22
+ EnclaveComputeCore,
23
+ EnclaveDecryptionError,
24
+ EnclaveExecutionError,
25
+ EnclaveFramingError,
26
+ EnclaveKeyExchangeError,
27
+ EnclaveSecurityPolicyError,
28
+ aes_gcm_decrypt,
29
+ aes_gcm_encrypt,
30
+ derive_session_keys,
31
+ )
32
+ from src.engine.session_manager import SessionExpiredError, SessionManager
33
+ from src.attestation.base import BaseAttestationProvider
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+
38
+ class TaskMetadataStore:
39
+ """Thread-safe bounded LRU and TTL store for negotiated task metadata."""
40
+
41
+ def __init__(self, max_size: int = 1000, ttl_seconds: float = 3600.0) -> None:
42
+ self.max_size = max_size
43
+ self.ttl_seconds = ttl_seconds
44
+ self._store: OrderedDict[str, Dict[str, Any]] = OrderedDict()
45
+ self._lock = threading.RLock()
46
+
47
+ def evict_expired(self, now: Optional[float] = None) -> None:
48
+ current_time = now if now is not None else time.time()
49
+ with self._lock:
50
+ expired_keys = [
51
+ k for k, v in self._store.items()
52
+ if current_time - v.get("created_at", 0) > self.ttl_seconds
53
+ ]
54
+ for k in expired_keys:
55
+ self._store.pop(k, None)
56
+
57
+ def get(self, task_id: str, default: Any = None) -> Optional[Dict[str, Any]]:
58
+ with self._lock:
59
+ self.evict_expired()
60
+ if task_id in self._store:
61
+ self._store.move_to_end(task_id)
62
+ return self._store[task_id]
63
+ return default
64
+
65
+ def set(self, task_id: str, data: Dict[str, Any]) -> None:
66
+ with self._lock:
67
+ self.evict_expired()
68
+ if task_id in self._store:
69
+ self._store.move_to_end(task_id)
70
+ self._store[task_id] = data
71
+ while len(self._store) > self.max_size:
72
+ self._store.popitem(last=False)
73
+
74
+ def pop(self, task_id: str, default: Any = None) -> Optional[Dict[str, Any]]:
75
+ with self._lock:
76
+ return self._store.pop(task_id, default)
77
+
78
+ def __getitem__(self, task_id: str) -> Dict[str, Any]:
79
+ val = self.get(task_id)
80
+ if val is None:
81
+ raise KeyError(task_id)
82
+ return val
83
+
84
+ def __setitem__(self, task_id: str, data: Dict[str, Any]) -> None:
85
+ self.set(task_id, data)
86
+
87
+ def __contains__(self, task_id: str) -> bool:
88
+ with self._lock:
89
+ self.evict_expired()
90
+ return task_id in self._store
91
+
92
+ def __len__(self) -> int:
93
+ with self._lock:
94
+ self.evict_expired()
95
+ return len(self._store)
96
+
97
+
98
+ class MatrixComputeServicer(pb2_grpc.MatrixComputeServiceServicer):
99
+ """
100
+ gRPC Servicer implementing MatrixComputeService:
101
+ 1. RequestTileTask: Handshake, parameter validation, GFLOP quotation, and readiness.
102
+ 2. ExecuteTileTask: Strict pre-allocation L402 verification, streaming chunk ingestion,
103
+ GEMM calculation, SHA256 hashing, and worker cryptographic signing.
104
+ 3. LeaseMatrix: Pins matrix A in VRAM/memory across iterative steps.
105
+ 4. StepIterative: Fast iterative GEMV matrix-vector steps (v_{t+1} = A * v_t).
106
+ 5. ReleaseLease: Explicit zeroization and VRAM deallocation.
107
+ """
108
+
109
+ def __init__(
110
+ self,
111
+ signer: Optional[WorkerSigner] = None,
112
+ gate: Optional[L402PreAllocationGate] = None,
113
+ engine: Optional[ComputeEngine] = None,
114
+ config: Optional[Any] = None,
115
+ attestation_provider: Optional[BaseAttestationProvider] = None,
116
+ enclave_core: Optional[EnclaveComputeCore] = None,
117
+ session_manager: Optional[SessionManager] = None,
118
+ scheduler: Optional[PreemptiveComputeScheduler] = None,
119
+ hashcash_verifier: Optional[HashcashVerifier] = None,
120
+ ) -> None:
121
+ self.signer = signer
122
+ self.gate = gate
123
+ self.engine = engine or ComputeEngine()
124
+ self.config = config
125
+ self.scheduler = scheduler or PreemptiveComputeScheduler()
126
+ self.hashcash_verifier = hashcash_verifier or HashcashVerifier(
127
+ min_bits=getattr(config, "trial_pow_bits", 12) if config else 12
128
+ )
129
+ self.enclave_core = enclave_core or EnclaveComputeCore(
130
+ compute_engine=self.engine,
131
+ max_sessions=1000,
132
+ session_ttl_seconds=3600.0,
133
+ )
134
+ self.session_manager = session_manager or SessionManager(
135
+ max_sessions=getattr(config, "max_sessions", 100) if config else 100,
136
+ max_memory_bytes=getattr(config, "max_memory_bytes", 4 * 1024 * 1024 * 1024) if config else 4 * 1024 * 1024 * 1024,
137
+ default_ttl_seconds=getattr(config, "lease_default_ttl_seconds", 3600.0) if config else 3600.0,
138
+ compute_engine=self.engine,
139
+ )
140
+
141
+ if attestation_provider is not None:
142
+ self.attestation_provider = attestation_provider
143
+ elif config is not None and getattr(config, "enable_confidential_compute", False):
144
+ prov_type = getattr(config, "attestation_provider", "auto")
145
+ if prov_type and prov_type.lower() != "none":
146
+ try:
147
+ from src.attestation.base import get_attestation_provider
148
+ self.attestation_provider = get_attestation_provider(
149
+ provider_type=prov_type,
150
+ device_index=getattr(config, "gpu_device_index", 0),
151
+ fallback_to_simulated=True,
152
+ )
153
+ except Exception as exc:
154
+ logger.warning("Failed initializing attestation provider from config: %s", exc)
155
+ self.attestation_provider = None
156
+ else:
157
+ self.attestation_provider = None
158
+ else:
159
+ self.attestation_provider = None
160
+
161
+ self._lock = threading.Lock()
162
+ self._task_metadata = TaskMetadataStore(max_size=1000, ttl_seconds=3600.0)
163
+ self._active_tasks: Set[str] = set()
164
+
165
+ def RequestTileTask(
166
+ self,
167
+ request: pb2.TileTaskRequest,
168
+ context: Optional[grpc.ServicerContext] = None,
169
+ ) -> pb2.TileTaskAck:
170
+ """
171
+ Step 1: Handshake, parameter validation, theoretical GFLOP estimation,
172
+ and Confidential Computing attestation evidence generation.
173
+ """
174
+ with self._lock:
175
+ if request.task_id in self._active_tasks:
176
+ self._abort(
177
+ context,
178
+ grpc.StatusCode.FAILED_PRECONDITION,
179
+ f"Task '{request.task_id}' is currently in active streaming execution",
180
+ )
181
+
182
+ if request.matrix_a_rows <= 0 or request.matrix_a_cols <= 0 or request.matrix_b_cols <= 0:
183
+ self._abort(context, grpc.StatusCode.INVALID_ARGUMENT, "Matrix dimensions must be positive integers")
184
+
185
+ m = int(request.matrix_a_rows)
186
+ k = int(request.matrix_a_cols)
187
+ n = int(request.matrix_b_cols)
188
+
189
+ max_elem_limit = 64 * 1024 * 1024
190
+ if (m * n) > max_elem_limit or max(m, n) > 16384:
191
+ self._abort(
192
+ context,
193
+ grpc.StatusCode.INVALID_ARGUMENT,
194
+ f"Tile dimensions ({m}x{k} @ {k}x{n}) exceed maximum allowed allocation limits (max_elem={max_elem_limit}, max_dim=16384)",
195
+ )
196
+
197
+ dtype = (request.dtype or "fp32").lower().strip()
198
+ if dtype not in ("fp32", "fp16", "bf16"):
199
+ self._abort(context, grpc.StatusCode.INVALID_ARGUMENT, f"Unsupported dtype: {dtype}")
200
+
201
+ estimated_gflops = (2.0 * float(m) * float(k) * float(n)) / 1e9
202
+
203
+ worker_ephemeral_pubkey = b""
204
+ attestation_evidence_bytes = b""
205
+ tee_type = ""
206
+ worker_ephemeral_priv = None
207
+
208
+ if request.require_confidential_compute:
209
+ if self.attestation_provider is None or not self.attestation_provider.is_available():
210
+ if context is not None:
211
+ context.abort(
212
+ grpc.StatusCode.FAILED_PRECONDITION,
213
+ "Confidential computing requested but worker has no operational attestation provider",
214
+ )
215
+ raise RuntimeError(
216
+ "Confidential computing requested but worker has no operational attestation provider"
217
+ )
218
+
219
+ req_tee = request.required_tee_type.strip() if request.required_tee_type else ""
220
+ if req_tee and req_tee not in (self.attestation_provider.provider_name, "any"):
221
+ if context is not None:
222
+ context.abort(
223
+ grpc.StatusCode.UNIMPLEMENTED,
224
+ f"Worker TEE type '{self.attestation_provider.provider_name}' does not match requested '{req_tee}'",
225
+ )
226
+ raise ValueError(
227
+ f"Worker TEE type '{self.attestation_provider.provider_name}' does not match requested '{req_tee}'"
228
+ )
229
+
230
+ if not request.client_ephemeral_pubkey or len(request.client_ephemeral_pubkey) != 32:
231
+ if context is not None:
232
+ context.abort(grpc.StatusCode.INVALID_ARGUMENT, "client_ephemeral_pubkey must be exactly 32 bytes")
233
+ raise ValueError("client_ephemeral_pubkey must be exactly 32 bytes")
234
+
235
+ if not request.attestation_nonce or len(request.attestation_nonce) != 32:
236
+ if context is not None:
237
+ context.abort(grpc.StatusCode.INVALID_ARGUMENT, "attestation_nonce must be exactly 32 bytes")
238
+ raise ValueError("attestation_nonce must be exactly 32 bytes")
239
+
240
+ # Generate worker ephemeral X25519 keypair
241
+ from cryptography.hazmat.primitives.asymmetric import x25519
242
+ from cryptography.hazmat.primitives import serialization
243
+
244
+ worker_ephemeral_priv = x25519.X25519PrivateKey.generate()
245
+ worker_ephemeral_pub = worker_ephemeral_priv.public_key()
246
+ worker_ephemeral_pubkey = worker_ephemeral_pub.public_bytes(
247
+ encoding=serialization.Encoding.Raw,
248
+ format=serialization.PublicFormat.Raw,
249
+ )
250
+
251
+ # Generate hardware attestation evidence bound to challenger nonce and worker ephemeral pubkey
252
+ evidence = self.attestation_provider.generate_evidence(
253
+ nonce=request.attestation_nonce,
254
+ public_key=worker_ephemeral_pubkey,
255
+ )
256
+ attestation_evidence_bytes = evidence.to_bytes()
257
+ tee_type = self.attestation_provider.provider_name
258
+
259
+ with self._lock:
260
+ meta: Dict[str, Any] = {
261
+ "m": m,
262
+ "k": k,
263
+ "n": n,
264
+ "dtype": dtype,
265
+ "gflops": estimated_gflops,
266
+ "created_at": time.time(),
267
+ "is_confidential": bool(request.require_confidential_compute),
268
+ }
269
+ if request.require_confidential_compute:
270
+ meta.update({
271
+ "worker_ephemeral_priv": worker_ephemeral_priv,
272
+ "worker_ephemeral_pubkey": worker_ephemeral_pubkey,
273
+ "client_ephemeral_pubkey": request.client_ephemeral_pubkey,
274
+ "attestation_nonce": request.attestation_nonce,
275
+ })
276
+ try:
277
+ self.enclave_core.create_session(
278
+ task_id=request.task_id,
279
+ m=m,
280
+ k=k,
281
+ n=n,
282
+ dtype=dtype,
283
+ require_confidential=True,
284
+ client_ephemeral_pubkey=request.client_ephemeral_pubkey,
285
+ attestation_nonce=request.attestation_nonce,
286
+ worker_ephemeral_priv=worker_ephemeral_priv,
287
+ )
288
+ except EnclaveKeyExchangeError as exc:
289
+ self._abort(
290
+ context,
291
+ grpc.StatusCode.INVALID_ARGUMENT,
292
+ f"Enclave key exchange failed: {exc}",
293
+ )
294
+ else:
295
+ self.enclave_core.create_session(
296
+ task_id=request.task_id,
297
+ m=m,
298
+ k=k,
299
+ n=n,
300
+ dtype=dtype,
301
+ require_confidential=False,
302
+ )
303
+ self._task_metadata[request.task_id] = meta
304
+
305
+ worker_pubkey = self.signer.get_pubkey_hex() if self.signer is not None else ""
306
+
307
+ return pb2.TileTaskAck(
308
+ task_id=request.task_id,
309
+ is_ready=True,
310
+ estimated_gflops=estimated_gflops,
311
+ worker_pubkey=worker_pubkey,
312
+ message="Node ready",
313
+ worker_ephemeral_pubkey=worker_ephemeral_pubkey,
314
+ attestation_evidence=attestation_evidence_bytes,
315
+ tee_type=tee_type,
316
+ )
317
+
318
+ def _abort(self, context: Optional[grpc.ServicerContext], status_code: grpc.StatusCode, details: str) -> None:
319
+ if context is not None:
320
+ context.abort(status_code, details)
321
+ else:
322
+ if status_code == grpc.StatusCode.UNAUTHENTICATED:
323
+ raise PermissionError(f"UNAUTHENTICATED: {details}")
324
+ elif status_code == grpc.StatusCode.PERMISSION_DENIED:
325
+ raise PermissionError(f"PERMISSION_DENIED: {details}")
326
+ elif status_code == grpc.StatusCode.FAILED_PRECONDITION:
327
+ raise RuntimeError(f"FAILED_PRECONDITION: {details}")
328
+ elif status_code == grpc.StatusCode.INVALID_ARGUMENT:
329
+ raise ValueError(f"INVALID_ARGUMENT: {details}")
330
+ else:
331
+ raise RuntimeError(f"{status_code}: {details}")
332
+
333
+ def ExecuteTileTask(
334
+ self,
335
+ request_iterator: Iterator[pb2.TileDataChunk],
336
+ context: Optional[grpc.ServicerContext] = None,
337
+ ) -> pb2.TileResult:
338
+ """
339
+ Step 2: Strict Pre-Allocation Gate verification, stream ingestion, and GEMM execution.
340
+ """
341
+ # 1. Extract Authorization header and metadata from invocation metadata (case-insensitive)
342
+ auth_header = ""
343
+ meta_task_id = None
344
+ hashcash_stamp = None
345
+ if context is not None:
346
+ metadata_dict = {str(k).lower(): str(v) for k, v in context.invocation_metadata()}
347
+ auth_header = metadata_dict.get("authorization") or metadata_dict.get("authorization-bin") or ""
348
+ meta_task_id = metadata_dict.get("x-task-id")
349
+ hashcash_stamp = metadata_dict.get("x-hashcash-stamp") or metadata_dict.get("x-hashcash")
350
+
351
+ # 2. Strict Pre-Allocation Gate:
352
+ # Check authorization and token BEFORE allocating VRAM or processing streams
353
+ if not auth_header:
354
+ self._abort(context, grpc.StatusCode.UNAUTHENTICATED, "Missing Authorization header with L402 token")
355
+
356
+ macaroon_b64, payment_hash = self.gate.parse_auth_header(auth_header)
357
+ if not macaroon_b64 or not payment_hash:
358
+ self._abort(context, grpc.StatusCode.UNAUTHENTICATED, "Malformed L402 Authorization header")
359
+
360
+ is_trial = macaroon_b64.startswith("mc_trial_")
361
+
362
+ # Extract task_id from metadata or macaroon caveats
363
+ task_id = meta_task_id
364
+ if not task_id:
365
+ try:
366
+ import base64
367
+ import json
368
+ b64_clean = macaroon_b64[len("mc_trial_") :] if is_trial else macaroon_b64
369
+ rem = len(b64_clean) % 4
370
+ if rem:
371
+ b64_clean += "=" * (4 - rem)
372
+ raw_bytes = (
373
+ base64.urlsafe_b64decode(b64_clean.encode("ascii"))
374
+ if ("-" in b64_clean or "_" in b64_clean)
375
+ else base64.b64decode(b64_clean)
376
+ )
377
+ payload = json.loads(raw_bytes.decode("utf-8"))
378
+ caveats = payload.get("caveats", payload) if isinstance(payload, dict) else {}
379
+ task_ids = caveats.get("task_ids") or caveats.get("task_batch") or caveats.get("tasks")
380
+ if task_ids and isinstance(task_ids, list):
381
+ if len(task_ids) == 1:
382
+ task_id = str(task_ids[0]).strip()
383
+ elif caveats.get("task_id"):
384
+ task_id = str(caveats.get("task_id")).strip()
385
+ except Exception:
386
+ pass
387
+
388
+ if not task_id:
389
+ self._abort(
390
+ context,
391
+ grpc.StatusCode.UNAUTHENTICATED,
392
+ "Unable to determine task_id: batch macaroon requires explicit 'x-task-id' metadata",
393
+ )
394
+
395
+ with self._lock:
396
+ if task_id in self._active_tasks:
397
+ self._abort(
398
+ context,
399
+ grpc.StatusCode.FAILED_PRECONDITION,
400
+ f"Task '{task_id}' is already actively executing",
401
+ )
402
+ self._active_tasks.add(task_id)
403
+
404
+ try:
405
+ task_info = self._task_metadata.get(task_id)
406
+
407
+ m = task_info["m"] if task_info else 1
408
+ k = task_info["k"] if task_info else 1
409
+ n = task_info["n"] if task_info else 1
410
+ dtype = task_info["dtype"] if task_info else "fp32"
411
+
412
+ # Execute 5-step gate verification BEFORE allocating memory
413
+ node_pubkey = self.signer.get_pubkey_hex() if (is_trial and self.signer is not None) else None
414
+ ok, err_msg, err_code = self.gate.verify_token(
415
+ auth_header=auth_header,
416
+ task_id=task_id,
417
+ m=m,
418
+ k=k,
419
+ n=n,
420
+ x_task_id=meta_task_id,
421
+ worker_pubkey=node_pubkey,
422
+ )
423
+ if not ok:
424
+ status = grpc.StatusCode.UNAUTHENTICATED
425
+ if err_code == "PERMISSION_DENIED":
426
+ status = grpc.StatusCode.PERMISSION_DENIED
427
+ elif err_code == "FAILED_PRECONDITION":
428
+ status = grpc.StatusCode.FAILED_PRECONDITION
429
+ self._abort(context, status, err_msg or "L402 Pre-allocation check failed")
430
+
431
+ if is_trial and (hashcash_stamp is not None or bool(getattr(self.config, "require_trial_hashcash", False))):
432
+ if not hashcash_stamp:
433
+ self._abort(
434
+ context,
435
+ grpc.StatusCode.UNAUTHENTICATED,
436
+ "Missing required x-hashcash-stamp metadata for FREE_TRIAL execution",
437
+ )
438
+ pow_ok, pow_reason = self.hashcash_verifier.verify_and_consume(
439
+ stamp=hashcash_stamp,
440
+ expected_resource=task_id,
441
+ )
442
+ if not pow_ok:
443
+ pow_status = (
444
+ grpc.StatusCode.PERMISSION_DENIED
445
+ if pow_reason == "REPLAYED_HASHCASH_STAMP"
446
+ else grpc.StatusCode.UNAUTHENTICATED
447
+ )
448
+ self._abort(context, pow_status, f"Invalid Hashcash proof-of-work: {pow_reason}")
449
+
450
+ if not task_info:
451
+ self._abort(
452
+ context,
453
+ grpc.StatusCode.FAILED_PRECONDITION,
454
+ f"Task '{task_id}' was not negotiated via RequestTileTask",
455
+ )
456
+
457
+ session = self.enclave_core.get_session(task_id)
458
+ if session is None:
459
+ session, _ = self.enclave_core.create_session(
460
+ task_id=task_id,
461
+ m=m,
462
+ k=k,
463
+ n=n,
464
+ dtype=dtype,
465
+ require_confidential=task_info.get("is_confidential", False),
466
+ client_ephemeral_pubkey=task_info.get("client_ephemeral_pubkey"),
467
+ attestation_nonce=task_info.get("attestation_nonce"),
468
+ worker_ephemeral_priv=task_info.get("worker_ephemeral_priv"),
469
+ )
470
+
471
+ # Ingest and decrypt stream chunks inside enclave execution boundary
472
+ for chunk in request_iterator:
473
+ try:
474
+ session.ingest_chunk(chunk)
475
+ except EnclaveSecurityPolicyError as exc:
476
+ self._abort(context, grpc.StatusCode.PERMISSION_DENIED, str(exc))
477
+ except (EnclaveDecryptionError, EnclaveFramingError) as exc:
478
+ self._abort(context, grpc.StatusCode.INVALID_ARGUMENT, str(exc))
479
+
480
+ # Finalize and execute in-enclave GEMM via PreemptiveComputeScheduler, encrypt output
481
+ should_inject_fraud = bool(getattr(self.config, "inject_fraud", False))
482
+ tier = PriorityTier.FREE_TRIAL if is_trial else PriorityTier.PAID_MAINNET
483
+ try:
484
+ result_bytes, iv, tag, is_encrypted, exec_time_ms = self.scheduler.execute(
485
+ tier,
486
+ lambda: session.execute_and_encrypt(inject_fraud=should_inject_fraud),
487
+ )
488
+ except EnclaveExecutionError as exc:
489
+ self._abort(context, grpc.StatusCode.INTERNAL, str(exc))
490
+ except EnclaveFramingError as exc:
491
+ self._abort(context, grpc.StatusCode.INVALID_ARGUMENT, str(exc))
492
+ except RuntimeError as exc:
493
+ if is_trial and "Trial execution throttled" in str(exc):
494
+ self._abort(context, grpc.StatusCode.RESOURCE_EXHAUSTED, str(exc))
495
+ raise
496
+
497
+ # Cryptographic digest and signing
498
+ c_hash = hashlib.sha256(result_bytes).hexdigest()
499
+ sig = ""
500
+ if self.signer is not None:
501
+ payload_to_sign = f"{task_id}:{c_hash}".encode("utf-8")
502
+ sig = self.signer.sign_message(payload_to_sign)
503
+
504
+ return pb2.TileResult(
505
+ task_id=task_id,
506
+ rows=session.m,
507
+ cols=session.n,
508
+ result_bytes=result_bytes,
509
+ worker_signature=sig,
510
+ execution_time_ms=max(exec_time_ms, 1),
511
+ is_encrypted=is_encrypted,
512
+ iv=iv,
513
+ tag=tag,
514
+ )
515
+ finally:
516
+ with self._lock:
517
+ self._active_tasks.discard(task_id)
518
+ self.enclave_core.close_session(task_id)
519
+ self._task_metadata.pop(task_id, None)
520
+
521
+ def LeaseMatrix(
522
+ self,
523
+ request: pb2.LeaseMatrixRequest,
524
+ context: Optional[grpc.ServicerContext] = None,
525
+ ) -> pb2.LeaseMatrixResponse:
526
+ """
527
+ Allocates and pins matrix A in memory across multiple vector steps.
528
+ Enforces upfront L402 verification, dimension bounding, and optional X25519 key exchange.
529
+ """
530
+ # 1. Parameter Validation
531
+ lease_id = str(request.lease_id).strip()
532
+ if not lease_id:
533
+ self._abort(context, grpc.StatusCode.INVALID_ARGUMENT, "lease_id must not be empty")
534
+
535
+ rows = int(request.rows)
536
+ cols = int(request.cols)
537
+ if rows <= 0 or cols <= 0:
538
+ self._abort(
539
+ context,
540
+ grpc.StatusCode.INVALID_ARGUMENT,
541
+ f"Matrix dimensions must be positive integers, got ({rows}, {cols})",
542
+ )
543
+
544
+ max_elem_limit = 64 * 1024 * 1024
545
+ if (rows * cols) > max_elem_limit or max(rows, cols) > 16384:
546
+ self._abort(
547
+ context,
548
+ grpc.StatusCode.INVALID_ARGUMENT,
549
+ f"Matrix dimensions ({rows}x{cols}) exceed maximum limits (max_elem={max_elem_limit}, max_dim=16384)",
550
+ )
551
+
552
+ dtype = (request.dtype or "fp32").lower().strip()
553
+ if dtype not in ("fp32", "fp16", "bf16"):
554
+ self._abort(context, grpc.StatusCode.INVALID_ARGUMENT, f"Unsupported dtype: {dtype}")
555
+
556
+ ttl_seconds = int(request.ttl_seconds) if request.ttl_seconds > 0 else 3600
557
+ ttl_seconds = min(ttl_seconds, 86400) # Maximum 24h
558
+
559
+ # 2. Confidential Computing Handshake (X25519 ECDH)
560
+ item_size = 4 if dtype in ("fp32", "bf16") else 2
561
+ expected_raw_bytes = rows * cols * item_size
562
+
563
+ worker_ephemeral_pubkey = b""
564
+ session_keys = None
565
+
566
+ if request.require_confidential_compute:
567
+ if not request.client_ephemeral_pubkey or len(request.client_ephemeral_pubkey) != 32:
568
+ self._abort(context, grpc.StatusCode.INVALID_ARGUMENT, "client_ephemeral_pubkey must be exactly 32 bytes")
569
+
570
+ from cryptography.hazmat.primitives.asymmetric import x25519
571
+ from cryptography.hazmat.primitives import serialization
572
+
573
+ try:
574
+ worker_ephemeral_priv = x25519.X25519PrivateKey.generate()
575
+ worker_ephemeral_pub = worker_ephemeral_priv.public_key()
576
+ worker_ephemeral_pubkey = worker_ephemeral_pub.public_bytes(
577
+ encoding=serialization.Encoding.Raw,
578
+ format=serialization.PublicFormat.Raw,
579
+ )
580
+
581
+ # Derive directional keys K_c2w, K_w2c using HKDF-SHA256
582
+ salt = hashlib.sha256(f"iterative:{lease_id}".encode("utf-8")).digest()
583
+ session_keys = derive_session_keys(
584
+ worker_priv=worker_ephemeral_priv,
585
+ client_pub_bytes=request.client_ephemeral_pubkey,
586
+ client_nonce=salt,
587
+ )
588
+ except Exception as exc:
589
+ self._abort(context, grpc.StatusCode.INTERNAL, f"ECDH key exchange failed: {exc}")
590
+
591
+ if len(request.matrix_bytes) != expected_raw_bytes + 28:
592
+ self._abort(
593
+ context,
594
+ grpc.StatusCode.INVALID_ARGUMENT,
595
+ "Confidential compute requires 28-byte encrypted framing (IV + ciphertext + tag)",
596
+ )
597
+
598
+ # 3. Extract Authorization metadata & Perform Upfront L402 Gate Verification
599
+ auth_header = ""
600
+ meta_lease_id = None
601
+ if context is not None:
602
+ metadata_dict = {str(k).lower(): str(v) for k, v in context.invocation_metadata()}
603
+ auth_header = metadata_dict.get("authorization") or metadata_dict.get("authorization-bin") or ""
604
+ meta_lease_id = metadata_dict.get("x-lease-id") or metadata_dict.get("x-task-id")
605
+
606
+ if self.gate is not None:
607
+ if not auth_header:
608
+ self._abort(context, grpc.StatusCode.UNAUTHENTICATED, "Missing Authorization header with L402 token")
609
+
610
+ macaroon_b64, payment_hash = self.gate.parse_auth_header(auth_header)
611
+ if not macaroon_b64 or not payment_hash:
612
+ self._abort(context, grpc.StatusCode.UNAUTHENTICATED, "Malformed L402 Authorization header")
613
+
614
+ # Upfront gate verification: baseline GFLOPs for A (M x K x 1)
615
+ ok, err_msg, err_code = self.gate.verify_token(
616
+ auth_header=auth_header,
617
+ task_id=lease_id,
618
+ m=rows,
619
+ k=cols,
620
+ n=1,
621
+ x_task_id=meta_lease_id or lease_id,
622
+ )
623
+ if not ok:
624
+ status = grpc.StatusCode.UNAUTHENTICATED
625
+ if err_code == "PERMISSION_DENIED":
626
+ status = grpc.StatusCode.PERMISSION_DENIED
627
+ elif err_code == "FAILED_PRECONDITION":
628
+ status = grpc.StatusCode.FAILED_PRECONDITION
629
+ self._abort(context, status, err_msg or "L402 Pre-allocation check failed")
630
+
631
+ # 4. Matrix Deserialization & Payload Validation
632
+ item_size = 4 if dtype in ("fp32", "bf16") else 2
633
+ expected_raw_bytes = rows * cols * item_size
634
+
635
+ matrix_bytes = request.matrix_bytes
636
+ if request.require_confidential_compute:
637
+ if len(matrix_bytes) != expected_raw_bytes + 28:
638
+ self._abort(
639
+ context,
640
+ grpc.StatusCode.INVALID_ARGUMENT,
641
+ "Confidential compute requires 28-byte encrypted framing (IV + ciphertext + tag)",
642
+ )
643
+ # Wire encrypted matrix: [IV (12B) || Tag (16B) || Ciphertext]
644
+ iv = matrix_bytes[:12]
645
+ tag = matrix_bytes[12:28]
646
+ ct = matrix_bytes[28:]
647
+ try:
648
+ matrix_bytes = aes_gcm_decrypt(
649
+ key=session_keys.k_c2w,
650
+ iv=iv,
651
+ ciphertext=ct,
652
+ tag=tag,
653
+ aad=None,
654
+ fallback_aads=[f"{lease_id}:matrix".encode("utf-8"), b""],
655
+ )
656
+ except Exception as exc:
657
+ self._abort(context, grpc.StatusCode.INVALID_ARGUMENT, f"Matrix decryption failed: {exc}")
658
+
659
+ if len(matrix_bytes) != expected_raw_bytes:
660
+ # Support 16-bit BF16 wire transfer if 2 bytes per element
661
+ if dtype == "bf16" and len(matrix_bytes) == rows * cols * 2:
662
+ raw_u16 = np.frombuffer(matrix_bytes, dtype=np.uint16)
663
+ raw_u32 = raw_u16.astype(np.uint32) << 16
664
+ matrix_arr = raw_u32.view(np.float32).reshape((rows, cols))
665
+ else:
666
+ self._abort(
667
+ context,
668
+ grpc.StatusCode.INVALID_ARGUMENT,
669
+ f"Payload size mismatch: expected {expected_raw_bytes} bytes for {rows}x{cols} {dtype}, got {len(matrix_bytes)} bytes",
670
+ )
671
+ else:
672
+ np_dt = np.float32 if dtype in ("fp32", "bf16") else np.float16
673
+ matrix_arr = np.frombuffer(bytearray(matrix_bytes), dtype=np_dt).reshape((rows, cols))
674
+
675
+ if dtype == "bf16":
676
+ matrix_arr = self.engine.truncate_to_bf16(matrix_arr)
677
+
678
+ # 5. Pin in SessionManager
679
+ try:
680
+ session = self.session_manager.lease_matrix(
681
+ lease_id=lease_id,
682
+ matrix=matrix_arr,
683
+ rows=rows,
684
+ cols=cols,
685
+ dtype=dtype,
686
+ ttl_seconds=float(ttl_seconds),
687
+ require_confidential_compute=bool(request.require_confidential_compute),
688
+ client_ephemeral_pubkey=request.client_ephemeral_pubkey if request.require_confidential_compute else None,
689
+ session_keys=session_keys,
690
+ )
691
+ except (ValueError, KeyError) as exc:
692
+ self._abort(context, grpc.StatusCode.ALREADY_EXISTS, str(exc))
693
+ except (MemoryError, RuntimeError) as exc:
694
+ self._abort(context, grpc.StatusCode.RESOURCE_EXHAUSTED, str(exc))
695
+ except Exception as exc:
696
+ self._abort(context, grpc.StatusCode.RESOURCE_EXHAUSTED, f"Session allocation failed: {exc}")
697
+
698
+ worker_pubkey = self.signer.get_pubkey_hex() if self.signer is not None else ""
699
+
700
+ return pb2.LeaseMatrixResponse(
701
+ lease_id=lease_id,
702
+ is_accepted=True,
703
+ expires_at_unix_ms=int(session.expires_at_unix_ms),
704
+ worker_pubkey=worker_pubkey,
705
+ message=f"Lease accepted for {rows}x{cols} ({dtype})",
706
+ worker_ephemeral_pubkey=worker_ephemeral_pubkey,
707
+ )
708
+
709
+ def StepIterative(
710
+ self,
711
+ request: pb2.IterativeStepRequest,
712
+ context: Optional[grpc.ServicerContext] = None,
713
+ ) -> pb2.IterativeStepResponse:
714
+ """
715
+ Executes a single matrix-vector multiplication step (v_{t+1} = A * v_t)
716
+ using the pinned matrix tensor. Handles decryption, GEMV math, encryption, and signing.
717
+ """
718
+ lease_id = str(request.lease_id).strip()
719
+ if not lease_id:
720
+ self._abort(context, grpc.StatusCode.INVALID_ARGUMENT, "lease_id must not be empty")
721
+
722
+ # 1. Session Lookup & Expiration Check
723
+ session = self.session_manager.get_session(lease_id, allow_expired=True)
724
+ if session is None or session.matrix is None:
725
+ self._abort(
726
+ context,
727
+ grpc.StatusCode.NOT_FOUND,
728
+ f"Active lease '{lease_id}' not found or has been evicted",
729
+ )
730
+
731
+ if session.is_expired():
732
+ self.session_manager.evict_expired()
733
+ self._abort(
734
+ context,
735
+ grpc.StatusCode.FAILED_PRECONDITION,
736
+ f"Lease '{lease_id}' has expired at {session.expires_at_unix_ms}",
737
+ )
738
+
739
+ session.touch()
740
+
741
+ # 2. Confidential Decryption
742
+ raw_vector_bytes = request.vector_bytes
743
+ if session.require_confidential_compute:
744
+ if not request.is_encrypted:
745
+ self._abort(
746
+ context,
747
+ grpc.StatusCode.PERMISSION_DENIED,
748
+ "Confidential compute enabled: step request must be encrypted",
749
+ )
750
+ if len(request.iv) != 12 or len(request.tag) != 16:
751
+ self._abort(
752
+ context,
753
+ grpc.StatusCode.INVALID_ARGUMENT,
754
+ f"Invalid AES-GCM framing: IV must be 12 bytes (got {len(request.iv)}), tag must be 16 bytes (got {len(request.tag)})",
755
+ )
756
+
757
+ step_aad = f"{lease_id}:step:{request.step_index}".encode("utf-8")
758
+ try:
759
+ raw_vector_bytes = aes_gcm_decrypt(
760
+ key=session.session_keys.k_c2w,
761
+ iv=request.iv,
762
+ ciphertext=request.vector_bytes,
763
+ tag=request.tag,
764
+ aad=None,
765
+ fallback_aads=[step_aad, b""],
766
+ )
767
+ except (EnclaveDecryptionError, EnclaveFramingError, Exception) as exc:
768
+ self._abort(context, grpc.StatusCode.INVALID_ARGUMENT, f"Step vector decryption failed: {exc}")
769
+ else:
770
+ if request.is_encrypted:
771
+ self._abort(
772
+ context,
773
+ grpc.StatusCode.INVALID_ARGUMENT,
774
+ "Session is unencrypted but request indicated is_encrypted=True",
775
+ )
776
+
777
+ # 3. Vector Deserialization & Dimensionality Check
778
+ expected_cols = session.cols
779
+ if request.vector_length and request.vector_length != expected_cols:
780
+ self._abort(
781
+ context,
782
+ grpc.StatusCode.INVALID_ARGUMENT,
783
+ f"Vector dimension mismatch: matrix inner dimension is {expected_cols}, request vector length is {request.vector_length}",
784
+ )
785
+
786
+ item_size = 4 if session.dtype in ("fp32", "bf16") else 2
787
+ expected_len = expected_cols * item_size
788
+
789
+ if len(raw_vector_bytes) != expected_len:
790
+ if session.dtype == "bf16" and len(raw_vector_bytes) == expected_cols * 2:
791
+ raw_u16 = np.frombuffer(raw_vector_bytes, dtype=np.uint16)
792
+ raw_u32 = raw_u16.astype(np.uint32) << 16
793
+ vec = raw_u32.view(np.float32)
794
+ else:
795
+ self._abort(
796
+ context,
797
+ grpc.StatusCode.INVALID_ARGUMENT,
798
+ f"Vector byte size mismatch: expected {expected_len} bytes for vector of length {expected_cols} ({session.dtype}), got {len(raw_vector_bytes)} bytes",
799
+ )
800
+ else:
801
+ np_dt = np.float32 if session.dtype in ("fp32", "bf16") else np.float16
802
+ vec = np.frombuffer(raw_vector_bytes, dtype=np_dt)
803
+
804
+ if vec.size != expected_cols:
805
+ self._abort(
806
+ context,
807
+ grpc.StatusCode.INVALID_ARGUMENT,
808
+ f"Vector dimension mismatch: matrix inner dimension is {expected_cols}, vector length is {vec.size}",
809
+ )
810
+
811
+ # 4. Fast GEMV Execution
812
+ t_start = time.perf_counter()
813
+ try:
814
+ result_vec = self.engine.gemv(session.matrix, vec, dtype=session.dtype)
815
+ except Exception as exc:
816
+ self._abort(context, grpc.StatusCode.INTERNAL, f"GEMV execution error: {exc}")
817
+ t_elapsed_ms = int((time.perf_counter() - t_start) * 1000)
818
+ try:
819
+ session.record_step()
820
+ except SessionExpiredError as exp_err:
821
+ self._abort(
822
+ context,
823
+ grpc.StatusCode.FAILED_PRECONDITION,
824
+ "Session expired or zeroized during step execution",
825
+ )
826
+
827
+ raw_result_bytes = result_vec.tobytes()
828
+
829
+ # 5. Confidential Result Encryption
830
+ res_is_encrypted = False
831
+ res_iv = b""
832
+ res_tag = b""
833
+ result_vector_bytes = raw_result_bytes
834
+
835
+ if session.require_confidential_compute:
836
+ try:
837
+ ct, iv, tag = aes_gcm_encrypt(
838
+ key=session.session_keys.k_w2c,
839
+ plaintext=raw_result_bytes,
840
+ aad=None,
841
+ )
842
+ result_vector_bytes = ct
843
+ res_iv = iv
844
+ res_tag = tag
845
+ res_is_encrypted = True
846
+ except Exception as exc:
847
+ self._abort(context, grpc.StatusCode.INTERNAL, f"Result encryption failed: {exc}")
848
+
849
+ # 6. Secp256k1 Result Signing
850
+ r_hash = hashlib.sha256(result_vector_bytes).hexdigest()
851
+ sig = ""
852
+ if self.signer is not None:
853
+ payload_to_sign = f"{lease_id}:{request.step_index}:{r_hash}".encode("utf-8")
854
+ sig = self.signer.sign_message(payload_to_sign)
855
+
856
+ return pb2.IterativeStepResponse(
857
+ lease_id=lease_id,
858
+ step_index=request.step_index,
859
+ result_vector_bytes=result_vector_bytes,
860
+ vector_length=int(session.rows),
861
+ worker_signature=sig,
862
+ execution_time_ms=max(t_elapsed_ms, 1),
863
+ is_encrypted=res_is_encrypted,
864
+ iv=res_iv,
865
+ tag=res_tag,
866
+ )
867
+
868
+ def ReleaseLease(
869
+ self,
870
+ request: pb2.ReleaseLeaseRequest,
871
+ context: Optional[grpc.ServicerContext] = None,
872
+ ) -> pb2.ReleaseLeaseResponse:
873
+ """
874
+ Explicitly releases the leased matrix tensor, executes cryptographic zeroization,
875
+ and reclaims memory in SessionManager.
876
+ """
877
+ lease_id = str(request.lease_id).strip()
878
+ if not lease_id:
879
+ self._abort(context, grpc.StatusCode.INVALID_ARGUMENT, "lease_id must not be empty")
880
+
881
+ bytes_freed = self.session_manager.release_lease(lease_id)
882
+ is_released = bytes_freed > 0
883
+ if is_released:
884
+ msg = f"Lease '{lease_id}' successfully released; {bytes_freed} bytes zeroized and reclaimed"
885
+ else:
886
+ msg = f"Lease '{lease_id}' was not active or already released"
887
+
888
+ return pb2.ReleaseLeaseResponse(
889
+ lease_id=lease_id,
890
+ is_released=is_released,
891
+ bytes_freed=bytes_freed,
892
+ message=msg,
893
+ )