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/auth/hashcash.py ADDED
@@ -0,0 +1,245 @@
1
+ """Server-side SHA-256 Hashcash Proof-of-Work Verifier for matrix-compute-node."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import OrderedDict
6
+ import hashlib
7
+ import threading
8
+ import time
9
+ from typing import Optional, Tuple
10
+
11
+
12
+ def count_leading_zero_bits(digest_bytes: bytes) -> int:
13
+ """Counts continuous leading zero bits in a SHA-256 digest."""
14
+ if not isinstance(digest_bytes, (bytes, bytearray)):
15
+ raise TypeError("digest_bytes must be bytes or bytearray")
16
+ zeros = 0
17
+ for b in digest_bytes:
18
+ if b == 0:
19
+ zeros += 8
20
+ else:
21
+ zeros += 8 - int(b).bit_length()
22
+ break
23
+ return zeros
24
+
25
+
26
+ def solve_hashcash(
27
+ resource: str,
28
+ bits: int = 20,
29
+ max_iterations: int = 10_000_000,
30
+ timestamp: Optional[int] = None,
31
+ ) -> str:
32
+ """
33
+ Solves a SHA-256 Hashcash challenge for a given resource identifier.
34
+ Wire format: `mc_pow:<bits>:<timestamp>:<resource>:<nonce>`
35
+ """
36
+ if not isinstance(resource, str) or not resource.strip():
37
+ raise ValueError("Hashcash resource must be a non-empty string")
38
+ if ":" in resource:
39
+ raise ValueError("Hashcash resource must not contain ':' delimiter")
40
+ if isinstance(bits, bool) or not isinstance(bits, int) or not (0 <= bits <= 256):
41
+ raise ValueError(f"Hashcash bits must be an integer in [0, 256], got {bits}")
42
+ if isinstance(max_iterations, bool) or not isinstance(max_iterations, int) or max_iterations <= 0:
43
+ raise ValueError(f"max_iterations must be a positive integer, got {max_iterations}")
44
+
45
+ ts = int(timestamp if timestamp is not None else time.time())
46
+ clean_resource = resource.strip()
47
+ prefix_str = f"mc_pow:{bits}:{ts}:{clean_resource}:"
48
+ prefix_bytes = prefix_str.encode("utf-8")
49
+
50
+ if bits == 0:
51
+ return f"{prefix_str}0"
52
+
53
+ target = 1 << (256 - bits)
54
+ base_hasher = hashlib.sha256(prefix_bytes)
55
+
56
+ for nonce in range(max_iterations):
57
+ h = base_hasher.copy()
58
+ nonce_str = str(nonce)
59
+ h.update(nonce_str.encode("ascii"))
60
+ digest = h.digest()
61
+ if int.from_bytes(digest, "big") < target:
62
+ return f"{prefix_str}{nonce_str}"
63
+
64
+ raise RuntimeError(
65
+ f"Hashcash solver exceeded max_iterations ({max_iterations}) for difficulty {bits} bits"
66
+ )
67
+
68
+
69
+ def verify_hashcash_with_reason(
70
+ stamp: str,
71
+ expected_resource: str,
72
+ min_bits: int = 20,
73
+ max_age_seconds: int = 300,
74
+ now: Optional[float] = None,
75
+ max_future_skew_seconds: int = 30,
76
+ ) -> Tuple[bool, str]:
77
+ """
78
+ Verifies a Hashcash stamp and returns `(is_valid, reason)`.
79
+
80
+ Checks:
81
+ 1. Wire format `mc_pow:<bits>:<timestamp>:<resource>:<nonce>` (5 colon-separated parts).
82
+ 2. Claimed difficulty `bits >= min_bits`.
83
+ 3. Resource binding `resource == expected_resource`.
84
+ 4. Timestamp freshness (`now - ts <= max_age_seconds` and `ts <= now + max_future_skew_seconds`).
85
+ 5. Cryptographic SHA-256 digest has at least `bits` leading zero bits.
86
+ """
87
+ if not isinstance(stamp, str) or not stamp.strip():
88
+ return False, "STAMP_NOT_STRING"
89
+
90
+ clean_stamp = stamp.strip()
91
+ parts = clean_stamp.split(":")
92
+ if len(parts) != 5 or parts[0] != "mc_pow":
93
+ return False, "MALFORMED_STAMP_FORMAT"
94
+
95
+ bits_str, ts_str, resource, nonce = parts[1], parts[2], parts[3], parts[4]
96
+ if not bits_str or not ts_str or not resource or not nonce:
97
+ return False, "MALFORMED_STAMP_VALUES"
98
+
99
+ try:
100
+ claimed_bits = int(bits_str)
101
+ ts = int(ts_str)
102
+ except ValueError:
103
+ return False, "MALFORMED_STAMP_VALUES"
104
+
105
+ if claimed_bits < 0 or claimed_bits > 256:
106
+ return False, "INVALID_STAMP_BITS_RANGE"
107
+
108
+ if claimed_bits < min_bits:
109
+ return False, f"INSUFFICIENT_STAMP_BITS: got {claimed_bits}, required {min_bits}"
110
+
111
+ if resource != str(expected_resource).strip():
112
+ return False, f"RESOURCE_MISMATCH: expected '{expected_resource}', got '{resource}'"
113
+
114
+ current_time = float(now if now is not None else time.time())
115
+ if ts > current_time + max_future_skew_seconds:
116
+ return False, "FUTURE_TIMESTAMP_REJECTED"
117
+ if (current_time - ts) > max_age_seconds:
118
+ return (
119
+ False,
120
+ f"EXPIRED_TIMESTAMP: age {int(current_time - ts)}s exceeds {max_age_seconds}s limit",
121
+ )
122
+
123
+ digest = hashlib.sha256(clean_stamp.encode("utf-8")).digest()
124
+ actual_bits = count_leading_zero_bits(digest)
125
+ if actual_bits < claimed_bits:
126
+ return (
127
+ False,
128
+ f"PROOF_OF_WORK_INVALID: actual leading zeros {actual_bits} < required {claimed_bits}",
129
+ )
130
+
131
+ return True, "VALID_HASHCASH_PROOF"
132
+
133
+
134
+ def verify_hashcash(
135
+ stamp: str,
136
+ expected_resource: str,
137
+ min_bits: int = 20,
138
+ max_age_seconds: int = 300,
139
+ now: Optional[float] = None,
140
+ ) -> bool:
141
+ """
142
+ Verifies a Hashcash stamp and returns True if valid, False otherwise.
143
+ """
144
+ ok, _ = verify_hashcash_with_reason(
145
+ stamp=stamp,
146
+ expected_resource=expected_resource,
147
+ min_bits=min_bits,
148
+ max_age_seconds=max_age_seconds,
149
+ now=now,
150
+ )
151
+ return ok
152
+
153
+
154
+ class HashcashVerifier:
155
+ """
156
+ Hashcash verifier for matrix-compute-node with thread-safe replay cache for spent stamps.
157
+ """
158
+
159
+ def __init__(
160
+ self,
161
+ min_bits: int = 20,
162
+ max_age_seconds: int = 300,
163
+ max_cache_size: int = 10_000,
164
+ ) -> None:
165
+ self.min_bits = min_bits
166
+ self.max_age_seconds = max_age_seconds
167
+ self.max_cache_size = max_cache_size
168
+ self._lock = threading.RLock()
169
+ self._spent_stamps: OrderedDict[str, float] = OrderedDict()
170
+
171
+ count_leading_zero_bits = staticmethod(count_leading_zero_bits)
172
+ solve = staticmethod(solve_hashcash)
173
+
174
+ @staticmethod
175
+ def verify(
176
+ stamp: str,
177
+ expected_resource: str,
178
+ min_bits: int = 20,
179
+ max_age_seconds: int = 300,
180
+ now: Optional[float] = None,
181
+ ) -> bool:
182
+ return verify_hashcash(
183
+ stamp=stamp,
184
+ expected_resource=expected_resource,
185
+ min_bits=min_bits,
186
+ max_age_seconds=max_age_seconds,
187
+ now=now,
188
+ )
189
+
190
+ @staticmethod
191
+ def verify_with_reason(
192
+ stamp: str,
193
+ expected_resource: str,
194
+ min_bits: int = 20,
195
+ max_age_seconds: int = 300,
196
+ now: Optional[float] = None,
197
+ ) -> Tuple[bool, str]:
198
+ return verify_hashcash_with_reason(
199
+ stamp=stamp,
200
+ expected_resource=expected_resource,
201
+ min_bits=min_bits,
202
+ max_age_seconds=max_age_seconds,
203
+ now=now,
204
+ )
205
+
206
+ def verify_and_consume(
207
+ self,
208
+ stamp: str,
209
+ expected_resource: str,
210
+ min_bits: Optional[int] = None,
211
+ max_age_seconds: Optional[int] = None,
212
+ now: Optional[float] = None,
213
+ ) -> Tuple[bool, str]:
214
+ """
215
+ Verifies the Hashcash stamp and records it in the replay cache so it cannot be reused.
216
+ """
217
+ req_bits = min_bits if min_bits is not None else self.min_bits
218
+ req_age = max_age_seconds if max_age_seconds is not None else self.max_age_seconds
219
+ current_time = float(now if now is not None else time.time())
220
+
221
+ ok, reason = verify_hashcash_with_reason(
222
+ stamp=stamp,
223
+ expected_resource=expected_resource,
224
+ min_bits=req_bits,
225
+ max_age_seconds=req_age,
226
+ now=current_time,
227
+ )
228
+ if not ok:
229
+ return False, reason
230
+
231
+ clean_stamp = stamp.strip()
232
+ with self._lock:
233
+ cutoff = current_time - req_age
234
+ expired = [k for k, ts in self._spent_stamps.items() if ts < cutoff]
235
+ for k in expired:
236
+ self._spent_stamps.pop(k, None)
237
+
238
+ if clean_stamp in self._spent_stamps:
239
+ return False, "REPLAYED_HASHCASH_STAMP"
240
+
241
+ self._spent_stamps[clean_stamp] = current_time
242
+ while len(self._spent_stamps) > self.max_cache_size:
243
+ self._spent_stamps.popitem(last=False)
244
+
245
+ return True, "VALID_HASHCASH_PROOF"