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/config/settings.py
ADDED
|
@@ -0,0 +1,730 @@
|
|
|
1
|
+
"""Configuration manager for matrix-compute-node daemon."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import secrets
|
|
10
|
+
from typing import Any, Dict, List, Optional, Sequence
|
|
11
|
+
from urllib.parse import urlparse
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel, Field, field_validator, model_validator
|
|
14
|
+
|
|
15
|
+
SECP256K1_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class NodeConfig(BaseModel):
|
|
19
|
+
"""
|
|
20
|
+
Worker daemon configuration model.
|
|
21
|
+
Resolves settings with priority: CLI Arguments > Environment Variables > Defaults.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
worker_privkey_hex: str = Field(
|
|
25
|
+
default_factory=lambda: hex(secrets.randbelow(SECP256K1_ORDER - 1) + 1)[2:].zfill(64),
|
|
26
|
+
description="32-byte Secp256k1 private key hex (64 hex characters)",
|
|
27
|
+
)
|
|
28
|
+
p2p_host: str = Field("0.0.0.0", description="P2P gRPC server binding host")
|
|
29
|
+
p2p_port: int = Field(50051, description="P2P gRPC server binding port")
|
|
30
|
+
p2p_multiaddr: Optional[str] = Field(None, description="Explicit libp2p multiaddr")
|
|
31
|
+
lightning_routing_pubkey: Optional[str] = Field(
|
|
32
|
+
None, description="Lightning node pubkey or Lightning Address for routing payments"
|
|
33
|
+
)
|
|
34
|
+
worker_lightning_address: Optional[str] = Field(
|
|
35
|
+
None, description="Worker Lightning Address (user@domain) or pubkey for payouts"
|
|
36
|
+
)
|
|
37
|
+
nostr_relays: List[str] = Field(
|
|
38
|
+
default_factory=lambda: ["wss://relay.matrix-compute.net"],
|
|
39
|
+
description="Nostr discovery relay WebSocket URLs",
|
|
40
|
+
)
|
|
41
|
+
settlement_api_url: str = Field(
|
|
42
|
+
"https://settlement.matrix-compute.net", description="Settlement layer base HTTP URL"
|
|
43
|
+
)
|
|
44
|
+
settlement_verification_key: str = Field(
|
|
45
|
+
"settlement_secret_key_dev", description="L402 Macaroon HMAC verification key"
|
|
46
|
+
)
|
|
47
|
+
sats_per_gflop: float = Field(0.0005, description="Price per GFLOP in Satoshis")
|
|
48
|
+
min_task_sats: int = Field(10, description="Minimum price floor per task in Satoshis")
|
|
49
|
+
gpu_device_index: int = 0
|
|
50
|
+
dtype_preference: str = Field("fp32", description="Compute precision preference")
|
|
51
|
+
log_level: str = "INFO"
|
|
52
|
+
grpc_max_workers: int = 10
|
|
53
|
+
grpc_max_message_bytes: int = 512 * 1024 * 1024 # 512 MB
|
|
54
|
+
l402_cache_ttl_seconds: float = Field(
|
|
55
|
+
300.0, description="TTL in seconds for cached HELD invoice verifications in L402 gate"
|
|
56
|
+
)
|
|
57
|
+
l402_max_cache_size: int = Field(
|
|
58
|
+
10000, description="Maximum number of verified payment hashes to cache in L402 gate"
|
|
59
|
+
)
|
|
60
|
+
enable_confidential_compute: bool = Field(
|
|
61
|
+
True, description="Enable TEE Confidential Computing"
|
|
62
|
+
)
|
|
63
|
+
attestation_provider: str = Field(
|
|
64
|
+
"auto",
|
|
65
|
+
description="Attestation provider: 'auto', 'nvidia-cca', 'amd-sev-snp', 'intel-tdx', 'simulated-cca', 'none'",
|
|
66
|
+
)
|
|
67
|
+
inject_fraud: bool = Field(
|
|
68
|
+
False,
|
|
69
|
+
description="Stage 03 fault-injection flag: intentionally perturbs GEMM output to test Freivalds & HODL cancellation",
|
|
70
|
+
)
|
|
71
|
+
nat_mode: str = Field("direct", description="NAT traversal mode: 'direct' or 'reverse_tunnel'")
|
|
72
|
+
relay_grpc_endpoint: Optional[str] = Field(
|
|
73
|
+
None, description="gRPC endpoint of relay for reverse tunnel (host:port)"
|
|
74
|
+
)
|
|
75
|
+
enable_outbound_nat: bool = Field(
|
|
76
|
+
False, description="Enable outbound-only reverse tunnel to relay"
|
|
77
|
+
)
|
|
78
|
+
tunnel_heartbeat_interval_seconds: float = Field(
|
|
79
|
+
30.0, description="Heartbeat interval in seconds for reverse tunnel"
|
|
80
|
+
)
|
|
81
|
+
d_tag: str = Field(
|
|
82
|
+
"matrix-compute-worker", description="Nostr replaceable event d-tag identifier"
|
|
83
|
+
)
|
|
84
|
+
is_seed_worker: bool = Field(
|
|
85
|
+
False, description="Whether this node is an authorized platform seed worker for FREE_TRIAL tasks"
|
|
86
|
+
)
|
|
87
|
+
trial_pow_bits: int = Field(
|
|
88
|
+
20, description="Minimum Hashcash PoW leading zero bits required for FREE_TRIAL tasks"
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
@model_validator(mode="before")
|
|
92
|
+
@classmethod
|
|
93
|
+
def populate_from_environment(cls, data: Any) -> Any:
|
|
94
|
+
"""
|
|
95
|
+
If field values are not explicitly supplied in data dictionary,
|
|
96
|
+
check os.environ for corresponding MATRIX_* and unprefixed env variables.
|
|
97
|
+
"""
|
|
98
|
+
if not isinstance(data, dict):
|
|
99
|
+
return data
|
|
100
|
+
|
|
101
|
+
env_mappings = {
|
|
102
|
+
"worker_privkey_hex": ["MATRIX_WORKER_PRIVKEY", "MATRIX_WORKER_PRIVKEY_HEX", "WORKER_PRIVKEY", "WORKER_PRIVKEY_HEX"],
|
|
103
|
+
"p2p_host": ["MATRIX_P2P_HOST", "MATRIX_WORKER_P2P_HOST", "P2P_HOST"],
|
|
104
|
+
"p2p_port": ["MATRIX_P2P_PORT", "MATRIX_WORKER_P2P_PORT", "P2P_PORT"],
|
|
105
|
+
"p2p_multiaddr": ["MATRIX_P2P_MULTIADDR", "MATRIX_WORKER_P2P_MULTIADDR", "P2P_MULTIADDR"],
|
|
106
|
+
"lightning_routing_pubkey": [
|
|
107
|
+
"MATRIX_LIGHTNING_ROUTING_PUBKEY",
|
|
108
|
+
"MATRIX_WORKER_LIGHTNING_ROUTING_PUBKEY",
|
|
109
|
+
"LIGHTNING_ROUTING_PUBKEY",
|
|
110
|
+
"WORKER_LIGHTNING_PUBKEY",
|
|
111
|
+
"MATRIX_WORKER_LIGHTNING_ADDRESS",
|
|
112
|
+
"WORKER_LIGHTNING_ADDRESS",
|
|
113
|
+
],
|
|
114
|
+
"worker_lightning_address": [
|
|
115
|
+
"MATRIX_WORKER_LIGHTNING_ADDRESS",
|
|
116
|
+
"WORKER_LIGHTNING_ADDRESS",
|
|
117
|
+
"MATRIX_LIGHTNING_ROUTING_PUBKEY",
|
|
118
|
+
"WORKER_LIGHTNING_PUBKEY",
|
|
119
|
+
],
|
|
120
|
+
"nostr_relays": ["MATRIX_NOSTR_RELAYS", "MATRIX_WORKER_NOSTR_RELAYS", "NOSTR_RELAYS"],
|
|
121
|
+
"settlement_api_url": [
|
|
122
|
+
"MATRIX_SETTLEMENT_API_URL",
|
|
123
|
+
"MATRIX_WORKER_SETTLEMENT_API_URL",
|
|
124
|
+
"MATRIX_SETTLEMENT_URL",
|
|
125
|
+
"SETTLEMENT_API_URL",
|
|
126
|
+
"SETTLEMENT_URL",
|
|
127
|
+
],
|
|
128
|
+
"settlement_verification_key": [
|
|
129
|
+
"MATRIX_SETTLEMENT_VERIFICATION_KEY",
|
|
130
|
+
"MATRIX_WORKER_SETTLEMENT_VERIFICATION_KEY",
|
|
131
|
+
"SETTLEMENT_VERIFICATION_KEY",
|
|
132
|
+
],
|
|
133
|
+
"sats_per_gflop": ["MATRIX_SATS_PER_GFLOP", "MATRIX_WORKER_SATS_PER_GFLOP", "SATS_PER_GFLOP"],
|
|
134
|
+
"min_task_sats": ["MATRIX_MIN_TASK_SATS", "MATRIX_WORKER_MIN_TASK_SATS", "MIN_TASK_SATS"],
|
|
135
|
+
"gpu_device_index": ["MATRIX_GPU_DEVICE_INDEX", "MATRIX_WORKER_GPU_DEVICE_INDEX", "GPU_DEVICE_INDEX"],
|
|
136
|
+
"dtype_preference": ["MATRIX_DTYPE_PREFERENCE", "MATRIX_WORKER_DTYPE_PREFERENCE", "DTYPE_PREFERENCE"],
|
|
137
|
+
"log_level": ["MATRIX_LOG_LEVEL", "MATRIX_WORKER_LOG_LEVEL", "LOG_LEVEL"],
|
|
138
|
+
"grpc_max_workers": ["MATRIX_GRPC_MAX_WORKERS", "MATRIX_WORKER_GRPC_MAX_WORKERS", "GRPC_MAX_WORKERS"],
|
|
139
|
+
"grpc_max_message_bytes": ["MATRIX_GRPC_MAX_MESSAGE_BYTES", "GRPC_MAX_MESSAGE_BYTES"],
|
|
140
|
+
"l402_cache_ttl_seconds": ["MATRIX_L402_CACHE_TTL_SECONDS", "L402_CACHE_TTL_SECONDS"],
|
|
141
|
+
"l402_max_cache_size": ["MATRIX_L402_MAX_CACHE_SIZE", "L402_MAX_CACHE_SIZE"],
|
|
142
|
+
"enable_confidential_compute": [
|
|
143
|
+
"MATRIX_ENABLE_CONFIDENTIAL_COMPUTE",
|
|
144
|
+
"MATRIX_WORKER_ENABLE_CONFIDENTIAL_COMPUTE",
|
|
145
|
+
"ENABLE_CONFIDENTIAL_COMPUTE",
|
|
146
|
+
],
|
|
147
|
+
"attestation_provider": [
|
|
148
|
+
"MATRIX_ATTESTATION_PROVIDER",
|
|
149
|
+
"MATRIX_WORKER_ATTESTATION_PROVIDER",
|
|
150
|
+
"ATTESTATION_PROVIDER",
|
|
151
|
+
],
|
|
152
|
+
"inject_fraud": [
|
|
153
|
+
"MATRIX_WORKER_INJECT_FRAUD",
|
|
154
|
+
"MATRIX_INJECT_FRAUD",
|
|
155
|
+
"INJECT_FRAUD",
|
|
156
|
+
],
|
|
157
|
+
"nat_mode": ["MATRIX_NAT_MODE", "MATRIX_WORKER_NAT_MODE", "NAT_MODE"],
|
|
158
|
+
"relay_grpc_endpoint": [
|
|
159
|
+
"MATRIX_RELAY_GRPC_ENDPOINT",
|
|
160
|
+
"MATRIX_WORKER_RELAY_GRPC_ENDPOINT",
|
|
161
|
+
"RELAY_GRPC_ENDPOINT",
|
|
162
|
+
"MATRIX_RELAY_ENDPOINT",
|
|
163
|
+
"RELAY_ENDPOINT",
|
|
164
|
+
],
|
|
165
|
+
"enable_outbound_nat": [
|
|
166
|
+
"MATRIX_ENABLE_OUTBOUND_NAT",
|
|
167
|
+
"ENABLE_OUTBOUND_NAT",
|
|
168
|
+
],
|
|
169
|
+
"tunnel_heartbeat_interval_seconds": [
|
|
170
|
+
"MATRIX_TUNNEL_HEARTBEAT_INTERVAL_SECONDS",
|
|
171
|
+
"TUNNEL_HEARTBEAT_INTERVAL_SECONDS",
|
|
172
|
+
],
|
|
173
|
+
"is_seed_worker": [
|
|
174
|
+
"MATRIX_IS_SEED_WORKER",
|
|
175
|
+
"MATRIX_WORKER_IS_SEED_WORKER",
|
|
176
|
+
"IS_SEED_WORKER",
|
|
177
|
+
],
|
|
178
|
+
"trial_pow_bits": [
|
|
179
|
+
"MATRIX_TRIAL_POW_BITS",
|
|
180
|
+
"MATRIX_WORKER_TRIAL_POW_BITS",
|
|
181
|
+
"TRIAL_POW_BITS",
|
|
182
|
+
],
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
enriched = dict(data)
|
|
186
|
+
for field_name, env_vars in env_mappings.items():
|
|
187
|
+
if field_name not in enriched or enriched[field_name] is None:
|
|
188
|
+
for env_var in env_vars:
|
|
189
|
+
if env_var in os.environ and os.environ[env_var] != "":
|
|
190
|
+
val = os.environ[env_var]
|
|
191
|
+
enriched[field_name] = val
|
|
192
|
+
break
|
|
193
|
+
|
|
194
|
+
# Convert nostr_relays from string if needed
|
|
195
|
+
if "nostr_relays" in enriched and isinstance(enriched["nostr_relays"], str):
|
|
196
|
+
raw = enriched["nostr_relays"].strip()
|
|
197
|
+
if raw.startswith("[") and raw.endswith("]"):
|
|
198
|
+
try:
|
|
199
|
+
enriched["nostr_relays"] = json.loads(raw)
|
|
200
|
+
except Exception:
|
|
201
|
+
enriched["nostr_relays"] = [r.strip() for r in raw[1:-1].split(",") if r.strip()]
|
|
202
|
+
else:
|
|
203
|
+
enriched["nostr_relays"] = [r.strip() for r in raw.split(",") if r.strip()]
|
|
204
|
+
|
|
205
|
+
if "enable_confidential_compute" in enriched and isinstance(enriched["enable_confidential_compute"], str):
|
|
206
|
+
enriched["enable_confidential_compute"] = enriched["enable_confidential_compute"].strip().lower() in ("1", "true", "yes")
|
|
207
|
+
|
|
208
|
+
if "inject_fraud" in enriched and isinstance(enriched["inject_fraud"], str):
|
|
209
|
+
enriched["inject_fraud"] = enriched["inject_fraud"].strip().lower() in ("1", "true", "yes", "on")
|
|
210
|
+
|
|
211
|
+
if "enable_outbound_nat" in enriched and isinstance(enriched["enable_outbound_nat"], str):
|
|
212
|
+
enriched["enable_outbound_nat"] = enriched["enable_outbound_nat"].strip().lower() in ("1", "true", "yes", "on")
|
|
213
|
+
|
|
214
|
+
if "is_seed_worker" in enriched and isinstance(enriched["is_seed_worker"], str):
|
|
215
|
+
enriched["is_seed_worker"] = enriched["is_seed_worker"].strip().lower() in ("1", "true", "yes", "on")
|
|
216
|
+
|
|
217
|
+
if "trial_pow_bits" in enriched and enriched["trial_pow_bits"] is not None:
|
|
218
|
+
enriched["trial_pow_bits"] = int(enriched["trial_pow_bits"])
|
|
219
|
+
|
|
220
|
+
if "tunnel_heartbeat_interval_seconds" in enriched and enriched["tunnel_heartbeat_interval_seconds"] is not None:
|
|
221
|
+
enriched["tunnel_heartbeat_interval_seconds"] = float(enriched["tunnel_heartbeat_interval_seconds"])
|
|
222
|
+
|
|
223
|
+
if enriched.get("enable_outbound_nat") and enriched.get("nat_mode") in (None, "direct", ""):
|
|
224
|
+
enriched["nat_mode"] = "reverse_tunnel"
|
|
225
|
+
|
|
226
|
+
return enriched
|
|
227
|
+
|
|
228
|
+
@field_validator("p2p_port")
|
|
229
|
+
@classmethod
|
|
230
|
+
def validate_port(cls, v: Any) -> int:
|
|
231
|
+
port = int(v)
|
|
232
|
+
if not (0 <= port <= 65535):
|
|
233
|
+
raise ValueError(f"p2p_port must be between 0 and 65535, got {port}")
|
|
234
|
+
return port
|
|
235
|
+
|
|
236
|
+
@model_validator(mode="after")
|
|
237
|
+
def validate_port_mode(self) -> "NodeConfig":
|
|
238
|
+
is_nat = bool(self.enable_outbound_nat or self.nat_mode == "reverse_tunnel")
|
|
239
|
+
if not is_nat and self.p2p_port == 0:
|
|
240
|
+
raise ValueError("p2p_port must be between 1 and 65535 when nat_mode is direct, got 0")
|
|
241
|
+
if is_nat and not self.relay_grpc_endpoint and self.nostr_relays:
|
|
242
|
+
try:
|
|
243
|
+
parsed = urlparse(str(self.nostr_relays[0]))
|
|
244
|
+
if parsed.hostname:
|
|
245
|
+
self.relay_grpc_endpoint = f"{parsed.hostname}:9090"
|
|
246
|
+
except Exception:
|
|
247
|
+
pass
|
|
248
|
+
if self.worker_lightning_address and not self.lightning_routing_pubkey:
|
|
249
|
+
self.lightning_routing_pubkey = self.worker_lightning_address
|
|
250
|
+
elif self.lightning_routing_pubkey and not self.worker_lightning_address:
|
|
251
|
+
self.worker_lightning_address = self.lightning_routing_pubkey
|
|
252
|
+
return self
|
|
253
|
+
|
|
254
|
+
@field_validator("attestation_provider")
|
|
255
|
+
@classmethod
|
|
256
|
+
def validate_attestation_provider(cls, v: Any) -> str:
|
|
257
|
+
if v is None:
|
|
258
|
+
return "auto"
|
|
259
|
+
return str(v).strip().lower()
|
|
260
|
+
|
|
261
|
+
@field_validator("dtype_preference")
|
|
262
|
+
@classmethod
|
|
263
|
+
def validate_dtype(cls, v: str) -> str:
|
|
264
|
+
allowed = {"fp32", "fp16", "bf16"}
|
|
265
|
+
cleaned = str(v).lower().strip()
|
|
266
|
+
if cleaned not in allowed:
|
|
267
|
+
raise ValueError(f"dtype_preference must be one of {allowed}, got {v}")
|
|
268
|
+
return cleaned
|
|
269
|
+
|
|
270
|
+
@field_validator("sats_per_gflop")
|
|
271
|
+
@classmethod
|
|
272
|
+
def validate_sats_rate(cls, v: Any) -> float:
|
|
273
|
+
rate = float(v)
|
|
274
|
+
if rate < 0:
|
|
275
|
+
raise ValueError(f"sats_per_gflop must be >= 0, got {rate}")
|
|
276
|
+
return rate
|
|
277
|
+
|
|
278
|
+
@field_validator("min_task_sats")
|
|
279
|
+
@classmethod
|
|
280
|
+
def validate_min_sats(cls, v: Any) -> int:
|
|
281
|
+
min_sats = int(v)
|
|
282
|
+
if min_sats < 0:
|
|
283
|
+
raise ValueError(f"min_task_sats must be >= 0, got {min_sats}")
|
|
284
|
+
return min_sats
|
|
285
|
+
|
|
286
|
+
@field_validator("settlement_api_url")
|
|
287
|
+
@classmethod
|
|
288
|
+
def validate_settlement_url(cls, v: str) -> str:
|
|
289
|
+
cleaned = str(v).strip()
|
|
290
|
+
parsed = urlparse(cleaned)
|
|
291
|
+
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
|
292
|
+
raise ValueError(f"settlement_api_url must be a valid http or https URL, got '{v}'")
|
|
293
|
+
return cleaned
|
|
294
|
+
|
|
295
|
+
@field_validator("worker_privkey_hex")
|
|
296
|
+
@classmethod
|
|
297
|
+
def validate_privkey(cls, v: str) -> str:
|
|
298
|
+
clean = str(v).strip().lower()
|
|
299
|
+
if not clean:
|
|
300
|
+
return secrets.token_hex(32)
|
|
301
|
+
if len(clean) != 64:
|
|
302
|
+
raise ValueError(f"worker_privkey_hex must be 64 hex characters (32 bytes), got length {len(clean)}")
|
|
303
|
+
try:
|
|
304
|
+
scalar = int(clean, 16)
|
|
305
|
+
except ValueError:
|
|
306
|
+
raise ValueError("worker_privkey_hex contains invalid hexadecimal characters")
|
|
307
|
+
if not (1 <= scalar < SECP256K1_ORDER):
|
|
308
|
+
raise ValueError("worker_privkey_hex scalar out of valid Secp256k1 range")
|
|
309
|
+
return clean
|
|
310
|
+
|
|
311
|
+
@property
|
|
312
|
+
def worker_pubkey_hex(self) -> str:
|
|
313
|
+
"""Derives 33-byte compressed Secp256k1 public key from worker_privkey_hex."""
|
|
314
|
+
try:
|
|
315
|
+
from src.crypto.signer import WorkerSigner
|
|
316
|
+
return WorkerSigner(self.worker_privkey_hex).get_pubkey_hex()
|
|
317
|
+
except Exception:
|
|
318
|
+
return ""
|
|
319
|
+
|
|
320
|
+
@property
|
|
321
|
+
def effective_p2p_multiaddr(self) -> str:
|
|
322
|
+
"""Returns explicit multiaddr or derives /ip4/{host}/tcp/{port}."""
|
|
323
|
+
if self.p2p_multiaddr:
|
|
324
|
+
return self.p2p_multiaddr
|
|
325
|
+
return f"/ip4/{self.p2p_host}/tcp/{self.p2p_port}"
|
|
326
|
+
|
|
327
|
+
def resolve_advertised_multiaddr(self, env: Optional[Dict[str, str]] = None) -> str:
|
|
328
|
+
"""
|
|
329
|
+
Resolves a routable multiaddr for Nostr Kind 30000 announcements.
|
|
330
|
+
1. Uses explicit p2p_multiaddr if configured.
|
|
331
|
+
2. Outbound NAT / Reverse Tunnel mode: constructs circuit multiaddr via relay.
|
|
332
|
+
3. Auto-detects cloud GPU port-mapping env vars (Vast.ai / RunPod):
|
|
333
|
+
- Vast.ai: PUBLIC_IPADDR + VAST_TCP_PORT_{p2p_port}
|
|
334
|
+
- RunPod: RUNPOD_PUBLIC_IP + RUNPOD_TCP_PORT_{p2p_port}
|
|
335
|
+
4. Uses /ip4/{p2p_host}/tcp/{p2p_port} if p2p_host is not a wildcard (0.0.0.0 / ::).
|
|
336
|
+
5. Otherwise probes outbound interface towards settlement_api_url or Nostr relay,
|
|
337
|
+
falling back to 127.0.0.1.
|
|
338
|
+
"""
|
|
339
|
+
if self.p2p_multiaddr:
|
|
340
|
+
return self.p2p_multiaddr
|
|
341
|
+
|
|
342
|
+
# Outbound NAT / Reverse Tunnel mode
|
|
343
|
+
if self.enable_outbound_nat or self.nat_mode == "reverse_tunnel":
|
|
344
|
+
if self.relay_grpc_endpoint:
|
|
345
|
+
clean_relay = self.relay_grpc_endpoint.strip()
|
|
346
|
+
pubkey = self.worker_pubkey_hex
|
|
347
|
+
if clean_relay.startswith("/"):
|
|
348
|
+
if "p2p-circuit" in clean_relay:
|
|
349
|
+
return clean_relay
|
|
350
|
+
return f"{clean_relay}/p2p-circuit/p2p/{pubkey}" if pubkey else f"{clean_relay}/p2p-circuit"
|
|
351
|
+
else:
|
|
352
|
+
if ":" in clean_relay:
|
|
353
|
+
host, port_str = clean_relay.split(":", 1)
|
|
354
|
+
else:
|
|
355
|
+
host, port_str = clean_relay, "9090"
|
|
356
|
+
proto = "ip4" if re.match(r"^\d+\.\d+\.\d+\.\d+$", host) else "dns4"
|
|
357
|
+
return f"/{proto}/{host}/tcp/{port_str}/p2p-circuit/p2p/{pubkey}" if pubkey else f"/{proto}/{host}/tcp/{port_str}/p2p-circuit"
|
|
358
|
+
|
|
359
|
+
environ = os.environ if env is None else env
|
|
360
|
+
# Vast.ai external TCP port mapping detection
|
|
361
|
+
vast_ip = environ.get("PUBLIC_IPADDR", "").strip()
|
|
362
|
+
vast_port = environ.get(f"VAST_TCP_PORT_{self.p2p_port}", "").strip()
|
|
363
|
+
if vast_ip and vast_port.isdigit():
|
|
364
|
+
return f"/ip4/{vast_ip}/tcp/{int(vast_port)}"
|
|
365
|
+
|
|
366
|
+
# RunPod external TCP port mapping detection
|
|
367
|
+
runpod_ip = environ.get("RUNPOD_PUBLIC_IP", "").strip()
|
|
368
|
+
runpod_port = environ.get(f"RUNPOD_TCP_PORT_{self.p2p_port}", "").strip()
|
|
369
|
+
if runpod_ip and runpod_port.isdigit():
|
|
370
|
+
return f"/ip4/{runpod_ip}/tcp/{int(runpod_port)}"
|
|
371
|
+
|
|
372
|
+
if self.p2p_host and self.p2p_host not in ("0.0.0.0", "::", ""):
|
|
373
|
+
return f"/ip4/{self.p2p_host}/tcp/{self.p2p_port}"
|
|
374
|
+
|
|
375
|
+
import socket
|
|
376
|
+
probe_targets: List[Tuple[str, int]] = []
|
|
377
|
+
try:
|
|
378
|
+
parsed_settlement = urlparse(self.settlement_api_url)
|
|
379
|
+
if parsed_settlement.hostname and parsed_settlement.hostname not in ("127.0.0.1", "localhost", "0.0.0.0"):
|
|
380
|
+
probe_targets.append((parsed_settlement.hostname, parsed_settlement.port or 8080))
|
|
381
|
+
except Exception:
|
|
382
|
+
pass
|
|
383
|
+
|
|
384
|
+
for relay in self.nostr_relays:
|
|
385
|
+
try:
|
|
386
|
+
parsed_relay = urlparse(relay)
|
|
387
|
+
if parsed_relay.hostname and parsed_relay.hostname not in ("127.0.0.1", "localhost", "0.0.0.0"):
|
|
388
|
+
probe_targets.append((parsed_relay.hostname, parsed_relay.port or 8008))
|
|
389
|
+
except Exception:
|
|
390
|
+
pass
|
|
391
|
+
|
|
392
|
+
for host, port in probe_targets:
|
|
393
|
+
try:
|
|
394
|
+
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
|
395
|
+
s.connect((host, port))
|
|
396
|
+
local_ip = s.getsockname()[0]
|
|
397
|
+
if local_ip and not local_ip.startswith("127.") and local_ip != "0.0.0.0":
|
|
398
|
+
return f"/ip4/{local_ip}/tcp/{self.p2p_port}"
|
|
399
|
+
except Exception:
|
|
400
|
+
continue
|
|
401
|
+
|
|
402
|
+
return f"/ip4/127.0.0.1/tcp/{self.p2p_port}"
|
|
403
|
+
|
|
404
|
+
def effective_lightning_pubkey(self, default_worker_pubkey: str) -> str:
|
|
405
|
+
"""Returns lightning routing pubkey or defaults to worker pubkey."""
|
|
406
|
+
return self.lightning_routing_pubkey or default_worker_pubkey
|
|
407
|
+
|
|
408
|
+
@classmethod
|
|
409
|
+
def from_env(cls, env: Optional[Dict[str, str]] = None) -> "NodeConfig":
|
|
410
|
+
"""Constructs NodeConfig from explicit environment mapping."""
|
|
411
|
+
environ = os.environ if env is None else env
|
|
412
|
+
data: Dict[str, Any] = {}
|
|
413
|
+
|
|
414
|
+
for field_name, env_vars in {
|
|
415
|
+
"worker_privkey_hex": ["MATRIX_WORKER_PRIVKEY", "MATRIX_WORKER_PRIVKEY_HEX", "WORKER_PRIVKEY", "WORKER_PRIVKEY_HEX"],
|
|
416
|
+
"p2p_host": ["MATRIX_P2P_HOST", "MATRIX_WORKER_P2P_HOST", "P2P_HOST"],
|
|
417
|
+
"p2p_port": ["MATRIX_P2P_PORT", "MATRIX_WORKER_P2P_PORT", "P2P_PORT"],
|
|
418
|
+
"p2p_multiaddr": ["MATRIX_P2P_MULTIADDR", "MATRIX_WORKER_P2P_MULTIADDR", "P2P_MULTIADDR"],
|
|
419
|
+
"lightning_routing_pubkey": [
|
|
420
|
+
"MATRIX_LIGHTNING_ROUTING_PUBKEY",
|
|
421
|
+
"MATRIX_WORKER_LIGHTNING_ROUTING_PUBKEY",
|
|
422
|
+
"LIGHTNING_ROUTING_PUBKEY",
|
|
423
|
+
"WORKER_LIGHTNING_PUBKEY",
|
|
424
|
+
"MATRIX_WORKER_LIGHTNING_ADDRESS",
|
|
425
|
+
"WORKER_LIGHTNING_ADDRESS",
|
|
426
|
+
],
|
|
427
|
+
"worker_lightning_address": [
|
|
428
|
+
"MATRIX_WORKER_LIGHTNING_ADDRESS",
|
|
429
|
+
"WORKER_LIGHTNING_ADDRESS",
|
|
430
|
+
"MATRIX_LIGHTNING_ROUTING_PUBKEY",
|
|
431
|
+
"WORKER_LIGHTNING_PUBKEY",
|
|
432
|
+
],
|
|
433
|
+
"nostr_relays": ["MATRIX_NOSTR_RELAYS", "MATRIX_WORKER_NOSTR_RELAYS", "NOSTR_RELAYS"],
|
|
434
|
+
"settlement_api_url": [
|
|
435
|
+
"MATRIX_SETTLEMENT_API_URL",
|
|
436
|
+
"MATRIX_WORKER_SETTLEMENT_API_URL",
|
|
437
|
+
"MATRIX_SETTLEMENT_URL",
|
|
438
|
+
"SETTLEMENT_API_URL",
|
|
439
|
+
"SETTLEMENT_URL",
|
|
440
|
+
],
|
|
441
|
+
"settlement_verification_key": [
|
|
442
|
+
"MATRIX_SETTLEMENT_VERIFICATION_KEY",
|
|
443
|
+
"MATRIX_WORKER_SETTLEMENT_VERIFICATION_KEY",
|
|
444
|
+
"SETTLEMENT_VERIFICATION_KEY",
|
|
445
|
+
],
|
|
446
|
+
"sats_per_gflop": ["MATRIX_SATS_PER_GFLOP", "MATRIX_WORKER_SATS_PER_GFLOP", "SATS_PER_GFLOP"],
|
|
447
|
+
"min_task_sats": ["MATRIX_MIN_TASK_SATS", "MATRIX_WORKER_MIN_TASK_SATS", "MIN_TASK_SATS"],
|
|
448
|
+
"gpu_device_index": ["MATRIX_GPU_DEVICE_INDEX", "MATRIX_WORKER_GPU_DEVICE_INDEX", "GPU_DEVICE_INDEX"],
|
|
449
|
+
"dtype_preference": ["MATRIX_DTYPE_PREFERENCE", "MATRIX_WORKER_DTYPE_PREFERENCE", "DTYPE_PREFERENCE"],
|
|
450
|
+
"log_level": ["MATRIX_LOG_LEVEL", "MATRIX_WORKER_LOG_LEVEL", "LOG_LEVEL"],
|
|
451
|
+
"l402_cache_ttl_seconds": ["MATRIX_L402_CACHE_TTL_SECONDS", "L402_CACHE_TTL_SECONDS"],
|
|
452
|
+
"l402_max_cache_size": ["MATRIX_L402_MAX_CACHE_SIZE", "L402_MAX_CACHE_SIZE"],
|
|
453
|
+
"enable_confidential_compute": [
|
|
454
|
+
"MATRIX_ENABLE_CONFIDENTIAL_COMPUTE",
|
|
455
|
+
"MATRIX_WORKER_ENABLE_CONFIDENTIAL_COMPUTE",
|
|
456
|
+
"ENABLE_CONFIDENTIAL_COMPUTE",
|
|
457
|
+
],
|
|
458
|
+
"attestation_provider": [
|
|
459
|
+
"MATRIX_ATTESTATION_PROVIDER",
|
|
460
|
+
"MATRIX_WORKER_ATTESTATION_PROVIDER",
|
|
461
|
+
"ATTESTATION_PROVIDER",
|
|
462
|
+
],
|
|
463
|
+
"inject_fraud": [
|
|
464
|
+
"MATRIX_WORKER_INJECT_FRAUD",
|
|
465
|
+
"MATRIX_INJECT_FRAUD",
|
|
466
|
+
"INJECT_FRAUD",
|
|
467
|
+
],
|
|
468
|
+
"nat_mode": ["MATRIX_NAT_MODE", "MATRIX_WORKER_NAT_MODE", "NAT_MODE"],
|
|
469
|
+
"relay_grpc_endpoint": [
|
|
470
|
+
"MATRIX_RELAY_GRPC_ENDPOINT",
|
|
471
|
+
"MATRIX_WORKER_RELAY_GRPC_ENDPOINT",
|
|
472
|
+
"RELAY_GRPC_ENDPOINT",
|
|
473
|
+
"MATRIX_RELAY_ENDPOINT",
|
|
474
|
+
"RELAY_ENDPOINT",
|
|
475
|
+
],
|
|
476
|
+
"enable_outbound_nat": [
|
|
477
|
+
"MATRIX_ENABLE_OUTBOUND_NAT",
|
|
478
|
+
"ENABLE_OUTBOUND_NAT",
|
|
479
|
+
],
|
|
480
|
+
"tunnel_heartbeat_interval_seconds": [
|
|
481
|
+
"MATRIX_TUNNEL_HEARTBEAT_INTERVAL_SECONDS",
|
|
482
|
+
"TUNNEL_HEARTBEAT_INTERVAL_SECONDS",
|
|
483
|
+
],
|
|
484
|
+
"is_seed_worker": [
|
|
485
|
+
"MATRIX_IS_SEED_WORKER",
|
|
486
|
+
"MATRIX_WORKER_IS_SEED_WORKER",
|
|
487
|
+
"IS_SEED_WORKER",
|
|
488
|
+
],
|
|
489
|
+
"trial_pow_bits": [
|
|
490
|
+
"MATRIX_TRIAL_POW_BITS",
|
|
491
|
+
"MATRIX_WORKER_TRIAL_POW_BITS",
|
|
492
|
+
"TRIAL_POW_BITS",
|
|
493
|
+
],
|
|
494
|
+
}.items():
|
|
495
|
+
for env_var in env_vars:
|
|
496
|
+
if env_var in environ and environ[env_var] != "":
|
|
497
|
+
data[field_name] = environ[env_var]
|
|
498
|
+
break
|
|
499
|
+
|
|
500
|
+
if "p2p_port" in data:
|
|
501
|
+
data["p2p_port"] = int(data["p2p_port"])
|
|
502
|
+
if "sats_per_gflop" in data:
|
|
503
|
+
data["sats_per_gflop"] = float(data["sats_per_gflop"])
|
|
504
|
+
if "min_task_sats" in data:
|
|
505
|
+
data["min_task_sats"] = int(data["min_task_sats"])
|
|
506
|
+
if "gpu_device_index" in data:
|
|
507
|
+
data["gpu_device_index"] = int(data["gpu_device_index"])
|
|
508
|
+
if "l402_cache_ttl_seconds" in data:
|
|
509
|
+
data["l402_cache_ttl_seconds"] = float(data["l402_cache_ttl_seconds"])
|
|
510
|
+
if "l402_max_cache_size" in data:
|
|
511
|
+
data["l402_max_cache_size"] = int(data["l402_max_cache_size"])
|
|
512
|
+
if "nostr_relays" in data and isinstance(data["nostr_relays"], str):
|
|
513
|
+
val = data["nostr_relays"].strip()
|
|
514
|
+
if val.startswith("[") and val.endswith("]"):
|
|
515
|
+
data["nostr_relays"] = json.loads(val)
|
|
516
|
+
else:
|
|
517
|
+
data["nostr_relays"] = [r.strip() for r in val.split(",") if r.strip()]
|
|
518
|
+
if "enable_confidential_compute" in data and isinstance(data["enable_confidential_compute"], str):
|
|
519
|
+
data["enable_confidential_compute"] = data["enable_confidential_compute"].strip().lower() in ("1", "true", "yes")
|
|
520
|
+
if "inject_fraud" in data and isinstance(data["inject_fraud"], str):
|
|
521
|
+
data["inject_fraud"] = data["inject_fraud"].strip().lower() in ("1", "true", "yes", "on")
|
|
522
|
+
if "enable_outbound_nat" in data and isinstance(data["enable_outbound_nat"], str):
|
|
523
|
+
data["enable_outbound_nat"] = data["enable_outbound_nat"].strip().lower() in ("1", "true", "yes", "on")
|
|
524
|
+
if "tunnel_heartbeat_interval_seconds" in data and data["tunnel_heartbeat_interval_seconds"] is not None:
|
|
525
|
+
data["tunnel_heartbeat_interval_seconds"] = float(data["tunnel_heartbeat_interval_seconds"])
|
|
526
|
+
if data.get("enable_outbound_nat") and data.get("nat_mode") in (None, "direct", ""):
|
|
527
|
+
data["nat_mode"] = "reverse_tunnel"
|
|
528
|
+
|
|
529
|
+
return cls(**data)
|
|
530
|
+
|
|
531
|
+
@classmethod
|
|
532
|
+
def create_arg_parser(cls, add_help: bool = True) -> argparse.ArgumentParser:
|
|
533
|
+
"""Builds CLI argument parser."""
|
|
534
|
+
parser = argparse.ArgumentParser(
|
|
535
|
+
description="matrix-compute-node daemon CLI options",
|
|
536
|
+
add_help=add_help,
|
|
537
|
+
)
|
|
538
|
+
parser.add_argument(
|
|
539
|
+
"--worker-privkey",
|
|
540
|
+
"--worker-privkey-hex",
|
|
541
|
+
dest="worker_privkey_hex",
|
|
542
|
+
type=str,
|
|
543
|
+
default=None,
|
|
544
|
+
help="32-byte Secp256k1 private key in hexadecimal",
|
|
545
|
+
)
|
|
546
|
+
parser.add_argument(
|
|
547
|
+
"--p2p-host",
|
|
548
|
+
dest="p2p_host",
|
|
549
|
+
type=str,
|
|
550
|
+
default=None,
|
|
551
|
+
help="gRPC server binding host (e.g. 0.0.0.0)",
|
|
552
|
+
)
|
|
553
|
+
parser.add_argument(
|
|
554
|
+
"--p2p-port",
|
|
555
|
+
dest="p2p_port",
|
|
556
|
+
type=int,
|
|
557
|
+
default=None,
|
|
558
|
+
help="gRPC server binding port (e.g. 50051)",
|
|
559
|
+
)
|
|
560
|
+
parser.add_argument(
|
|
561
|
+
"--p2p-multiaddr",
|
|
562
|
+
dest="p2p_multiaddr",
|
|
563
|
+
type=str,
|
|
564
|
+
default=None,
|
|
565
|
+
help="Explicit libp2p/gRPC multiaddr",
|
|
566
|
+
)
|
|
567
|
+
parser.add_argument(
|
|
568
|
+
"--lightning-routing-pubkey",
|
|
569
|
+
dest="lightning_routing_pubkey",
|
|
570
|
+
type=str,
|
|
571
|
+
default=None,
|
|
572
|
+
help="Lightning node public key for HODL invoices",
|
|
573
|
+
)
|
|
574
|
+
parser.add_argument(
|
|
575
|
+
"--nostr-relays",
|
|
576
|
+
"--nostr-relay",
|
|
577
|
+
dest="nostr_relays",
|
|
578
|
+
type=str,
|
|
579
|
+
default=None,
|
|
580
|
+
help="Comma-separated Nostr relay WebSocket URLs",
|
|
581
|
+
)
|
|
582
|
+
parser.add_argument(
|
|
583
|
+
"--settlement-api-url",
|
|
584
|
+
"--settlement-url",
|
|
585
|
+
dest="settlement_api_url",
|
|
586
|
+
type=str,
|
|
587
|
+
default=None,
|
|
588
|
+
help="Settlement layer HTTP URL",
|
|
589
|
+
)
|
|
590
|
+
parser.add_argument(
|
|
591
|
+
"--settlement-verification-key",
|
|
592
|
+
dest="settlement_verification_key",
|
|
593
|
+
type=str,
|
|
594
|
+
default=None,
|
|
595
|
+
help="L402 Macaroon verification secret key",
|
|
596
|
+
)
|
|
597
|
+
parser.add_argument(
|
|
598
|
+
"--sats-per-gflop",
|
|
599
|
+
dest="sats_per_gflop",
|
|
600
|
+
type=float,
|
|
601
|
+
default=None,
|
|
602
|
+
help="Price in Satoshis per computed GFLOP",
|
|
603
|
+
)
|
|
604
|
+
parser.add_argument(
|
|
605
|
+
"--min-task-sats",
|
|
606
|
+
dest="min_task_sats",
|
|
607
|
+
type=int,
|
|
608
|
+
default=None,
|
|
609
|
+
help="Minimum price floor per task in Satoshis",
|
|
610
|
+
)
|
|
611
|
+
parser.add_argument(
|
|
612
|
+
"--gpu-device-index",
|
|
613
|
+
dest="gpu_device_index",
|
|
614
|
+
type=int,
|
|
615
|
+
default=None,
|
|
616
|
+
help="Target GPU device index",
|
|
617
|
+
)
|
|
618
|
+
parser.add_argument(
|
|
619
|
+
"--dtype-preference",
|
|
620
|
+
dest="dtype_preference",
|
|
621
|
+
type=str,
|
|
622
|
+
default=None,
|
|
623
|
+
help="Compute precision format (fp32, fp16, bf16)",
|
|
624
|
+
)
|
|
625
|
+
parser.add_argument(
|
|
626
|
+
"--log-level",
|
|
627
|
+
dest="log_level",
|
|
628
|
+
type=str,
|
|
629
|
+
default=None,
|
|
630
|
+
help="Logging verbosity level",
|
|
631
|
+
)
|
|
632
|
+
parser.add_argument(
|
|
633
|
+
"--l402-cache-ttl-seconds",
|
|
634
|
+
dest="l402_cache_ttl_seconds",
|
|
635
|
+
type=float,
|
|
636
|
+
default=None,
|
|
637
|
+
help="TTL in seconds for cached HELD invoice verifications in L402 gate",
|
|
638
|
+
)
|
|
639
|
+
parser.add_argument(
|
|
640
|
+
"--l402-max-cache-size",
|
|
641
|
+
dest="l402_max_cache_size",
|
|
642
|
+
type=int,
|
|
643
|
+
default=None,
|
|
644
|
+
help="Maximum number of verified payment hashes to cache in L402 gate",
|
|
645
|
+
)
|
|
646
|
+
parser.add_argument(
|
|
647
|
+
"--enable-confidential-compute",
|
|
648
|
+
dest="enable_confidential_compute",
|
|
649
|
+
action=argparse.BooleanOptionalAction if hasattr(argparse, "BooleanOptionalAction") else "store_true",
|
|
650
|
+
default=None,
|
|
651
|
+
help="Enable TEE Confidential Computing",
|
|
652
|
+
)
|
|
653
|
+
parser.add_argument(
|
|
654
|
+
"--attestation-provider",
|
|
655
|
+
dest="attestation_provider",
|
|
656
|
+
type=str,
|
|
657
|
+
default=None,
|
|
658
|
+
help="Attestation provider ('auto', 'nvidia-cca', 'amd-sev-snp', 'intel-tdx', 'simulated-cca', 'none')",
|
|
659
|
+
)
|
|
660
|
+
parser.add_argument(
|
|
661
|
+
"--inject-fraud",
|
|
662
|
+
dest="inject_fraud",
|
|
663
|
+
action=argparse.BooleanOptionalAction if hasattr(argparse, "BooleanOptionalAction") else "store_true",
|
|
664
|
+
default=None,
|
|
665
|
+
help="Intentionally perturb GEMM output for Scenario 3 invalidation drills",
|
|
666
|
+
)
|
|
667
|
+
parser.add_argument(
|
|
668
|
+
"--nat-mode",
|
|
669
|
+
dest="nat_mode",
|
|
670
|
+
type=str,
|
|
671
|
+
default=None,
|
|
672
|
+
help="NAT traversal mode ('direct', 'reverse_tunnel')",
|
|
673
|
+
)
|
|
674
|
+
parser.add_argument(
|
|
675
|
+
"--relay-grpc-endpoint",
|
|
676
|
+
"--relay-endpoint",
|
|
677
|
+
dest="relay_grpc_endpoint",
|
|
678
|
+
type=str,
|
|
679
|
+
default=None,
|
|
680
|
+
help="Relay gRPC endpoint for reverse tunnel (host:port)",
|
|
681
|
+
)
|
|
682
|
+
parser.add_argument(
|
|
683
|
+
"--enable-outbound-nat",
|
|
684
|
+
dest="enable_outbound_nat",
|
|
685
|
+
action=argparse.BooleanOptionalAction if hasattr(argparse, "BooleanOptionalAction") else "store_true",
|
|
686
|
+
default=None,
|
|
687
|
+
help="Enable outbound-only reverse tunnel to relay",
|
|
688
|
+
)
|
|
689
|
+
parser.add_argument(
|
|
690
|
+
"--tunnel-heartbeat-interval-seconds",
|
|
691
|
+
dest="tunnel_heartbeat_interval_seconds",
|
|
692
|
+
type=float,
|
|
693
|
+
default=None,
|
|
694
|
+
help="Heartbeat interval in seconds for reverse tunnel",
|
|
695
|
+
)
|
|
696
|
+
return parser
|
|
697
|
+
|
|
698
|
+
@classmethod
|
|
699
|
+
def load(
|
|
700
|
+
cls,
|
|
701
|
+
args: Optional[Sequence[str]] = None,
|
|
702
|
+
env: Optional[Dict[str, str]] = None,
|
|
703
|
+
) -> "NodeConfig":
|
|
704
|
+
"""
|
|
705
|
+
Loads configuration merging Defaults < Environment Variables < CLI Arguments.
|
|
706
|
+
"""
|
|
707
|
+
base_config = cls.from_env(env=env).model_dump()
|
|
708
|
+
|
|
709
|
+
parser = cls.create_arg_parser()
|
|
710
|
+
parsed_args, _ = parser.parse_known_args(args)
|
|
711
|
+
cli_dict = {k: v for k, v in vars(parsed_args).items() if v is not None}
|
|
712
|
+
|
|
713
|
+
if "nostr_relays" in cli_dict and isinstance(cli_dict["nostr_relays"], str):
|
|
714
|
+
raw = cli_dict["nostr_relays"].strip()
|
|
715
|
+
if raw.startswith("[") and raw.endswith("]"):
|
|
716
|
+
try:
|
|
717
|
+
cli_dict["nostr_relays"] = json.loads(raw)
|
|
718
|
+
except Exception:
|
|
719
|
+
cli_dict["nostr_relays"] = [r.strip() for r in raw[1:-1].split(",") if r.strip()]
|
|
720
|
+
else:
|
|
721
|
+
cli_dict["nostr_relays"] = [r.strip() for r in raw.split(",") if r.strip()]
|
|
722
|
+
|
|
723
|
+
merged = {**base_config, **cli_dict}
|
|
724
|
+
if merged.get("enable_outbound_nat") and merged.get("nat_mode") in (None, "direct", ""):
|
|
725
|
+
merged["nat_mode"] = "reverse_tunnel"
|
|
726
|
+
return cls(**merged)
|
|
727
|
+
|
|
728
|
+
# Alias for backwards-compatibility and CLI invocations
|
|
729
|
+
from_cli_and_env = load
|
|
730
|
+
|