pwsolve 0.1.0__tar.gz

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.
@@ -0,0 +1,210 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "block-buffer"
7
+ version = "0.10.4"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
10
+ dependencies = [
11
+ "generic-array",
12
+ ]
13
+
14
+ [[package]]
15
+ name = "cfg-if"
16
+ version = "1.0.5"
17
+ source = "registry+https://github.com/rust-lang/crates.io-index"
18
+ checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
19
+
20
+ [[package]]
21
+ name = "cpufeatures"
22
+ version = "0.2.17"
23
+ source = "registry+https://github.com/rust-lang/crates.io-index"
24
+ checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
25
+ dependencies = [
26
+ "libc",
27
+ ]
28
+
29
+ [[package]]
30
+ name = "crypto-common"
31
+ version = "0.1.7"
32
+ source = "registry+https://github.com/rust-lang/crates.io-index"
33
+ checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
34
+ dependencies = [
35
+ "generic-array",
36
+ "typenum",
37
+ ]
38
+
39
+ [[package]]
40
+ name = "digest"
41
+ version = "0.10.7"
42
+ source = "registry+https://github.com/rust-lang/crates.io-index"
43
+ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
44
+ dependencies = [
45
+ "block-buffer",
46
+ "crypto-common",
47
+ ]
48
+
49
+ [[package]]
50
+ name = "generic-array"
51
+ version = "0.14.7"
52
+ source = "registry+https://github.com/rust-lang/crates.io-index"
53
+ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
54
+ dependencies = [
55
+ "typenum",
56
+ "version_check",
57
+ ]
58
+
59
+ [[package]]
60
+ name = "heck"
61
+ version = "0.5.0"
62
+ source = "registry+https://github.com/rust-lang/crates.io-index"
63
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
64
+
65
+ [[package]]
66
+ name = "libc"
67
+ version = "0.2.191"
68
+ source = "registry+https://github.com/rust-lang/crates.io-index"
69
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
70
+
71
+ [[package]]
72
+ name = "once_cell"
73
+ version = "1.21.4"
74
+ source = "registry+https://github.com/rust-lang/crates.io-index"
75
+ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
76
+
77
+ [[package]]
78
+ name = "portable-atomic"
79
+ version = "1.15.0"
80
+ source = "registry+https://github.com/rust-lang/crates.io-index"
81
+ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
82
+
83
+ [[package]]
84
+ name = "proc-macro2"
85
+ version = "1.0.107"
86
+ source = "registry+https://github.com/rust-lang/crates.io-index"
87
+ checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
88
+ dependencies = [
89
+ "unicode-ident",
90
+ ]
91
+
92
+ [[package]]
93
+ name = "pwsolve-native"
94
+ version = "0.1.0"
95
+ dependencies = [
96
+ "pyo3",
97
+ "sha2",
98
+ ]
99
+
100
+ [[package]]
101
+ name = "pyo3"
102
+ version = "0.30.1"
103
+ source = "registry+https://github.com/rust-lang/crates.io-index"
104
+ checksum = "229ca13b8a15bb0d1487b81ab975bfcd97513416499a8312011b6036e42e0de4"
105
+ dependencies = [
106
+ "libc",
107
+ "once_cell",
108
+ "portable-atomic",
109
+ "pyo3-build-config",
110
+ "pyo3-ffi",
111
+ "pyo3-macros",
112
+ ]
113
+
114
+ [[package]]
115
+ name = "pyo3-build-config"
116
+ version = "0.30.1"
117
+ source = "registry+https://github.com/rust-lang/crates.io-index"
118
+ checksum = "70130e2b6dd1ee589a8788026a429561ca5c40fa7a2fa7914c2282eddae24700"
119
+ dependencies = [
120
+ "target-lexicon",
121
+ ]
122
+
123
+ [[package]]
124
+ name = "pyo3-ffi"
125
+ version = "0.30.1"
126
+ source = "registry+https://github.com/rust-lang/crates.io-index"
127
+ checksum = "5e7ff73c555c286d212d4ce7e5fbda845a973c4f61bd5f160f5f2c3c2a04d1c4"
128
+ dependencies = [
129
+ "libc",
130
+ "pyo3-build-config",
131
+ ]
132
+
133
+ [[package]]
134
+ name = "pyo3-macros"
135
+ version = "0.30.1"
136
+ source = "registry+https://github.com/rust-lang/crates.io-index"
137
+ checksum = "c46d2e5862c7bb8207e3b639f713dda3c499933444784154c11d013c5a691b60"
138
+ dependencies = [
139
+ "proc-macro2",
140
+ "pyo3-macros-backend",
141
+ "quote",
142
+ "syn",
143
+ ]
144
+
145
+ [[package]]
146
+ name = "pyo3-macros-backend"
147
+ version = "0.30.1"
148
+ source = "registry+https://github.com/rust-lang/crates.io-index"
149
+ checksum = "38b89f066f2ae72a2aef52d1537ca2fcd104440ebfadee06e97aa90738a25b9b"
150
+ dependencies = [
151
+ "heck",
152
+ "proc-macro2",
153
+ "quote",
154
+ "syn",
155
+ ]
156
+
157
+ [[package]]
158
+ name = "quote"
159
+ version = "1.0.47"
160
+ source = "registry+https://github.com/rust-lang/crates.io-index"
161
+ checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
162
+ dependencies = [
163
+ "proc-macro2",
164
+ ]
165
+
166
+ [[package]]
167
+ name = "sha2"
168
+ version = "0.10.9"
169
+ source = "registry+https://github.com/rust-lang/crates.io-index"
170
+ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
171
+ dependencies = [
172
+ "cfg-if",
173
+ "cpufeatures",
174
+ "digest",
175
+ ]
176
+
177
+ [[package]]
178
+ name = "syn"
179
+ version = "3.0.10"
180
+ source = "registry+https://github.com/rust-lang/crates.io-index"
181
+ checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
182
+ dependencies = [
183
+ "proc-macro2",
184
+ "quote",
185
+ "unicode-ident",
186
+ ]
187
+
188
+ [[package]]
189
+ name = "target-lexicon"
190
+ version = "0.13.6"
191
+ source = "registry+https://github.com/rust-lang/crates.io-index"
192
+ checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da"
193
+
194
+ [[package]]
195
+ name = "typenum"
196
+ version = "1.20.1"
197
+ source = "registry+https://github.com/rust-lang/crates.io-index"
198
+ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
199
+
200
+ [[package]]
201
+ name = "unicode-ident"
202
+ version = "1.0.27"
203
+ source = "registry+https://github.com/rust-lang/crates.io-index"
204
+ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
205
+
206
+ [[package]]
207
+ name = "version_check"
208
+ version = "0.9.5"
209
+ source = "registry+https://github.com/rust-lang/crates.io-index"
210
+ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
@@ -0,0 +1,21 @@
1
+ [package]
2
+ name = "pwsolve-native"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ description = "Native Anubis proof-of-work solver"
6
+ license = "MIT"
7
+ readme = "README.md"
8
+
9
+ [lib]
10
+ name = "_native"
11
+ crate-type = ["cdylib"]
12
+
13
+ [dependencies]
14
+ pyo3 = { version = "0.30.1", features = ["extension-module", "abi3-py310"] }
15
+ sha2 = "0.10"
16
+
17
+ [profile.release]
18
+ opt-level = 3
19
+ lto = "thin"
20
+ codegen-units = 1
21
+ strip = true
pwsolve-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,119 @@
1
+ Metadata-Version: 2.4
2
+ Name: pwsolve
3
+ Version: 0.1.0
4
+ Classifier: Programming Language :: Python :: 3
5
+ Classifier: Programming Language :: Python :: 3 :: Only
6
+ Classifier: Programming Language :: Rust
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Operating System :: Microsoft :: Windows
9
+ Classifier: Operating System :: POSIX :: Linux
10
+ Classifier: Operating System :: MacOS
11
+ Classifier: Topic :: Internet :: WWW/HTTP
12
+ Classifier: Topic :: Security :: Cryptography
13
+ Summary: Native Anubis proof-of-work solver with a configurable worker pool and input queue
14
+ Keywords: anubis,proof-of-work,pow,sha256,solver
15
+ Author: pwsolve contributors
16
+ License: MIT
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
19
+
20
+ # pwsolve
21
+
22
+ `pwsolve` is a native Anubis proof-of-work solver for Python. It searches for
23
+ the first nonce whose SHA-256 digest has the requested number of leading zero
24
+ hexadecimal nibbles.
25
+
26
+ The hashing loop is written in Rust and releases the Python GIL while it runs.
27
+ A fixed-size worker pool consumes requests from an input queue, so concurrent
28
+ solves do not create a thread or process per challenge.
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ pip install pwsolve
34
+ ```
35
+
36
+ Building from source requires a Rust toolchain and `maturin`.
37
+
38
+ ## Quick start
39
+
40
+ ```python
41
+ from pwsolve import Solver
42
+
43
+ with Solver(workers=4) as solver:
44
+ result = solver.solve(
45
+ "challenge-random-data",
46
+ difficulty=4,
47
+ max_seconds=30,
48
+ )
49
+
50
+ print(result.digest)
51
+ print(result.nonce)
52
+ ```
53
+
54
+ `difficulty` counts hexadecimal nibbles. Difficulty 6 is a 24-bit prefix and
55
+ takes about 16.7 million hashes on average, not `2**6`.
56
+
57
+ If `workers` is omitted, `os.cpu_count()` worker threads are used.
58
+
59
+ ## Queueing requests
60
+
61
+ `submit()` places a request on the solver's queue and returns a
62
+ `concurrent.futures.Future`.
63
+
64
+ ```python
65
+ from pwsolve import Solver
66
+
67
+ with Solver(workers=4, queue_size=32) as solver:
68
+ futures = [
69
+ solver.submit(random_data, difficulty=4, max_seconds=30)
70
+ for random_data in challenges
71
+ ]
72
+
73
+ for future in futures:
74
+ result = future.result()
75
+ print(result.nonce, result.digest)
76
+ ```
77
+
78
+ `queue_size=0` means unbounded. A bounded queue applies backpressure:
79
+ `submit()` blocks when the queue is full until a worker takes a request.
80
+
81
+ For a large stream, `solve_many()` keeps at most `2 * workers` requests in
82
+ flight and yields results in input order:
83
+
84
+ ```python
85
+ for result in solver.solve_many(
86
+ [("data-a", 4), ("data-b", 5), {"randomData": "data-c", "difficulty": 6}],
87
+ max_seconds=30,
88
+ ):
89
+ print(result)
90
+ ```
91
+
92
+ ## Shared pool
93
+
94
+ The module-level functions use a shared pool configured before first use:
95
+
96
+ ```python
97
+ import pwsolve
98
+
99
+ pwsolve.configure(workers=4, queue_size=16)
100
+
101
+ for challenge in challenges:
102
+ result = pwsolve.solve_pow(
103
+ challenge["randomData"],
104
+ challenge["difficulty"],
105
+ max_seconds=45,
106
+ )
107
+
108
+ pwsolve.shutdown()
109
+ ```
110
+
111
+ ## Limits and errors
112
+
113
+ - `start` and `stop` select a nonce shard. They default to `0` and an
114
+ effectively unbounded window.
115
+ - `max_seconds` bounds native hashing time. Queue wait time is separate.
116
+ - `PowBudgetExceeded` is raised when the shard or time budget is exhausted.
117
+ - `SolverClosedError` is raised when submitting after shutdown.
118
+ - Difficulty must be between 0 and 64 inclusive.
119
+
@@ -0,0 +1,99 @@
1
+ # pwsolve
2
+
3
+ `pwsolve` is a native Anubis proof-of-work solver for Python. It searches for
4
+ the first nonce whose SHA-256 digest has the requested number of leading zero
5
+ hexadecimal nibbles.
6
+
7
+ The hashing loop is written in Rust and releases the Python GIL while it runs.
8
+ A fixed-size worker pool consumes requests from an input queue, so concurrent
9
+ solves do not create a thread or process per challenge.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install pwsolve
15
+ ```
16
+
17
+ Building from source requires a Rust toolchain and `maturin`.
18
+
19
+ ## Quick start
20
+
21
+ ```python
22
+ from pwsolve import Solver
23
+
24
+ with Solver(workers=4) as solver:
25
+ result = solver.solve(
26
+ "challenge-random-data",
27
+ difficulty=4,
28
+ max_seconds=30,
29
+ )
30
+
31
+ print(result.digest)
32
+ print(result.nonce)
33
+ ```
34
+
35
+ `difficulty` counts hexadecimal nibbles. Difficulty 6 is a 24-bit prefix and
36
+ takes about 16.7 million hashes on average, not `2**6`.
37
+
38
+ If `workers` is omitted, `os.cpu_count()` worker threads are used.
39
+
40
+ ## Queueing requests
41
+
42
+ `submit()` places a request on the solver's queue and returns a
43
+ `concurrent.futures.Future`.
44
+
45
+ ```python
46
+ from pwsolve import Solver
47
+
48
+ with Solver(workers=4, queue_size=32) as solver:
49
+ futures = [
50
+ solver.submit(random_data, difficulty=4, max_seconds=30)
51
+ for random_data in challenges
52
+ ]
53
+
54
+ for future in futures:
55
+ result = future.result()
56
+ print(result.nonce, result.digest)
57
+ ```
58
+
59
+ `queue_size=0` means unbounded. A bounded queue applies backpressure:
60
+ `submit()` blocks when the queue is full until a worker takes a request.
61
+
62
+ For a large stream, `solve_many()` keeps at most `2 * workers` requests in
63
+ flight and yields results in input order:
64
+
65
+ ```python
66
+ for result in solver.solve_many(
67
+ [("data-a", 4), ("data-b", 5), {"randomData": "data-c", "difficulty": 6}],
68
+ max_seconds=30,
69
+ ):
70
+ print(result)
71
+ ```
72
+
73
+ ## Shared pool
74
+
75
+ The module-level functions use a shared pool configured before first use:
76
+
77
+ ```python
78
+ import pwsolve
79
+
80
+ pwsolve.configure(workers=4, queue_size=16)
81
+
82
+ for challenge in challenges:
83
+ result = pwsolve.solve_pow(
84
+ challenge["randomData"],
85
+ challenge["difficulty"],
86
+ max_seconds=45,
87
+ )
88
+
89
+ pwsolve.shutdown()
90
+ ```
91
+
92
+ ## Limits and errors
93
+
94
+ - `start` and `stop` select a nonce shard. They default to `0` and an
95
+ effectively unbounded window.
96
+ - `max_seconds` bounds native hashing time. Queue wait time is separate.
97
+ - `PowBudgetExceeded` is raised when the shard or time budget is exhausted.
98
+ - `SolverClosedError` is raised when submitting after shutdown.
99
+ - Difficulty must be between 0 and 64 inclusive.
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["maturin>=1.7,<2"]
3
+ build-backend = "maturin"
4
+
5
+ [project]
6
+ name = "pwsolve"
7
+ version = "0.1.0"
8
+ description = "Native Anubis proof-of-work solver with a configurable worker pool and input queue"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "pwsolve contributors" }]
13
+ keywords = ["anubis", "proof-of-work", "pow", "sha256", "solver"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ "Programming Language :: Rust",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Operating System :: Microsoft :: Windows",
20
+ "Operating System :: POSIX :: Linux",
21
+ "Operating System :: MacOS",
22
+ "Topic :: Internet :: WWW/HTTP",
23
+ "Topic :: Security :: Cryptography",
24
+ ]
25
+
26
+ [tool.maturin]
27
+ python-source = "python"
28
+ module-name = "pwsolve._native"
29
+ features = ["pyo3/extension-module"]
30
+ exclude = ["dist/**", "target/**", "**/__pycache__/**", "**/*.pdb"]
@@ -0,0 +1,402 @@
1
+ """Native Anubis proof-of-work solver.
2
+
3
+ The solver searches for the first nonce whose ``sha256(random_data + str(nonce))``
4
+ has ``difficulty`` leading zero hexadecimal nibbles. Difficulty is counted in
5
+ nibbles, matching Anubis: difficulty 6 is a 24-bit prefix, not six bits.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import queue
12
+ import threading
13
+ from collections import deque
14
+ from concurrent.futures import Future
15
+ from dataclasses import dataclass
16
+ from typing import Any, Iterable, Iterator, Mapping, NamedTuple
17
+
18
+ from ._native import __version__, solve as _native_solve
19
+
20
+ __all__ = [
21
+ "PowBudgetExceeded",
22
+ "Solver",
23
+ "SolverClosedError",
24
+ "Solution",
25
+ "configure",
26
+ "shutdown",
27
+ "solve",
28
+ "solve_pow",
29
+ "solve_many",
30
+ ]
31
+
32
+
33
+ class PowBudgetExceeded(RuntimeError):
34
+ """The nonce shard or the caller's time budget was exhausted."""
35
+
36
+
37
+ class SolverClosedError(RuntimeError):
38
+ """A request was submitted after the solver was shut down."""
39
+
40
+
41
+ class Solution(NamedTuple):
42
+ """A matching nonce and the full SHA-256 digest as lowercase hex."""
43
+
44
+ digest: str
45
+ nonce: int
46
+
47
+
48
+ @dataclass(frozen=True, slots=True)
49
+ class _Task:
50
+ random_data: str
51
+ difficulty: int
52
+ start: int
53
+ stop: int | None
54
+ max_seconds: float | None
55
+ future: Future[Solution]
56
+
57
+
58
+ def _validate_request(
59
+ random_data: str,
60
+ difficulty: int,
61
+ start: int,
62
+ stop: int | None,
63
+ max_seconds: float | None,
64
+ ) -> tuple[str, int, int, int | None, float | None]:
65
+ if not isinstance(random_data, str):
66
+ raise TypeError("random_data must be a str")
67
+ if isinstance(difficulty, bool) or not isinstance(difficulty, int):
68
+ raise TypeError("difficulty must be an int")
69
+ if not 0 <= difficulty <= 64:
70
+ raise ValueError("difficulty must be between 0 and 64")
71
+ if isinstance(start, bool) or not isinstance(start, int):
72
+ raise TypeError("start must be an int")
73
+ if not 0 <= start <= (1 << 64) - 1:
74
+ raise ValueError("start must fit in an unsigned 64-bit integer")
75
+ if stop is not None:
76
+ if isinstance(stop, bool) or not isinstance(stop, int):
77
+ raise TypeError("stop must be an int or None")
78
+ if not 0 <= stop <= (1 << 64) - 1:
79
+ raise ValueError("stop must fit in an unsigned 64-bit integer")
80
+ if max_seconds is not None:
81
+ if isinstance(max_seconds, bool) or not isinstance(max_seconds, (int, float)):
82
+ raise TypeError("max_seconds must be a number or None")
83
+ max_seconds = float(max_seconds)
84
+ if max_seconds < 0 or max_seconds != max_seconds or max_seconds == float("inf"):
85
+ raise ValueError("max_seconds must be finite and non-negative")
86
+ return random_data, difficulty, start, stop, max_seconds
87
+
88
+
89
+ def _coerce_request(
90
+ request: Any, default_max_seconds: float | None
91
+ ) -> dict[str, Any]:
92
+ if isinstance(request, Mapping):
93
+ random_data = request.get("random_data", request.get("randomData"))
94
+ if random_data is None or "difficulty" not in request:
95
+ raise ValueError("request mapping needs random_data and difficulty")
96
+ return {
97
+ "random_data": random_data,
98
+ "difficulty": request["difficulty"],
99
+ "start": request.get("start", 0),
100
+ "stop": request.get("stop"),
101
+ "max_seconds": request.get("max_seconds", default_max_seconds),
102
+ }
103
+
104
+ if isinstance(request, (tuple, list)):
105
+ if len(request) == 2:
106
+ random_data, difficulty = request
107
+ return {
108
+ "random_data": random_data,
109
+ "difficulty": difficulty,
110
+ "start": 0,
111
+ "stop": None,
112
+ "max_seconds": default_max_seconds,
113
+ }
114
+ if len(request) in (3, 4, 5):
115
+ values = list(request) + [None] * (5 - len(request))
116
+ return {
117
+ "random_data": values[0],
118
+ "difficulty": values[1],
119
+ "start": values[2] if len(request) >= 3 else 0,
120
+ "stop": values[3],
121
+ "max_seconds": values[4] if len(request) >= 5 else default_max_seconds,
122
+ }
123
+
124
+ raise TypeError(
125
+ "request must be a (random_data, difficulty) tuple, a longer tuple, "
126
+ "or a mapping with random_data/randomData and difficulty"
127
+ )
128
+
129
+
130
+ class Solver:
131
+ """A fixed-size worker pool fed by an input queue.
132
+
133
+ ``workers`` controls how many native solver threads run concurrently.
134
+ ``queue_size`` bounds the number of waiting requests; zero means unbounded.
135
+ Submitting to a full bounded queue blocks until a worker takes a request.
136
+ """
137
+
138
+ def __init__(self, workers: int | None = None, *, queue_size: int = 0) -> None:
139
+ if workers is None:
140
+ workers = max(1, os.cpu_count() or 1)
141
+ if isinstance(workers, bool) or not isinstance(workers, int) or workers < 1:
142
+ raise ValueError("workers must be a positive integer")
143
+ if isinstance(queue_size, bool) or not isinstance(queue_size, int) or queue_size < 0:
144
+ raise ValueError("queue_size must be zero or a positive integer")
145
+
146
+ self._workers = workers
147
+ self._queue_size = queue_size
148
+ self._queue: queue.Queue[_Task | None] = queue.Queue(maxsize=queue_size)
149
+ self._submit_lock = threading.Lock()
150
+ self._closed = False
151
+ self._threads = [
152
+ threading.Thread(target=self._worker, name=f"pwsolve-{index}", daemon=True)
153
+ for index in range(workers)
154
+ ]
155
+ for thread in self._threads:
156
+ thread.start()
157
+
158
+ @property
159
+ def workers(self) -> int:
160
+ return self._workers
161
+
162
+ @property
163
+ def queue_size(self) -> int:
164
+ return self._queue_size
165
+
166
+ @property
167
+ def pending(self) -> int:
168
+ """Number of requests currently waiting in the input queue."""
169
+ return self._queue.qsize()
170
+
171
+ @property
172
+ def closed(self) -> bool:
173
+ return self._closed
174
+
175
+ def _worker(self) -> None:
176
+ while True:
177
+ task = self._queue.get()
178
+ if task is None:
179
+ self._queue.task_done()
180
+ return
181
+
182
+ future = task.future
183
+ try:
184
+ if not future.set_running_or_notify_cancel():
185
+ continue
186
+ native = _native_solve(
187
+ task.random_data,
188
+ task.difficulty,
189
+ start=task.start,
190
+ stop=task.stop,
191
+ max_seconds=task.max_seconds,
192
+ )
193
+ if native is None:
194
+ limit = (
195
+ "no time limit"
196
+ if task.max_seconds is None
197
+ else f"{task.max_seconds:g}s"
198
+ )
199
+ raise PowBudgetExceeded(
200
+ f"difficulty {task.difficulty} exhausted nonce range "
201
+ f"[{task.start}, {task.stop}) with {limit}"
202
+ )
203
+ nonce, digest = native
204
+ future.set_result(Solution(digest=digest, nonce=nonce))
205
+ except BaseException as error:
206
+ if not future.done():
207
+ future.set_exception(error)
208
+ finally:
209
+ self._queue.task_done()
210
+
211
+ def submit(
212
+ self,
213
+ random_data: str,
214
+ difficulty: int,
215
+ *,
216
+ start: int = 0,
217
+ stop: int | None = None,
218
+ max_seconds: float | None = None,
219
+ block: bool = True,
220
+ timeout: float | None = None,
221
+ ) -> Future[Solution]:
222
+ """Queue one solve and return a future for its result."""
223
+ random_data, difficulty, start, stop, max_seconds = _validate_request(
224
+ random_data, difficulty, start, stop, max_seconds
225
+ )
226
+ future: Future[Solution] = Future()
227
+ task = _Task(
228
+ random_data=random_data,
229
+ difficulty=difficulty,
230
+ start=start,
231
+ stop=stop,
232
+ max_seconds=max_seconds,
233
+ future=future,
234
+ )
235
+ with self._submit_lock:
236
+ if self._closed:
237
+ raise SolverClosedError("solver is shut down")
238
+ self._queue.put(task, block=block, timeout=timeout)
239
+ return future
240
+
241
+ def solve(
242
+ self,
243
+ random_data: str,
244
+ difficulty: int,
245
+ *,
246
+ start: int = 0,
247
+ stop: int | None = None,
248
+ max_seconds: float | None = None,
249
+ ) -> Solution:
250
+ """Queue one solve and block for its result."""
251
+ return self.submit(
252
+ random_data,
253
+ difficulty,
254
+ start=start,
255
+ stop=stop,
256
+ max_seconds=max_seconds,
257
+ ).result()
258
+
259
+ def submit_many(
260
+ self,
261
+ requests: Iterable[Any],
262
+ *,
263
+ max_seconds: float | None = None,
264
+ ) -> list[Future[Solution]]:
265
+ """Queue an iterable of requests and return all futures."""
266
+ return [
267
+ self.submit(**_coerce_request(request, max_seconds))
268
+ for request in requests
269
+ ]
270
+
271
+ def solve_many(
272
+ self,
273
+ requests: Iterable[Any],
274
+ *,
275
+ max_seconds: float | None = None,
276
+ ) -> Iterator[Solution]:
277
+ """Queue requests and yield results in input order.
278
+
279
+ A sliding window keeps at most ``2 * workers`` requests in flight, so a
280
+ large input stream is not materialised into the queue at once.
281
+ """
282
+ pending: deque[Future[Solution]] = deque()
283
+ window = max(1, self._workers * 2)
284
+ for request in requests:
285
+ pending.append(self.submit(**_coerce_request(request, max_seconds)))
286
+ if len(pending) >= window:
287
+ yield pending.popleft().result()
288
+ while pending:
289
+ yield pending.popleft().result()
290
+
291
+ def shutdown(self, wait: bool = True, cancel_futures: bool = False) -> None:
292
+ """Stop accepting requests and terminate the worker pool."""
293
+ with self._submit_lock:
294
+ if not self._closed:
295
+ self._closed = True
296
+ if cancel_futures:
297
+ while True:
298
+ try:
299
+ task = self._queue.get_nowait()
300
+ except queue.Empty:
301
+ break
302
+ if task is not None:
303
+ task.future.cancel()
304
+ self._queue.task_done()
305
+ for _ in self._threads:
306
+ self._queue.put(None)
307
+
308
+ if wait:
309
+ current = threading.current_thread()
310
+ for thread in self._threads:
311
+ if thread is not current:
312
+ thread.join()
313
+
314
+ close = shutdown
315
+
316
+ def __enter__(self) -> "Solver":
317
+ return self
318
+
319
+ def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
320
+ self.shutdown()
321
+
322
+
323
+ _default_solver: Solver | None = None
324
+ _default_lock = threading.Lock()
325
+ _default_workers: int | None = None
326
+ _default_queue_size = 0
327
+
328
+
329
+ def configure(*, workers: int | None = None, queue_size: int = 0) -> None:
330
+ """Set options for the module-level solver before its first use."""
331
+ global _default_workers, _default_queue_size
332
+ with _default_lock:
333
+ if _default_solver is not None:
334
+ raise RuntimeError("call pwsolve.shutdown() before reconfiguring")
335
+ _default_workers = workers
336
+ _default_queue_size = queue_size
337
+
338
+
339
+ def _get_default_solver() -> Solver:
340
+ global _default_solver
341
+ with _default_lock:
342
+ if _default_solver is None:
343
+ _default_solver = Solver(
344
+ workers=_default_workers,
345
+ queue_size=_default_queue_size,
346
+ )
347
+ return _default_solver
348
+
349
+
350
+ def solve_pow(
351
+ random_data: str,
352
+ difficulty: int,
353
+ max_seconds: float | None = None,
354
+ *,
355
+ start: int = 0,
356
+ stop: int | None = None,
357
+ ) -> Solution:
358
+ """Solve using the shared module-level pool."""
359
+ return _get_default_solver().solve(
360
+ random_data,
361
+ difficulty,
362
+ start=start,
363
+ stop=stop,
364
+ max_seconds=max_seconds,
365
+ )
366
+
367
+
368
+ def solve(
369
+ random_data: str,
370
+ difficulty: int,
371
+ max_seconds: float | None = None,
372
+ *,
373
+ start: int = 0,
374
+ stop: int | None = None,
375
+ ) -> Solution:
376
+ """Alias for :func:`solve_pow`."""
377
+ return solve_pow(
378
+ random_data,
379
+ difficulty,
380
+ max_seconds=max_seconds,
381
+ start=start,
382
+ stop=stop,
383
+ )
384
+
385
+
386
+ def solve_many(
387
+ requests: Iterable[Any],
388
+ *,
389
+ max_seconds: float | None = None,
390
+ ) -> Iterator[Solution]:
391
+ """Queue requests on the shared pool and yield results in input order."""
392
+ return _get_default_solver().solve_many(requests, max_seconds=max_seconds)
393
+
394
+
395
+ def shutdown(wait: bool = True) -> None:
396
+ """Shut down the shared module-level pool, if it was created."""
397
+ global _default_solver
398
+ with _default_lock:
399
+ solver = _default_solver
400
+ _default_solver = None
401
+ if solver is not None:
402
+ solver.shutdown(wait=wait)
File without changes
@@ -0,0 +1,138 @@
1
+ use pyo3::exceptions::PyValueError;
2
+ use pyo3::prelude::*;
3
+ use sha2::{Digest, Sha256};
4
+ use std::time::{Duration, Instant};
5
+
6
+ const DEFAULT_WINDOW: u64 = 1 << 62;
7
+ const TIME_CHECK_INTERVAL: u32 = 4096;
8
+
9
+ fn increment_decimal(buf: &mut Vec<u8>) {
10
+ let mut index = buf.len();
11
+ while index > 0 && buf[index - 1] == b'9' {
12
+ buf[index - 1] = b'0';
13
+ index -= 1;
14
+ }
15
+ if index == 0 {
16
+ buf.insert(0, b'1');
17
+ } else {
18
+ buf[index - 1] += 1;
19
+ }
20
+ }
21
+
22
+ fn hex_encode(bytes: &[u8]) -> String {
23
+ const HEX: &[u8; 16] = b"0123456789abcdef";
24
+ let mut out = String::with_capacity(bytes.len() * 2);
25
+ for byte in bytes {
26
+ out.push(HEX[(byte >> 4) as usize] as char);
27
+ out.push(HEX[(byte & 0x0f) as usize] as char);
28
+ }
29
+ out
30
+ }
31
+
32
+ fn solve_bytes(
33
+ random_data: &[u8],
34
+ difficulty: u32,
35
+ start: u64,
36
+ stop: u64,
37
+ max_seconds: Option<f64>,
38
+ ) -> Result<Option<(u64, String)>, String> {
39
+ if difficulty > 64 {
40
+ return Err("difficulty must be between 0 and 64".to_string());
41
+ }
42
+ if let Some(seconds) = max_seconds {
43
+ if !seconds.is_finite() || seconds < 0.0 {
44
+ return Err("max_seconds must be a finite non-negative number".to_string());
45
+ }
46
+ }
47
+
48
+ let stop = if stop <= start {
49
+ start.saturating_add(DEFAULT_WINDOW)
50
+ } else {
51
+ stop
52
+ };
53
+
54
+ let deadline = max_seconds.map(|seconds| {
55
+ Instant::now() + Duration::from_secs_f64(seconds.min(1_000_000_000_000.0))
56
+ });
57
+ if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
58
+ return Ok(None);
59
+ }
60
+
61
+ let full_bytes = (difficulty / 2) as usize;
62
+ let half_byte = difficulty % 2 == 1;
63
+ let mut nonce = start.to_string().into_bytes();
64
+ let mut scratch = Vec::with_capacity(random_data.len() + nonce.len() + 16);
65
+ let mut checked = 0u32;
66
+ let mut n = start;
67
+
68
+ loop {
69
+ if n >= stop {
70
+ return Ok(None);
71
+ }
72
+
73
+ scratch.clear();
74
+ scratch.extend_from_slice(random_data);
75
+ scratch.extend_from_slice(&nonce);
76
+ let digest = Sha256::digest(&scratch);
77
+
78
+ let mut matched = digest[..full_bytes].iter().all(|byte| *byte == 0);
79
+ if matched && half_byte {
80
+ matched = digest[full_bytes] & 0xf0 == 0;
81
+ }
82
+ if matched {
83
+ return Ok(Some((n, hex_encode(&digest))));
84
+ }
85
+
86
+ if n == u64::MAX {
87
+ return Ok(None);
88
+ }
89
+ n += 1;
90
+ if n < stop {
91
+ increment_decimal(&mut nonce);
92
+ }
93
+
94
+ checked += 1;
95
+ if checked >= TIME_CHECK_INTERVAL {
96
+ checked = 0;
97
+ if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
98
+ return Ok(None);
99
+ }
100
+ }
101
+ }
102
+ }
103
+
104
+ #[pyfunction]
105
+ #[pyo3(signature = (random_data, difficulty, *, start=0, stop=None, max_seconds=None))]
106
+ fn solve(
107
+ py: Python<'_>,
108
+ random_data: &str,
109
+ difficulty: u32,
110
+ start: u64,
111
+ stop: Option<u64>,
112
+ max_seconds: Option<f64>,
113
+ ) -> PyResult<Option<(u64, String)>> {
114
+ if difficulty > 64 {
115
+ return Err(PyValueError::new_err(
116
+ "difficulty must be between 0 and 64",
117
+ ));
118
+ }
119
+ if let Some(seconds) = max_seconds {
120
+ if !seconds.is_finite() || seconds < 0.0 {
121
+ return Err(PyValueError::new_err(
122
+ "max_seconds must be a finite non-negative number",
123
+ ));
124
+ }
125
+ }
126
+
127
+ let data = random_data.as_bytes().to_vec();
128
+ let stop = stop.unwrap_or_else(|| start.saturating_add(DEFAULT_WINDOW));
129
+ py.detach(move || solve_bytes(&data, difficulty, start, stop, max_seconds))
130
+ .map_err(PyValueError::new_err)
131
+ }
132
+
133
+ #[pymodule]
134
+ fn _native(module: &Bound<'_, PyModule>) -> PyResult<()> {
135
+ module.add_function(wrap_pyfunction!(solve, module)?)?;
136
+ module.add("__version__", env!("CARGO_PKG_VERSION"))?;
137
+ Ok(())
138
+ }
@@ -0,0 +1,104 @@
1
+ import hashlib
2
+ import unittest
3
+
4
+ import pwsolve
5
+
6
+
7
+ def first_nonce(
8
+ random_data: str, difficulty: int, limit: int = 2_000_000, start: int = 0
9
+ ) -> int:
10
+ target = "0" * difficulty
11
+ for nonce in range(start, start + limit):
12
+ digest = hashlib.sha256(f"{random_data}{nonce}".encode()).hexdigest()
13
+ if digest.startswith(target):
14
+ return nonce
15
+ raise AssertionError("test vector limit exceeded")
16
+
17
+
18
+ class SolverTests(unittest.TestCase):
19
+ def test_known_vector(self):
20
+ expected = first_nonce("abc", 4)
21
+ with pwsolve.Solver(workers=1) as solver:
22
+ result = solver.solve("abc", 4)
23
+ self.assertEqual(result.nonce, expected)
24
+ self.assertEqual(
25
+ result.digest,
26
+ hashlib.sha256(f"abc{expected}".encode()).hexdigest(),
27
+ )
28
+ self.assertTrue(result.digest.startswith("0000"))
29
+
30
+ def test_nonce_shard(self):
31
+ with pwsolve.Solver(workers=1) as solver:
32
+ result = solver.solve("abc", 0, start=17, stop=18)
33
+ self.assertEqual(result.nonce, 17)
34
+ self.assertEqual(
35
+ result.digest,
36
+ hashlib.sha256(b"abc17").hexdigest(),
37
+ )
38
+
39
+ def test_decimal_growth(self):
40
+ expected = first_nonce("abc", 3, start=99_997)
41
+ with pwsolve.Solver(workers=1) as solver:
42
+ result = solver.solve("abc", 3, start=99_997)
43
+ self.assertEqual(result.nonce, expected)
44
+ self.assertEqual(
45
+ result.digest,
46
+ hashlib.sha256(f"abc{expected}".encode()).hexdigest(),
47
+ )
48
+
49
+ def test_workers_and_queue(self):
50
+ requests = [f"challenge-{index}" for index in range(6)]
51
+ with pwsolve.Solver(workers=2, queue_size=4) as solver:
52
+ futures = [solver.submit(data, 3) for data in requests]
53
+ results = [future.result(timeout=10) for future in futures]
54
+ for data, result in zip(requests, results):
55
+ self.assertTrue(result.digest.startswith("000"))
56
+ self.assertEqual(
57
+ result.digest,
58
+ hashlib.sha256(f"{data}{result.nonce}".encode()).hexdigest(),
59
+ )
60
+
61
+ def test_solve_many_preserves_order(self):
62
+ requests = [("alpha", 3), ("beta", 3), ("gamma", 3)]
63
+ with pwsolve.Solver(workers=2) as solver:
64
+ results = list(solver.solve_many(requests))
65
+ self.assertEqual(len(results), 3)
66
+ for (data, _), result in zip(requests, results):
67
+ self.assertEqual(
68
+ result.digest,
69
+ hashlib.sha256(f"{data}{result.nonce}".encode()).hexdigest(),
70
+ )
71
+
72
+ def test_time_budget(self):
73
+ with pwsolve.Solver(workers=1) as solver:
74
+ with self.assertRaises(pwsolve.PowBudgetExceeded):
75
+ solver.solve("abc", 64, max_seconds=0.001)
76
+
77
+ def test_shutdown_rejects_new_work(self):
78
+ solver = pwsolve.Solver(workers=1)
79
+ solver.shutdown()
80
+ with self.assertRaises(pwsolve.SolverClosedError):
81
+ solver.submit("abc", 1)
82
+
83
+ def test_invalid_options(self):
84
+ with self.assertRaises(ValueError):
85
+ pwsolve.Solver(workers=0)
86
+ with self.assertRaises(ValueError):
87
+ pwsolve.Solver(queue_size=-1)
88
+ with pwsolve.Solver(workers=1) as solver:
89
+ with self.assertRaises(ValueError):
90
+ solver.solve("abc", 65)
91
+
92
+ def test_module_level_pool(self):
93
+ pwsolve.configure(workers=2, queue_size=4)
94
+ try:
95
+ result = pwsolve.solve_pow("abc", 0)
96
+ self.assertEqual(result.nonce, 0)
97
+ batch = list(pwsolve.solve_many([("a", 0), ("b", 0)]))
98
+ self.assertEqual([item.nonce for item in batch], [0, 0])
99
+ finally:
100
+ pwsolve.shutdown()
101
+
102
+
103
+ if __name__ == "__main__":
104
+ unittest.main()