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
src/crypto/__init__.py
ADDED
src/crypto/signer.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Secp256k1 Cryptographic Signer for matrix-compute-node."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import secrets
|
|
7
|
+
from typing import List, Optional, Tuple, Union
|
|
8
|
+
|
|
9
|
+
# Pure-Python Bech32 implementation (BIP-173 / Nostr NIP-19)
|
|
10
|
+
BECH32_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _bech32_polymod(values: List[int]) -> int:
|
|
14
|
+
generator = [0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3]
|
|
15
|
+
chk = 1
|
|
16
|
+
for value in values:
|
|
17
|
+
top = chk >> 25
|
|
18
|
+
chk = ((chk & 0x1FFFFFF) << 5) ^ value
|
|
19
|
+
for i in range(5):
|
|
20
|
+
chk ^= generator[i] if ((top >> i) & 1) else 0
|
|
21
|
+
return chk
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _bech32_hrp_expand(hrp: str) -> List[int]:
|
|
25
|
+
return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _convertbits(data: bytes, frombits: int, tobits: int, pad: bool = True) -> Optional[List[int]]:
|
|
29
|
+
acc = 0
|
|
30
|
+
bits = 0
|
|
31
|
+
ret = []
|
|
32
|
+
maxv = (1 << tobits) - 1
|
|
33
|
+
max_acc = (1 << (frombits + tobits - 1)) - 1
|
|
34
|
+
for value in data:
|
|
35
|
+
acc = ((acc << frombits) | value) & max_acc
|
|
36
|
+
bits += frombits
|
|
37
|
+
while bits >= tobits:
|
|
38
|
+
bits -= tobits
|
|
39
|
+
ret.append((acc >> bits) & maxv)
|
|
40
|
+
if pad:
|
|
41
|
+
if bits:
|
|
42
|
+
ret.append((acc << (tobits - bits)) & maxv)
|
|
43
|
+
elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
|
|
44
|
+
return None
|
|
45
|
+
return ret
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def bech32_encode(hrp: str, data_bytes: bytes) -> str:
|
|
49
|
+
"""Encodes arbitrary bytes into Bech32 format with the specified human-readable part."""
|
|
50
|
+
data5 = _convertbits(data_bytes, 8, 5, True)
|
|
51
|
+
if data5 is None:
|
|
52
|
+
raise ValueError("Failed to convert bits for Bech32 encoding")
|
|
53
|
+
values = _bech32_hrp_expand(hrp) + data5
|
|
54
|
+
polymod = _bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1
|
|
55
|
+
checksum = [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
|
|
56
|
+
return hrp + "1" + "".join(BECH32_CHARSET[d] for d in (data5 + checksum))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
SECP256K1_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
|
|
60
|
+
SECP256K1_HALF_ORDER = SECP256K1_ORDER // 2
|
|
61
|
+
|
|
62
|
+
# Cryptographic backend resolution (cryptography preferred, fallback to pure Python ecdsa)
|
|
63
|
+
try:
|
|
64
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
65
|
+
from cryptography.hazmat.primitives.asymmetric.utils import (
|
|
66
|
+
decode_dss_signature,
|
|
67
|
+
encode_dss_signature,
|
|
68
|
+
)
|
|
69
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
70
|
+
_HAS_CRYPTOGRAPHY = True
|
|
71
|
+
except ImportError:
|
|
72
|
+
_HAS_CRYPTOGRAPHY = False
|
|
73
|
+
try:
|
|
74
|
+
import ecdsa
|
|
75
|
+
except ImportError:
|
|
76
|
+
ecdsa = None # type: ignore
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class WorkerSigner:
|
|
80
|
+
"""
|
|
81
|
+
Secp256k1 cryptographic key manager, message signer, and signature verifier.
|
|
82
|
+
Handles worker identity, Nostr npub derivation, and result signing.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(self, privkey_hex: Optional[str] = None):
|
|
86
|
+
if privkey_hex is None or not str(privkey_hex).strip():
|
|
87
|
+
self._privkey_int = secrets.randbelow(SECP256K1_ORDER - 1) + 1
|
|
88
|
+
else:
|
|
89
|
+
clean = str(privkey_hex).strip().lower()
|
|
90
|
+
if len(clean) != 64:
|
|
91
|
+
raise ValueError(f"Private key hex must be 64 characters (32 bytes), got {len(clean)}")
|
|
92
|
+
try:
|
|
93
|
+
self._privkey_int = int(clean, 16)
|
|
94
|
+
except ValueError:
|
|
95
|
+
raise ValueError("Private key contains invalid hexadecimal characters")
|
|
96
|
+
if not (1 <= self._privkey_int < SECP256K1_ORDER):
|
|
97
|
+
raise ValueError("Private key scalar out of valid range [1, SECP256K1_ORDER - 1]")
|
|
98
|
+
|
|
99
|
+
self._privkey_bytes = self._privkey_int.to_bytes(32, "big")
|
|
100
|
+
|
|
101
|
+
if _HAS_CRYPTOGRAPHY:
|
|
102
|
+
self._priv_key_obj = ec.derive_private_key(self._privkey_int, ec.SECP256K1())
|
|
103
|
+
self._pub_key_obj = self._priv_key_obj.public_key()
|
|
104
|
+
self._pubkey_bytes_compressed = self._pub_key_obj.public_bytes(
|
|
105
|
+
encoding=serialization.Encoding.X962,
|
|
106
|
+
format=serialization.PublicFormat.CompressedPoint,
|
|
107
|
+
)
|
|
108
|
+
elif ecdsa is not None:
|
|
109
|
+
sk = ecdsa.SigningKey.from_secret_exponent(self._privkey_int, curve=ecdsa.SECP256k1)
|
|
110
|
+
vk = sk.verifying_key
|
|
111
|
+
self._pubkey_bytes_compressed = vk.to_string("compressed")
|
|
112
|
+
else:
|
|
113
|
+
raise RuntimeError("No cryptographic backend available (neither 'cryptography' nor 'ecdsa' found)")
|
|
114
|
+
|
|
115
|
+
def get_privkey_hex(self) -> str:
|
|
116
|
+
"""Returns 32-byte hex private key (64 hex characters)."""
|
|
117
|
+
return self._privkey_bytes.hex()
|
|
118
|
+
|
|
119
|
+
def get_pubkey_hex(self) -> str:
|
|
120
|
+
"""Returns 33-byte compressed public key hex (66 hex characters)."""
|
|
121
|
+
return self._pubkey_bytes_compressed.hex()
|
|
122
|
+
|
|
123
|
+
def get_nostr_pubkey(self) -> str:
|
|
124
|
+
"""Returns 32-byte X-only Nostr public key hex (64 hex characters)."""
|
|
125
|
+
return self._pubkey_bytes_compressed[1:33].hex()
|
|
126
|
+
|
|
127
|
+
def get_nostr_npub(self) -> str:
|
|
128
|
+
"""Returns Bech32-encoded Nostr public key ('npub1...')."""
|
|
129
|
+
x_only_bytes = self._pubkey_bytes_compressed[1:]
|
|
130
|
+
return bech32_encode("npub", x_only_bytes)
|
|
131
|
+
|
|
132
|
+
def get_npub(self) -> str:
|
|
133
|
+
"""Alias for get_nostr_npub."""
|
|
134
|
+
return self.get_nostr_npub()
|
|
135
|
+
|
|
136
|
+
def sign_message(self, data: bytes) -> str:
|
|
137
|
+
"""
|
|
138
|
+
Computes SHA256(data) and generates a deterministic canonical ECDSA signature.
|
|
139
|
+
Returns 64-byte compact hex signature (128 hex characters) with low-S normalization.
|
|
140
|
+
"""
|
|
141
|
+
if not isinstance(data, (bytes, bytearray)):
|
|
142
|
+
raise TypeError("Data to sign must be bytes")
|
|
143
|
+
|
|
144
|
+
if _HAS_CRYPTOGRAPHY:
|
|
145
|
+
der_sig = self._priv_key_obj.sign(data, ec.ECDSA(hashes.SHA256()))
|
|
146
|
+
r, s = decode_dss_signature(der_sig)
|
|
147
|
+
else:
|
|
148
|
+
digest = hashlib.sha256(data).digest()
|
|
149
|
+
sk = ecdsa.SigningKey.from_secret_exponent(self._privkey_int, curve=ecdsa.SECP256k1)
|
|
150
|
+
sig_bytes = sk.sign_digest_deterministic(digest, hashfunc=hashlib.sha256)
|
|
151
|
+
r = int.from_bytes(sig_bytes[:32], "big")
|
|
152
|
+
s = int.from_bytes(sig_bytes[32:], "big")
|
|
153
|
+
|
|
154
|
+
# Enforce canonical low-S normalization (BIP-62 / BIP-141)
|
|
155
|
+
if s > SECP256K1_HALF_ORDER:
|
|
156
|
+
s = SECP256K1_ORDER - s
|
|
157
|
+
|
|
158
|
+
r_bytes = r.to_bytes(32, "big")
|
|
159
|
+
s_bytes = s.to_bytes(32, "big")
|
|
160
|
+
return (r_bytes + s_bytes).hex()
|
|
161
|
+
|
|
162
|
+
def sign_result(self, task_id: str, result_hash_or_bytes: Union[str, bytes]) -> str:
|
|
163
|
+
"""
|
|
164
|
+
Signs (task_id, SHA256(result_bytes)) tuple.
|
|
165
|
+
result_hash_or_bytes can be either raw result bytes or precomputed SHA256 hex string.
|
|
166
|
+
"""
|
|
167
|
+
if isinstance(result_hash_or_bytes, (bytes, bytearray)):
|
|
168
|
+
result_hash = hashlib.sha256(result_hash_or_bytes).hexdigest()
|
|
169
|
+
else:
|
|
170
|
+
result_hash = str(result_hash_or_bytes).strip()
|
|
171
|
+
|
|
172
|
+
payload = f"{task_id}:{result_hash}".encode("utf-8")
|
|
173
|
+
return self.sign_message(payload)
|
|
174
|
+
|
|
175
|
+
def verify_signature(
|
|
176
|
+
self,
|
|
177
|
+
data: bytes,
|
|
178
|
+
signature_hex: str,
|
|
179
|
+
pubkey_hex: Optional[str] = None,
|
|
180
|
+
) -> bool:
|
|
181
|
+
"""
|
|
182
|
+
Verifies signature over data against this signer's or an external public key.
|
|
183
|
+
Supports both 64-byte compact hex (128 chars) and DER hex signatures.
|
|
184
|
+
"""
|
|
185
|
+
target_pubkey = pubkey_hex if pubkey_hex is not None else self.get_pubkey_hex()
|
|
186
|
+
return self.verify_peer_signature(data, signature_hex, target_pubkey)
|
|
187
|
+
|
|
188
|
+
@classmethod
|
|
189
|
+
def verify_peer_signature(cls, data: bytes, signature_hex: str, pubkey_hex: str) -> bool:
|
|
190
|
+
"""
|
|
191
|
+
Verifies signature over data against a given peer's public key.
|
|
192
|
+
Handles both 64-byte compact signatures (128 hex chars) and DER signatures.
|
|
193
|
+
Accepts 33-byte compressed, 65-byte uncompressed, or 32-byte X-only public keys.
|
|
194
|
+
"""
|
|
195
|
+
if not isinstance(data, (bytes, bytearray)):
|
|
196
|
+
return False
|
|
197
|
+
|
|
198
|
+
try:
|
|
199
|
+
sig_bytes = bytes.fromhex(str(signature_hex).strip())
|
|
200
|
+
pub_str = str(pubkey_hex).strip()
|
|
201
|
+
pub_bytes = bytes.fromhex(pub_str)
|
|
202
|
+
except Exception:
|
|
203
|
+
return False
|
|
204
|
+
|
|
205
|
+
# If 32-byte X-only pubkey is provided, try with both 02 and 03 prefixes
|
|
206
|
+
candidate_pubs = []
|
|
207
|
+
if len(pub_bytes) == 32:
|
|
208
|
+
candidate_pubs = [b"\x02" + pub_bytes, b"\x03" + pub_bytes]
|
|
209
|
+
elif len(pub_bytes) in (33, 65):
|
|
210
|
+
candidate_pubs = [pub_bytes]
|
|
211
|
+
else:
|
|
212
|
+
return False
|
|
213
|
+
|
|
214
|
+
for candidate_pub in candidate_pubs:
|
|
215
|
+
if cls._verify_single_pubkey(data, sig_bytes, candidate_pub):
|
|
216
|
+
return True
|
|
217
|
+
|
|
218
|
+
return False
|
|
219
|
+
|
|
220
|
+
@classmethod
|
|
221
|
+
def _verify_single_pubkey(cls, data: bytes, sig_bytes: bytes, pub_bytes: bytes) -> bool:
|
|
222
|
+
"""Helper to verify against a single 33-byte or 65-byte public key."""
|
|
223
|
+
if _HAS_CRYPTOGRAPHY:
|
|
224
|
+
try:
|
|
225
|
+
peer_pub = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256K1(), pub_bytes)
|
|
226
|
+
|
|
227
|
+
if len(sig_bytes) == 64:
|
|
228
|
+
r = int.from_bytes(sig_bytes[:32], "big")
|
|
229
|
+
s = int.from_bytes(sig_bytes[32:], "big")
|
|
230
|
+
s_candidates = [s]
|
|
231
|
+
if s != 0:
|
|
232
|
+
s_candidates.append(SECP256K1_ORDER - s)
|
|
233
|
+
for s_cand in s_candidates:
|
|
234
|
+
try:
|
|
235
|
+
der_bytes = encode_dss_signature(r, s_cand)
|
|
236
|
+
peer_pub.verify(der_bytes, data, ec.ECDSA(hashes.SHA256()))
|
|
237
|
+
return True
|
|
238
|
+
except Exception:
|
|
239
|
+
continue
|
|
240
|
+
return False
|
|
241
|
+
else:
|
|
242
|
+
der_bytes = sig_bytes
|
|
243
|
+
peer_pub.verify(der_bytes, data, ec.ECDSA(hashes.SHA256()))
|
|
244
|
+
return True
|
|
245
|
+
except Exception:
|
|
246
|
+
return False
|
|
247
|
+
elif ecdsa is not None:
|
|
248
|
+
try:
|
|
249
|
+
vk = ecdsa.VerifyingKey.from_string(pub_bytes, curve=ecdsa.SECP256k1)
|
|
250
|
+
digest = hashlib.sha256(data).digest()
|
|
251
|
+
if len(sig_bytes) == 64:
|
|
252
|
+
return vk.verify_digest(sig_bytes, digest)
|
|
253
|
+
else:
|
|
254
|
+
return vk.verify_digest(sig_bytes, digest, sigdecode=ecdsa.util.sigdecode_der)
|
|
255
|
+
except Exception:
|
|
256
|
+
return False
|
|
257
|
+
return False
|
src/engine/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Compute engine subsystem."""
|
|
2
|
+
|
|
3
|
+
from src.engine.compute_core import ComputeEngine
|
|
4
|
+
from src.engine.scheduler import PreemptiveComputeScheduler, PriorityTier
|
|
5
|
+
from src.engine.enclave_compute import (
|
|
6
|
+
EnclaveComputeCore,
|
|
7
|
+
EnclaveDecryptionError,
|
|
8
|
+
EnclaveError,
|
|
9
|
+
EnclaveExecutionError,
|
|
10
|
+
EnclaveFramingError,
|
|
11
|
+
EnclaveKeyExchangeError,
|
|
12
|
+
EnclaveSecurityPolicyError,
|
|
13
|
+
EnclaveSession,
|
|
14
|
+
EnclaveSessionNotFoundError,
|
|
15
|
+
SessionKeys,
|
|
16
|
+
aes_gcm_decrypt,
|
|
17
|
+
aes_gcm_encrypt,
|
|
18
|
+
canonical_chunk_aad,
|
|
19
|
+
canonical_result_aad,
|
|
20
|
+
compute_chunk_aad,
|
|
21
|
+
compute_result_aad,
|
|
22
|
+
derive_session_keys,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"ComputeEngine",
|
|
27
|
+
"PreemptiveComputeScheduler",
|
|
28
|
+
"PriorityTier",
|
|
29
|
+
"EnclaveComputeCore",
|
|
30
|
+
"EnclaveSession",
|
|
31
|
+
"EnclaveError",
|
|
32
|
+
"EnclaveSessionNotFoundError",
|
|
33
|
+
"EnclaveKeyExchangeError",
|
|
34
|
+
"EnclaveSecurityPolicyError",
|
|
35
|
+
"EnclaveDecryptionError",
|
|
36
|
+
"EnclaveFramingError",
|
|
37
|
+
"EnclaveExecutionError",
|
|
38
|
+
"SessionKeys",
|
|
39
|
+
"aes_gcm_decrypt",
|
|
40
|
+
"aes_gcm_encrypt",
|
|
41
|
+
"canonical_chunk_aad",
|
|
42
|
+
"canonical_result_aad",
|
|
43
|
+
"compute_chunk_aad",
|
|
44
|
+
"compute_result_aad",
|
|
45
|
+
"derive_session_keys",
|
|
46
|
+
]
|