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.
- matrix_compute_node-0.1.0.dist-info/LICENSE +190 -0
- matrix_compute_node-0.1.0.dist-info/METADATA +71 -0
- matrix_compute_node-0.1.0.dist-info/RECORD +35 -0
- matrix_compute_node-0.1.0.dist-info/WHEEL +5 -0
- matrix_compute_node-0.1.0.dist-info/entry_points.txt +2 -0
- matrix_compute_node-0.1.0.dist-info/top_level.txt +1 -0
- src/__init__.py +52 -0
- src/attestation/__init__.py +114 -0
- src/attestation/base.py +226 -0
- src/attestation/nvml_attest.py +1000 -0
- src/attestation/sev_snp_attest.py +568 -0
- src/attestation/simulated.py +325 -0
- src/attestation/tdx_attest.py +596 -0
- src/auth/__init__.py +19 -0
- src/auth/hashcash.py +245 -0
- src/auth/l402_gate.py +553 -0
- src/config/__init__.py +4 -0
- src/config/settings.py +730 -0
- src/crypto/__init__.py +4 -0
- src/crypto/signer.py +257 -0
- src/engine/__init__.py +46 -0
- src/engine/compute_core.py +409 -0
- src/engine/enclave_compute.py +587 -0
- src/engine/scheduler.py +213 -0
- src/engine/session_manager.py +563 -0
- src/main.py +224 -0
- src/p2p/__init__.py +5 -0
- src/p2p/servicer.py +893 -0
- src/p2p/tunnel_client.py +604 -0
- src/relay/__init__.py +5 -0
- src/relay/nostr_client.py +266 -0
- src/settings.py +8 -0
- src/test_doubles/__init__.py +5 -0
- src/test_doubles/mock_nostr_relay.py +332 -0
- src/test_doubles/mock_settlement.py +410 -0
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Enclave Execution Boundary & Wire Decryption/Encryption Engine (Milestone 3).
|
|
3
|
+
|
|
4
|
+
Enforces strict hardware/software isolation for Confidential Computing (TEE):
|
|
5
|
+
1. Manages ephemeral X25519 session keys and HKDF-SHA256 derivation.
|
|
6
|
+
2. In-enclave AES-256-GCM chunk decryption and AAD authentication.
|
|
7
|
+
3. Protected memory tensor slicing and GEMM acceleration.
|
|
8
|
+
4. In-enclave AES-256-GCM result encryption with fresh 12-byte IVs.
|
|
9
|
+
5. Clean unencrypted fallback for non-confidential execution.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
import logging
|
|
16
|
+
import secrets
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
from cryptography.exceptions import InvalidTag
|
|
23
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
24
|
+
from cryptography.hazmat.primitives.asymmetric import x25519
|
|
25
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
26
|
+
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
from matrix_contracts.v1 import pb2
|
|
30
|
+
except ImportError:
|
|
31
|
+
from matrix_contracts.proto import compute_service_pb2 as pb2
|
|
32
|
+
|
|
33
|
+
from src.engine.compute_core import ComputeEngine
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger("matrix_compute_node.engine.enclave")
|
|
36
|
+
|
|
37
|
+
# ==============================================================================
|
|
38
|
+
# ENCLAVE EXCEPTIONS
|
|
39
|
+
# ==============================================================================
|
|
40
|
+
|
|
41
|
+
class EnclaveError(Exception):
|
|
42
|
+
"""Base exception for all enclave compute core errors."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class EnclaveSessionNotFoundError(EnclaveError):
|
|
46
|
+
"""Raised when a task session is missing or expired."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class EnclaveKeyExchangeError(EnclaveError):
|
|
50
|
+
"""Raised when X25519 ECDH fails (e.g. low-order point submission)."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class EnclaveSecurityPolicyError(EnclaveError):
|
|
54
|
+
"""Raised when confidentiality policy is violated (e.g. unencrypted chunk in TEE)."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class EnclaveDecryptionError(EnclaveError):
|
|
58
|
+
"""Raised when AES-256-GCM tag verification or decryption fails."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class EnclaveFramingError(EnclaveError):
|
|
62
|
+
"""Raised when chunk framing, IV length, tag length, or byte bounds are invalid."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class EnclaveExecutionError(EnclaveError):
|
|
66
|
+
"""Raised when in-enclave GEMM calculation fails."""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ==============================================================================
|
|
70
|
+
# CRYPTOGRAPHIC HELPER FUNCTIONS & DATA STRUCTURES
|
|
71
|
+
# ==============================================================================
|
|
72
|
+
|
|
73
|
+
HKDF_INFO_LABEL: bytes = b"matrix-matmul-v1-aead"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class SessionKeys:
|
|
78
|
+
"""Directional 256-bit symmetric session keys derived via HKDF-SHA256."""
|
|
79
|
+
|
|
80
|
+
k_c2w: bytes
|
|
81
|
+
k_w2c: bytes
|
|
82
|
+
shared_secret: bytes
|
|
83
|
+
salt: bytes
|
|
84
|
+
info: bytes
|
|
85
|
+
|
|
86
|
+
def __iter__(self) -> Iterator[bytes]:
|
|
87
|
+
yield self.k_c2w
|
|
88
|
+
yield self.k_w2c
|
|
89
|
+
|
|
90
|
+
def __getitem__(self, item: int) -> bytes:
|
|
91
|
+
if item == 0:
|
|
92
|
+
return self.k_c2w
|
|
93
|
+
elif item == 1:
|
|
94
|
+
return self.k_w2c
|
|
95
|
+
raise IndexError("SessionKeys has only 2 directional keys (0: k_c2w, 1: k_w2c)")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def compute_ecdh_shared_secret(
|
|
99
|
+
private_key: x25519.X25519PrivateKey,
|
|
100
|
+
peer_public_bytes: bytes,
|
|
101
|
+
) -> bytes:
|
|
102
|
+
"""Performs X25519 Diffie-Hellman scalar multiplication against peer's public key."""
|
|
103
|
+
if not isinstance(peer_public_bytes, (bytes, bytearray)) or len(peer_public_bytes) != 32:
|
|
104
|
+
raise EnclaveKeyExchangeError(f"Peer X25519 public key must be 32 bytes, got {len(peer_public_bytes)}")
|
|
105
|
+
try:
|
|
106
|
+
peer_pub = x25519.X25519PublicKey.from_public_bytes(bytes(peer_public_bytes))
|
|
107
|
+
shared_secret = private_key.exchange(peer_pub)
|
|
108
|
+
if len(shared_secret) != 32:
|
|
109
|
+
raise EnclaveKeyExchangeError(f"Unexpected shared secret length: {len(shared_secret)}")
|
|
110
|
+
if shared_secret == b"\x00" * 32:
|
|
111
|
+
raise EnclaveKeyExchangeError("X25519 produced all-zero shared secret (low-order point rejected)")
|
|
112
|
+
return shared_secret
|
|
113
|
+
except Exception as exc:
|
|
114
|
+
raise EnclaveKeyExchangeError(f"X25519 ECDH exchange failed: {exc}") from exc
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def derive_session_keys(
|
|
118
|
+
worker_priv: Union[x25519.X25519PrivateKey, bytes],
|
|
119
|
+
client_pub_bytes: Union[bytes, x25519.X25519PublicKey],
|
|
120
|
+
client_nonce: bytes,
|
|
121
|
+
worker_nonce: bytes = b"",
|
|
122
|
+
info: bytes = HKDF_INFO_LABEL,
|
|
123
|
+
) -> SessionKeys:
|
|
124
|
+
"""
|
|
125
|
+
Derives directional 256-bit AES-GCM session keys (K_c2w, K_w2c) using HKDF-SHA256.
|
|
126
|
+
Returns SessionKeys which can be unpacked as (k_c2w, k_w2c).
|
|
127
|
+
"""
|
|
128
|
+
if isinstance(worker_priv, x25519.X25519PrivateKey):
|
|
129
|
+
client_bytes = (
|
|
130
|
+
client_pub_bytes.public_bytes(
|
|
131
|
+
encoding=serialization.Encoding.Raw,
|
|
132
|
+
format=serialization.PublicFormat.Raw,
|
|
133
|
+
)
|
|
134
|
+
if isinstance(client_pub_bytes, x25519.X25519PublicKey)
|
|
135
|
+
else bytes(client_pub_bytes)
|
|
136
|
+
)
|
|
137
|
+
shared_secret = compute_ecdh_shared_secret(worker_priv, client_bytes)
|
|
138
|
+
salt = bytes(client_nonce) + bytes(worker_nonce) if worker_nonce else bytes(client_nonce)
|
|
139
|
+
else:
|
|
140
|
+
shared_secret = bytes(worker_priv)
|
|
141
|
+
if len(shared_secret) != 32:
|
|
142
|
+
raise EnclaveKeyExchangeError(f"shared_secret must be 32 bytes, got {len(shared_secret)}")
|
|
143
|
+
if shared_secret == b"\x00" * 32:
|
|
144
|
+
raise EnclaveKeyExchangeError("All-zero shared secret rejected")
|
|
145
|
+
nonce_c = bytes(client_pub_bytes)
|
|
146
|
+
nonce_w = bytes(client_nonce) if client_nonce else b""
|
|
147
|
+
salt = nonce_c + nonce_w if nonce_w else nonce_c
|
|
148
|
+
|
|
149
|
+
if not salt:
|
|
150
|
+
raise EnclaveKeyExchangeError("HKDF salt must not be empty")
|
|
151
|
+
|
|
152
|
+
hkdf = HKDF(
|
|
153
|
+
algorithm=hashes.SHA256(),
|
|
154
|
+
length=64,
|
|
155
|
+
salt=salt,
|
|
156
|
+
info=info,
|
|
157
|
+
)
|
|
158
|
+
derived = hkdf.derive(shared_secret)
|
|
159
|
+
k_c2w = derived[:32]
|
|
160
|
+
k_w2c = derived[32:]
|
|
161
|
+
return SessionKeys(
|
|
162
|
+
k_c2w=k_c2w,
|
|
163
|
+
k_w2c=k_w2c,
|
|
164
|
+
shared_secret=shared_secret,
|
|
165
|
+
salt=salt,
|
|
166
|
+
info=info,
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def canonical_chunk_aad(
|
|
171
|
+
task_id: str,
|
|
172
|
+
sequence_number: int,
|
|
173
|
+
is_matrix_a: bool,
|
|
174
|
+
is_final_chunk: bool = False,
|
|
175
|
+
) -> bytes:
|
|
176
|
+
"""Canonical AAD binding TileDataChunk header metadata."""
|
|
177
|
+
t_id = str(task_id).strip()
|
|
178
|
+
seq = int(sequence_number)
|
|
179
|
+
mat = 1 if is_matrix_a else 0
|
|
180
|
+
fin = 1 if is_final_chunk else 0
|
|
181
|
+
return f"{t_id}:chunk:{mat}:{seq}:{fin}".encode("utf-8")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def compute_chunk_aad(
|
|
185
|
+
task_id: str,
|
|
186
|
+
sequence_number: Union[int, bool] = 0,
|
|
187
|
+
is_matrix_a: Union[bool, int] = True,
|
|
188
|
+
is_final_chunk: bool = False,
|
|
189
|
+
) -> bytes:
|
|
190
|
+
"""Flexible chunk AAD generator supporting multiple positional argument conventions."""
|
|
191
|
+
if isinstance(sequence_number, bool) and isinstance(is_matrix_a, int):
|
|
192
|
+
return canonical_chunk_aad(task_id, sequence_number=is_matrix_a, is_matrix_a=sequence_number, is_final_chunk=is_final_chunk)
|
|
193
|
+
return canonical_chunk_aad(task_id, sequence_number=int(sequence_number), is_matrix_a=bool(is_matrix_a), is_final_chunk=is_final_chunk)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def canonical_result_aad(task_id: str, rows: int, cols: int) -> bytes:
|
|
197
|
+
"""Canonical AAD binding TileResult dimensions metadata."""
|
|
198
|
+
return f"{str(task_id).strip()}:result:{int(rows)}:{int(cols)}".encode("utf-8")
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
compute_result_aad = canonical_result_aad
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def aes_gcm_decrypt(
|
|
205
|
+
key: bytes,
|
|
206
|
+
iv: bytes,
|
|
207
|
+
ciphertext: bytes,
|
|
208
|
+
tag: bytes,
|
|
209
|
+
aad: Optional[bytes] = None,
|
|
210
|
+
fallback_aads: Optional[list[Optional[bytes]]] = None,
|
|
211
|
+
) -> bytes:
|
|
212
|
+
"""
|
|
213
|
+
Decrypts AES-256-GCM ciphertext and validates authentication tag and AAD.
|
|
214
|
+
|
|
215
|
+
Raises:
|
|
216
|
+
EnclaveFramingError: If IV != 12 bytes or tag != 16 bytes.
|
|
217
|
+
EnclaveDecryptionError: If authentication tag verification fails.
|
|
218
|
+
"""
|
|
219
|
+
if len(iv) != 12:
|
|
220
|
+
raise EnclaveFramingError(f"IV must be exactly 12 bytes, got {len(iv)}")
|
|
221
|
+
if len(tag) != 16:
|
|
222
|
+
raise EnclaveFramingError(f"Tag must be exactly 16 bytes, got {len(tag)}")
|
|
223
|
+
|
|
224
|
+
aesgcm = AESGCM(key)
|
|
225
|
+
full_ct = bytes(ciphertext) + bytes(tag)
|
|
226
|
+
|
|
227
|
+
try:
|
|
228
|
+
return aesgcm.decrypt(bytes(iv), full_ct, aad)
|
|
229
|
+
except InvalidTag as exc:
|
|
230
|
+
if fallback_aads:
|
|
231
|
+
for alt in fallback_aads:
|
|
232
|
+
try:
|
|
233
|
+
return aesgcm.decrypt(bytes(iv), full_ct, alt)
|
|
234
|
+
except InvalidTag:
|
|
235
|
+
continue
|
|
236
|
+
raise EnclaveDecryptionError("AES-256-GCM authentication failed: invalid tag or corrupted ciphertext") from exc
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def aes_gcm_encrypt(
|
|
240
|
+
key: bytes,
|
|
241
|
+
plaintext: bytes,
|
|
242
|
+
aad: Optional[bytes] = None,
|
|
243
|
+
iv: Optional[bytes] = None,
|
|
244
|
+
) -> Tuple[bytes, bytes, bytes]:
|
|
245
|
+
"""
|
|
246
|
+
Encrypts plaintext with AES-256-GCM using a fresh 12-byte IV.
|
|
247
|
+
Returns Tuple of (ciphertext, iv, tag).
|
|
248
|
+
"""
|
|
249
|
+
if len(key) != 32:
|
|
250
|
+
raise ValueError(f"Key must be 32 bytes, got {len(key)}")
|
|
251
|
+
|
|
252
|
+
actual_iv = iv if iv is not None else secrets.token_bytes(12)
|
|
253
|
+
if len(actual_iv) != 12:
|
|
254
|
+
raise ValueError(f"IV must be 12 bytes, got {len(actual_iv)}")
|
|
255
|
+
|
|
256
|
+
aesgcm = AESGCM(key)
|
|
257
|
+
ciphertext_and_tag = aesgcm.encrypt(actual_iv, plaintext, aad)
|
|
258
|
+
ciphertext = ciphertext_and_tag[:-16]
|
|
259
|
+
tag = ciphertext_and_tag[-16:]
|
|
260
|
+
return ciphertext, actual_iv, tag
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
# ==============================================================================
|
|
264
|
+
# ENCLAVE SESSION CLASS
|
|
265
|
+
# ==============================================================================
|
|
266
|
+
|
|
267
|
+
class EnclaveSession:
|
|
268
|
+
"""
|
|
269
|
+
Represents an isolated execution context for a single tile task.
|
|
270
|
+
Holds session keys, secure chunk buffers, and performs in-enclave GEMM.
|
|
271
|
+
"""
|
|
272
|
+
|
|
273
|
+
def __init__(
|
|
274
|
+
self,
|
|
275
|
+
task_id: str,
|
|
276
|
+
m: int,
|
|
277
|
+
k: int,
|
|
278
|
+
n: int,
|
|
279
|
+
dtype: str = "fp32",
|
|
280
|
+
is_confidential: bool = True,
|
|
281
|
+
k_c2w: Optional[bytes] = None,
|
|
282
|
+
k_w2c: Optional[bytes] = None,
|
|
283
|
+
compute_engine: Optional[ComputeEngine] = None,
|
|
284
|
+
use_aad: bool = True,
|
|
285
|
+
) -> None:
|
|
286
|
+
self.task_id = str(task_id).strip()
|
|
287
|
+
self.m = int(m)
|
|
288
|
+
self.k = int(k)
|
|
289
|
+
self.n = int(n)
|
|
290
|
+
self.dtype = dtype.lower().strip()
|
|
291
|
+
if self.dtype not in ("fp32", "fp16", "bf16"):
|
|
292
|
+
raise ValueError(f"Unsupported dtype: {self.dtype}")
|
|
293
|
+
|
|
294
|
+
if self.m <= 0 or self.k <= 0 or self.n <= 0:
|
|
295
|
+
raise ValueError("Matrix dimensions must be positive integers")
|
|
296
|
+
|
|
297
|
+
max_elem_limit = 64 * 1024 * 1024
|
|
298
|
+
if (self.m * self.n) > max_elem_limit or max(self.m, self.n) > 16384:
|
|
299
|
+
raise ValueError(
|
|
300
|
+
f"Tile dimensions ({self.m}x{self.k} @ {self.k}x{self.n}) exceed maximum allowed allocation limit"
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
self.is_confidential = is_confidential
|
|
304
|
+
self.k_c2w = k_c2w
|
|
305
|
+
self.k_w2c = k_w2c
|
|
306
|
+
self.compute_engine = compute_engine or ComputeEngine()
|
|
307
|
+
self.use_aad = use_aad
|
|
308
|
+
|
|
309
|
+
# Datatype byte scaling
|
|
310
|
+
self.np_dtype = np.float32 if self.dtype in ("fp32", "bf16") else np.float16
|
|
311
|
+
self.bytes_per_elem = 4 if self.np_dtype == np.float32 else 2
|
|
312
|
+
self.expected_a_bytes = self.m * self.k * self.bytes_per_elem
|
|
313
|
+
self.expected_b_bytes = self.k * self.n * self.bytes_per_elem
|
|
314
|
+
|
|
315
|
+
# Internal in-enclave byte buffers
|
|
316
|
+
self._a_chunks: List[bytes] = []
|
|
317
|
+
self._b_chunks: List[bytes] = []
|
|
318
|
+
self._running_a_bytes = 0
|
|
319
|
+
self._running_b_bytes = 0
|
|
320
|
+
self._expected_seq = 0
|
|
321
|
+
self._final_seen = False
|
|
322
|
+
self.created_at = time.time()
|
|
323
|
+
self._lock = threading.Lock()
|
|
324
|
+
|
|
325
|
+
def ingest_chunk(self, chunk: pb2.TileDataChunk) -> None:
|
|
326
|
+
"""
|
|
327
|
+
Ingests and decrypts a streaming TileDataChunk inside the enclave boundary.
|
|
328
|
+
Enforces strict sequence ordering, task matching, and running byte bounds.
|
|
329
|
+
"""
|
|
330
|
+
with self._lock:
|
|
331
|
+
if self._final_seen:
|
|
332
|
+
raise EnclaveFramingError("Cannot ingest chunks after is_final_chunk=True")
|
|
333
|
+
|
|
334
|
+
if chunk.sequence_number != self._expected_seq:
|
|
335
|
+
raise EnclaveFramingError(
|
|
336
|
+
f"Out of order chunk: expected seq {self._expected_seq}, got {chunk.sequence_number}"
|
|
337
|
+
)
|
|
338
|
+
if str(chunk.task_id).strip() != self.task_id:
|
|
339
|
+
raise EnclaveFramingError(
|
|
340
|
+
f"Chunk task_id mismatch: expected '{self.task_id}', got '{chunk.task_id}'"
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
chunk_payload = chunk.chunk_bytes if chunk.chunk_bytes is not None else b""
|
|
344
|
+
if len(chunk_payload) == 0:
|
|
345
|
+
raise EnclaveFramingError("Empty chunk bytes")
|
|
346
|
+
|
|
347
|
+
# Security Policy Enforcement
|
|
348
|
+
if self.is_confidential:
|
|
349
|
+
if not chunk.is_encrypted:
|
|
350
|
+
raise EnclaveSecurityPolicyError(
|
|
351
|
+
f"Unencrypted chunk received for confidential task '{self.task_id}'"
|
|
352
|
+
)
|
|
353
|
+
if not self.k_c2w:
|
|
354
|
+
raise EnclaveSecurityPolicyError(
|
|
355
|
+
f"Missing inbound session key K_c2w for confidential task '{self.task_id}'"
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
aad = canonical_chunk_aad(self.task_id, chunk.sequence_number, chunk.is_matrix_a, chunk.is_final_chunk) if self.use_aad else None
|
|
359
|
+
alt_aads = [
|
|
360
|
+
f"{self.task_id}:{int(chunk.sequence_number)}:{1 if chunk.is_matrix_a else 0}".encode("utf-8"),
|
|
361
|
+
f"{self.task_id}:{'A' if chunk.is_matrix_a else 'B'}:{int(chunk.sequence_number)}".encode("utf-8"),
|
|
362
|
+
] if self.use_aad else None
|
|
363
|
+
|
|
364
|
+
decrypted_bytes = aes_gcm_decrypt(
|
|
365
|
+
key=self.k_c2w,
|
|
366
|
+
iv=chunk.iv,
|
|
367
|
+
ciphertext=chunk_payload,
|
|
368
|
+
tag=chunk.tag,
|
|
369
|
+
aad=aad,
|
|
370
|
+
fallback_aads=alt_aads,
|
|
371
|
+
)
|
|
372
|
+
else:
|
|
373
|
+
if chunk.is_encrypted:
|
|
374
|
+
raise EnclaveSecurityPolicyError(
|
|
375
|
+
f"Encrypted chunk received for non-confidential task '{self.task_id}'"
|
|
376
|
+
)
|
|
377
|
+
decrypted_bytes = chunk_payload
|
|
378
|
+
|
|
379
|
+
dec_len = len(decrypted_bytes)
|
|
380
|
+
if dec_len == 0:
|
|
381
|
+
raise EnclaveFramingError("Empty chunk bytes")
|
|
382
|
+
|
|
383
|
+
# Enforce Running Byte Limits
|
|
384
|
+
if chunk.is_matrix_a:
|
|
385
|
+
if self._running_a_bytes + dec_len > self.expected_a_bytes:
|
|
386
|
+
raise EnclaveFramingError(
|
|
387
|
+
f"Matrix A stream exceeded expected byte limit ({self.expected_a_bytes} bytes): "
|
|
388
|
+
f"accumulated {self._running_a_bytes + dec_len} bytes"
|
|
389
|
+
)
|
|
390
|
+
self._running_a_bytes += dec_len
|
|
391
|
+
self._a_chunks.append(decrypted_bytes)
|
|
392
|
+
else:
|
|
393
|
+
if self._running_b_bytes + dec_len > self.expected_b_bytes:
|
|
394
|
+
raise EnclaveFramingError(
|
|
395
|
+
f"Matrix B stream exceeded expected byte limit ({self.expected_b_bytes} bytes): "
|
|
396
|
+
f"accumulated {self._running_b_bytes + dec_len} bytes"
|
|
397
|
+
)
|
|
398
|
+
self._running_b_bytes += dec_len
|
|
399
|
+
self._b_chunks.append(decrypted_bytes)
|
|
400
|
+
|
|
401
|
+
self._expected_seq += 1
|
|
402
|
+
if chunk.is_final_chunk:
|
|
403
|
+
self._final_seen = True
|
|
404
|
+
|
|
405
|
+
def execute_and_encrypt(self, inject_fraud: bool = False) -> Tuple[bytes, bytes, bytes, bool, int]:
|
|
406
|
+
"""
|
|
407
|
+
Finalizes chunk assembly, executes GEMM inside enclave memory,
|
|
408
|
+
and encrypts the result using K_w2c.
|
|
409
|
+
|
|
410
|
+
Returns:
|
|
411
|
+
Tuple of (result_bytes, iv, tag, is_encrypted, execution_time_ms)
|
|
412
|
+
"""
|
|
413
|
+
with self._lock:
|
|
414
|
+
if not self._final_seen:
|
|
415
|
+
raise EnclaveFramingError("Stream terminated without final chunk flag")
|
|
416
|
+
|
|
417
|
+
if self._running_a_bytes != self.expected_a_bytes:
|
|
418
|
+
raise EnclaveFramingError(
|
|
419
|
+
f"Matrix A byte count mismatch: got {self._running_a_bytes}, expected {self.expected_a_bytes}"
|
|
420
|
+
)
|
|
421
|
+
if self._running_b_bytes != self.expected_b_bytes:
|
|
422
|
+
raise EnclaveFramingError(
|
|
423
|
+
f"Matrix B byte count mismatch: got {self._running_b_bytes}, expected {self.expected_b_bytes}"
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
# In-enclave tensor reconstruction
|
|
427
|
+
a_raw = b"".join(self._a_chunks)
|
|
428
|
+
b_raw = b"".join(self._b_chunks)
|
|
429
|
+
|
|
430
|
+
matrix_a = np.frombuffer(a_raw, dtype=self.np_dtype).reshape((self.m, self.k))
|
|
431
|
+
matrix_b = np.frombuffer(b_raw, dtype=self.np_dtype).reshape((self.k, self.n))
|
|
432
|
+
|
|
433
|
+
# In-enclave GEMM execution
|
|
434
|
+
start_time = time.perf_counter()
|
|
435
|
+
try:
|
|
436
|
+
matrix_c = self.compute_engine.gemm(matrix_a, matrix_b, dtype=self.dtype)
|
|
437
|
+
except Exception as exc:
|
|
438
|
+
raise EnclaveExecutionError(f"In-enclave GEMM calculation failed: {exc}") from exc
|
|
439
|
+
exec_time_ms = int((time.perf_counter() - start_time) * 1000)
|
|
440
|
+
|
|
441
|
+
if inject_fraud:
|
|
442
|
+
matrix_c = np.array(matrix_c, copy=True)
|
|
443
|
+
matrix_c = matrix_c + np.asarray(1000.0, dtype=matrix_c.dtype)
|
|
444
|
+
|
|
445
|
+
c_raw = matrix_c.tobytes()
|
|
446
|
+
|
|
447
|
+
if self.is_confidential:
|
|
448
|
+
if not self.k_w2c:
|
|
449
|
+
raise EnclaveSecurityPolicyError("Missing outbound session key K_w2c")
|
|
450
|
+
aad = canonical_result_aad(self.task_id, self.m, self.n) if self.use_aad else None
|
|
451
|
+
ciphertext, iv, tag = aes_gcm_encrypt(
|
|
452
|
+
key=self.k_w2c,
|
|
453
|
+
plaintext=c_raw,
|
|
454
|
+
aad=aad,
|
|
455
|
+
)
|
|
456
|
+
return ciphertext, iv, tag, True, max(exec_time_ms, 1)
|
|
457
|
+
else:
|
|
458
|
+
return c_raw, b"", b"", False, max(exec_time_ms, 1)
|
|
459
|
+
|
|
460
|
+
def zeroize(self) -> None:
|
|
461
|
+
"""Securely clears internal buffers and session keys."""
|
|
462
|
+
with self._lock:
|
|
463
|
+
self._a_chunks.clear()
|
|
464
|
+
self._b_chunks.clear()
|
|
465
|
+
self.k_c2w = None
|
|
466
|
+
self.k_w2c = None
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
# ==============================================================================
|
|
470
|
+
# ENCLAVE COMPUTE CORE
|
|
471
|
+
# ==============================================================================
|
|
472
|
+
|
|
473
|
+
class EnclaveComputeCore:
|
|
474
|
+
"""
|
|
475
|
+
Enclave Execution Boundary manager.
|
|
476
|
+
Coordinates active task sessions, manages session lifecycles,
|
|
477
|
+
and isolates cryptographic session keys.
|
|
478
|
+
"""
|
|
479
|
+
|
|
480
|
+
def __init__(
|
|
481
|
+
self,
|
|
482
|
+
compute_engine: Optional[ComputeEngine] = None,
|
|
483
|
+
max_sessions: int = 1000,
|
|
484
|
+
session_ttl_seconds: float = 3600.0,
|
|
485
|
+
) -> None:
|
|
486
|
+
self.compute_engine = compute_engine or ComputeEngine()
|
|
487
|
+
self.max_sessions = max_sessions
|
|
488
|
+
self.session_ttl_seconds = session_ttl_seconds
|
|
489
|
+
self._sessions: Dict[str, EnclaveSession] = {}
|
|
490
|
+
self._lock = threading.RLock()
|
|
491
|
+
|
|
492
|
+
def create_session(
|
|
493
|
+
self,
|
|
494
|
+
task_id: str,
|
|
495
|
+
m: int,
|
|
496
|
+
k: int,
|
|
497
|
+
n: int,
|
|
498
|
+
dtype: str = "fp32",
|
|
499
|
+
require_confidential: bool = True,
|
|
500
|
+
client_ephemeral_pubkey: Optional[bytes] = None,
|
|
501
|
+
attestation_nonce: Optional[bytes] = None,
|
|
502
|
+
worker_ephemeral_priv: Optional[x25519.X25519PrivateKey] = None,
|
|
503
|
+
worker_nonce: bytes = b"",
|
|
504
|
+
) -> Tuple[EnclaveSession, bytes]:
|
|
505
|
+
"""
|
|
506
|
+
Creates and registers an isolated EnclaveSession for a task.
|
|
507
|
+
|
|
508
|
+
Returns:
|
|
509
|
+
Tuple of (EnclaveSession, worker_ephemeral_pubkey)
|
|
510
|
+
"""
|
|
511
|
+
self.evict_expired()
|
|
512
|
+
|
|
513
|
+
worker_pubkey_bytes = b""
|
|
514
|
+
k_c2w = None
|
|
515
|
+
k_w2c = None
|
|
516
|
+
|
|
517
|
+
if require_confidential:
|
|
518
|
+
if client_ephemeral_pubkey is None or len(client_ephemeral_pubkey) != 32:
|
|
519
|
+
raise EnclaveKeyExchangeError("client_ephemeral_pubkey must be 32 bytes")
|
|
520
|
+
if attestation_nonce is None or len(attestation_nonce) != 32:
|
|
521
|
+
raise EnclaveKeyExchangeError("attestation_nonce must be 32 bytes")
|
|
522
|
+
|
|
523
|
+
priv_key = worker_ephemeral_priv or x25519.X25519PrivateKey.generate()
|
|
524
|
+
pub_key = priv_key.public_key()
|
|
525
|
+
worker_pubkey_bytes = pub_key.public_bytes(
|
|
526
|
+
encoding=serialization.Encoding.Raw,
|
|
527
|
+
format=serialization.PublicFormat.Raw,
|
|
528
|
+
)
|
|
529
|
+
|
|
530
|
+
keys = derive_session_keys(
|
|
531
|
+
worker_priv=priv_key,
|
|
532
|
+
client_pub_bytes=client_ephemeral_pubkey,
|
|
533
|
+
client_nonce=attestation_nonce,
|
|
534
|
+
worker_nonce=worker_nonce,
|
|
535
|
+
)
|
|
536
|
+
k_c2w = keys.k_c2w
|
|
537
|
+
k_w2c = keys.k_w2c
|
|
538
|
+
|
|
539
|
+
session = EnclaveSession(
|
|
540
|
+
task_id=task_id,
|
|
541
|
+
m=m,
|
|
542
|
+
k=k,
|
|
543
|
+
n=n,
|
|
544
|
+
dtype=dtype,
|
|
545
|
+
is_confidential=require_confidential,
|
|
546
|
+
k_c2w=k_c2w,
|
|
547
|
+
k_w2c=k_w2c,
|
|
548
|
+
compute_engine=self.compute_engine,
|
|
549
|
+
)
|
|
550
|
+
|
|
551
|
+
with self._lock:
|
|
552
|
+
if task_id in self._sessions:
|
|
553
|
+
old_session = self._sessions.pop(task_id)
|
|
554
|
+
old_session.zeroize()
|
|
555
|
+
self._sessions[task_id] = session
|
|
556
|
+
while len(self._sessions) > self.max_sessions:
|
|
557
|
+
oldest_key = next(iter(self._sessions))
|
|
558
|
+
old_session = self._sessions.pop(oldest_key)
|
|
559
|
+
old_session.zeroize()
|
|
560
|
+
|
|
561
|
+
return session, worker_pubkey_bytes
|
|
562
|
+
|
|
563
|
+
def get_session(self, task_id: str) -> Optional[EnclaveSession]:
|
|
564
|
+
"""Retrieves active session for task_id, or None if expired/not found."""
|
|
565
|
+
self.evict_expired()
|
|
566
|
+
with self._lock:
|
|
567
|
+
return self._sessions.get(str(task_id).strip())
|
|
568
|
+
|
|
569
|
+
def close_session(self, task_id: str) -> None:
|
|
570
|
+
"""Closes and zeroizes an active session."""
|
|
571
|
+
with self._lock:
|
|
572
|
+
session = self._sessions.pop(str(task_id).strip(), None)
|
|
573
|
+
if session:
|
|
574
|
+
session.zeroize()
|
|
575
|
+
|
|
576
|
+
def evict_expired(self, now: Optional[float] = None) -> None:
|
|
577
|
+
"""Evicts sessions exceeding session_ttl_seconds."""
|
|
578
|
+
current_time = now if now is not None else time.time()
|
|
579
|
+
with self._lock:
|
|
580
|
+
expired_keys = [
|
|
581
|
+
k for k, v in self._sessions.items()
|
|
582
|
+
if current_time - v.created_at > self.session_ttl_seconds
|
|
583
|
+
]
|
|
584
|
+
for k in expired_keys:
|
|
585
|
+
session = self._sessions.pop(k, None)
|
|
586
|
+
if session:
|
|
587
|
+
session.zeroize()
|