-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpu_verify.py
More file actions
1707 lines (1414 loc) · 59.3 KB
/
Copy pathcpu_verify.py
File metadata and controls
1707 lines (1414 loc) · 59.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import ctypes
import hashlib
import os
import threading
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Optional
import numpy as np
from models import CandidateShare, MiningJob, VerifiedShare
from utils import nonce_to_hex_le, safe_bytes_from_hex
MAX_U64 = 0xFFFFFFFFFFFFFFFF
MAX_U256 = (1 << 256) - 1
def _normalize_hex(text: Optional[str]) -> str:
if not text:
return ""
return "".join(ch for ch in text.strip().lower() if not ch.isspace())
def _nonce_array(nonces: list[int] | np.ndarray | None) -> np.ndarray:
if nonces is None:
return np.empty((0,), dtype=np.uint32)
if isinstance(nonces, np.ndarray):
return np.ascontiguousarray(nonces, dtype=np.uint32)
return np.ascontiguousarray(list(nonces), dtype=np.uint32)
def _nonce_range_array(start_nonce: int, count: int) -> np.ndarray:
count = max(0, int(count))
if count <= 0:
return np.empty((0,), dtype=np.uint32)
base = np.uint64(int(start_nonce) & 0xFFFFFFFF)
seq = (np.arange(count, dtype=np.uint64) + base) & np.uint64(0xFFFFFFFF)
return np.ascontiguousarray(seq.astype(np.uint32))
def parse_target_hex_to_bytes(target_hex: str) -> bytes:
s = _normalize_hex(target_hex)
raw = safe_bytes_from_hex(s)
if not raw:
return b""
if len(raw) >= 32:
return raw[:32]
return raw.ljust(32, b"\x00")
def target_hex_uses_full_256(target_hex: str) -> bool:
raw = safe_bytes_from_hex(_normalize_hex(target_hex))
return bool(raw) and len(raw) >= 32
def target_hex_to_int(target_hex: str) -> int:
raw = parse_target_hex_to_bytes(target_hex)
if not raw:
return 0
return int.from_bytes(raw, "little", signed=False)
def parse_target_hex_to_u64(target_hex: str) -> int:
s = _normalize_hex(target_hex)
raw = safe_bytes_from_hex(s)
if not raw:
return 0
if len(raw) == 4:
t32 = int.from_bytes(raw, "little", signed=False)
if t32 == 0:
return 0
denom = 0xFFFFFFFF // t32
if denom == 0:
return MAX_U64
return MAX_U64 // denom
if len(raw) >= 8:
return int.from_bytes(raw[:8], "little", signed=False)
return int.from_bytes(raw.ljust(8, b"\x00"), "little", signed=False)
def target_hex_to_assigned_work(target_hex: str) -> float:
raw = safe_bytes_from_hex(_normalize_hex(target_hex))
if not raw:
return 0.0
if len(raw) >= 32:
target_int = int.from_bytes(parse_target_hex_to_bytes(target_hex), "little", signed=False)
if target_int <= 0:
return 0.0
return float(MAX_U256) / float(target_int)
target64 = parse_target_hex_to_u64(target_hex)
if target64 <= 0:
return 0.0
return float(MAX_U64) / float(target64)
def hash_bytes_to_actual_hash_int(hash32: bytes) -> int:
if not hash32 or len(hash32) < 32:
return 0
return int.from_bytes(hash32[:32], "little", signed=False)
def hash_bytes_to_actual_tail_u64(hash32: bytes) -> int:
if not hash32 or len(hash32) < 32:
return 0
return int.from_bytes(hash32[24:32], "little", signed=False)
def tail_u64_to_actual_work(tail_u64: int) -> float:
v = int(tail_u64) & MAX_U64
if v <= 0:
return float(MAX_U64)
return float(MAX_U64) / float(v)
def hash_bytes_to_actual_work(hash32: bytes, target_hex: str) -> float:
raw = safe_bytes_from_hex(_normalize_hex(target_hex))
if not raw:
return 0.0
if len(raw) >= 32:
v = hash_bytes_to_actual_hash_int(hash32)
if v <= 0:
return float(MAX_U256)
return float(MAX_U256) / float(v)
return tail_u64_to_actual_work(hash_bytes_to_actual_tail_u64(hash32))
def hash_meets_target(hash32: bytes, target_hex: str) -> bool:
raw = safe_bytes_from_hex(_normalize_hex(target_hex))
if not raw or len(hash32) < 32:
return False
if len(raw) >= 32:
target_int = int.from_bytes(parse_target_hex_to_bytes(target_hex), "little", signed=False)
if target_int <= 0:
return False
hash_int = hash_bytes_to_actual_hash_int(hash32)
return hash_int <= target_int
target64 = parse_target_hex_to_u64(target_hex)
if target64 <= 0:
return False
return hash_bytes_to_actual_tail_u64(hash32) <= target64
@dataclass(frozen=True)
class _PreparedSeed:
seed: bytes
seed_hex_norm: str
fingerprint: bytes
dataset_fingerprint: bytes
@dataclass(frozen=True)
class _PreparedJob:
job_id: str
blob: bytes
target_hex: str
target_b: bytes
blob_hex_norm: str
target_raw: bytes
target_int: int
target64: int
assigned_work: float
fingerprint: bytes
seed_ctx: _PreparedSeed
full_target: bool
@dataclass
class HashLabelResult:
share: CandidateShare
exact_hash_hex: str = ""
exact_tail_u64: int = 0
predictor_hash_match: bool = False
verified: Optional[VerifiedShare] = None
credited_work: float = 0.0
accepted_by_tail: bool = False
tail_only: bool = False
class _NativeHandle:
__slots__ = (
"_lib",
"_handle",
"_lock",
"_current_seed_fingerprint",
"_current_job_fingerprint",
"_current_dataset_fingerprint",
)
def __init__(self, lib: ctypes.CDLL) -> None:
self._lib = lib
self._handle = lib.bnrx_create()
if not self._handle:
raise RuntimeError("bnrx_create returned null")
self._lock = threading.RLock()
self._current_seed_fingerprint: Optional[bytes] = None
self._current_job_fingerprint: Optional[bytes] = None
self._current_dataset_fingerprint: Optional[bytes] = None
@property
def current_job_fingerprint(self) -> Optional[bytes]:
return self._current_job_fingerprint
@property
def current_dataset_fingerprint(self) -> Optional[bytes]:
return self._current_dataset_fingerprint
@property
def has_prepare_seed(self) -> bool:
return hasattr(self._lib, "bnrx_prepare_seed")
@property
def has_set_job(self) -> bool:
return hasattr(self._lib, "bnrx_set_job")
@property
def has_warm_batch_vms(self) -> bool:
return hasattr(self._lib, "bnrx_warm_batch_vms")
@property
def has_batch_verify(self) -> bool:
return hasattr(self._lib, "bnrx_verify_nonce_batch")
@property
def has_hash_nonce(self) -> bool:
return hasattr(self._lib, "bnrx_hash_nonce")
@property
def has_batch_hash(self) -> bool:
return hasattr(self._lib, "bnrx_hash_nonce_batch")
@property
def has_batch_tail(self) -> bool:
return hasattr(self._lib, "bnrx_tail_nonce_batch")
def close(self) -> None:
with self._lock:
if self._handle:
try:
self._lib.bnrx_destroy(self._handle)
finally:
self._handle = None
self._current_seed_fingerprint = None
self._current_job_fingerprint = None
self._current_dataset_fingerprint = None
def _last_error_unlocked(self) -> str:
if not self._handle or not hasattr(self._lib, "bnrx_last_error"):
return ""
try:
raw = self._lib.bnrx_last_error(self._handle)
if not raw:
return ""
if isinstance(raw, bytes):
return raw.decode("utf-8", errors="replace")
return str(raw)
except Exception:
return ""
def last_error(self) -> str:
with self._lock:
return self._last_error_unlocked()
def prepare_seed(self, seed_ctx: _PreparedSeed) -> None:
if self._current_seed_fingerprint == seed_ctx.fingerprint:
return
if not self.has_prepare_seed:
raise RuntimeError("native verifier does not export bnrx_prepare_seed")
seed_arr = _to_ubyte_array(seed_ctx.seed)
with self._lock:
if not self._handle:
raise RuntimeError("native verifier handle is closed")
if self._current_seed_fingerprint == seed_ctx.fingerprint:
return
rc = int(
self._lib.bnrx_prepare_seed(
self._handle,
seed_arr,
ctypes.c_size_t(len(seed_ctx.seed)),
)
)
if rc != 0:
raise RuntimeError(
self._last_error_unlocked() or f"bnrx_prepare_seed failed with rc={rc}"
)
self._current_seed_fingerprint = seed_ctx.fingerprint
self._current_dataset_fingerprint = seed_ctx.dataset_fingerprint
self._current_job_fingerprint = None
def set_job(self, prepared: _PreparedJob, nonce_offset: int) -> None:
if (
self._current_job_fingerprint == prepared.fingerprint
and self._current_seed_fingerprint == prepared.seed_ctx.fingerprint
):
return
blob_arr = _to_ubyte_array(prepared.blob)
with self._lock:
if not self._handle:
raise RuntimeError("native verifier handle is closed")
if (
self._current_job_fingerprint == prepared.fingerprint
and self._current_seed_fingerprint == prepared.seed_ctx.fingerprint
):
return
if self.has_set_job:
rc = int(
self._lib.bnrx_set_job(
self._handle,
blob_arr,
ctypes.c_size_t(len(prepared.blob)),
ctypes.c_uint32(int(nonce_offset)),
ctypes.c_char_p(prepared.target_b),
)
)
else:
seed_arr = _to_ubyte_array(prepared.seed_ctx.seed)
rc = int(
self._lib.bnrx_prepare_job(
self._handle,
blob_arr,
ctypes.c_size_t(len(prepared.blob)),
ctypes.c_uint32(int(nonce_offset)),
seed_arr,
ctypes.c_size_t(len(prepared.seed_ctx.seed)),
ctypes.c_char_p(prepared.target_b),
)
)
if rc != 0:
raise RuntimeError(
self._last_error_unlocked() or f"bnrx_set_job failed with rc={rc}"
)
self._current_job_fingerprint = prepared.fingerprint
self._current_seed_fingerprint = prepared.seed_ctx.fingerprint
self._current_dataset_fingerprint = prepared.seed_ctx.dataset_fingerprint
def warm_batch_vms(self, wanted: int) -> None:
if not self.has_warm_batch_vms:
return
with self._lock:
if not self._handle:
raise RuntimeError("native verifier handle is closed")
rc = int(
self._lib.bnrx_warm_batch_vms(
self._handle,
ctypes.c_size_t(max(0, int(wanted))),
)
)
if rc != 0:
raise RuntimeError(
self._last_error_unlocked() or f"bnrx_warm_batch_vms failed with rc={rc}"
)
def prepare(self, prepared: _PreparedJob, nonce_offset: int) -> None:
if self.has_prepare_seed and self.has_set_job:
self.prepare_seed(prepared.seed_ctx)
self.set_job(prepared, nonce_offset)
return
blob_arr = _to_ubyte_array(prepared.blob)
seed_arr = _to_ubyte_array(prepared.seed_ctx.seed)
with self._lock:
if not self._handle:
raise RuntimeError("native verifier handle is closed")
rc = int(
self._lib.bnrx_prepare_job(
self._handle,
blob_arr,
ctypes.c_size_t(len(prepared.blob)),
ctypes.c_uint32(int(nonce_offset)),
seed_arr,
ctypes.c_size_t(len(prepared.seed_ctx.seed)),
ctypes.c_char_p(prepared.target_b),
)
)
if rc != 0:
raise RuntimeError(
self._last_error_unlocked() or f"bnrx_prepare_job failed with rc={rc}"
)
self._current_seed_fingerprint = prepared.seed_ctx.fingerprint
self._current_job_fingerprint = prepared.fingerprint
self._current_dataset_fingerprint = prepared.seed_ctx.dataset_fingerprint
def verify_nonce(self, nonce: int) -> tuple[int, bytes]:
out_hash = (ctypes.c_ubyte * 32)()
with self._lock:
if not self._handle:
raise RuntimeError("native verifier handle is closed")
rc = int(
self._lib.bnrx_verify_nonce(
self._handle,
ctypes.c_uint32(int(nonce) & 0xFFFFFFFF),
out_hash,
)
)
return rc, bytes(out_hash)
def verify_nonces_batch(
self,
nonces: list[int] | np.ndarray,
*,
max_threads: int = 0,
) -> tuple[int, np.ndarray, np.ndarray]:
if not self.has_batch_verify:
raise RuntimeError("native verifier does not export bnrx_verify_nonce_batch")
nonce_np = _nonce_array(nonces)
count = int(nonce_np.size)
out_accepts = np.zeros((count,), dtype=np.uint8)
out_hashes = np.empty((count, 32), dtype=np.uint8)
if count <= 0:
return 0, out_accepts, out_hashes
with self._lock:
if not self._handle:
raise RuntimeError("native verifier handle is closed")
rc = int(
self._lib.bnrx_verify_nonce_batch(
self._handle,
nonce_np.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)),
ctypes.c_size_t(count),
out_hashes.ctypes.data_as(ctypes.POINTER(ctypes.c_ubyte)),
out_accepts.ctypes.data_as(ctypes.POINTER(ctypes.c_ubyte)),
ctypes.c_size_t(max(0, int(max_threads))),
)
)
return rc, out_accepts, out_hashes
def hash_nonce(self, nonce: int) -> bytes:
if not self.has_hash_nonce:
raise RuntimeError("native verifier does not export bnrx_hash_nonce")
out_hash = (ctypes.c_ubyte * 32)()
with self._lock:
if not self._handle:
raise RuntimeError("native verifier handle is closed")
rc = int(
self._lib.bnrx_hash_nonce(
self._handle,
ctypes.c_uint32(int(nonce) & 0xFFFFFFFF),
out_hash,
)
)
if rc != 0:
raise RuntimeError(
self._last_error_unlocked() or f"bnrx_hash_nonce failed with rc={rc}"
)
return bytes(out_hash)
def hash_nonces_batch(
self,
nonces: list[int] | np.ndarray,
*,
max_threads: int = 0,
) -> tuple[int, np.ndarray]:
if not self.has_batch_hash:
raise RuntimeError("native verifier does not export bnrx_hash_nonce_batch")
nonce_np = _nonce_array(nonces)
count = int(nonce_np.size)
out_hashes = np.empty((count, 32), dtype=np.uint8)
if count <= 0:
return 0, out_hashes
with self._lock:
if not self._handle:
raise RuntimeError("native verifier handle is closed")
rc = int(
self._lib.bnrx_hash_nonce_batch(
self._handle,
nonce_np.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)),
ctypes.c_size_t(count),
out_hashes.ctypes.data_as(ctypes.POINTER(ctypes.c_ubyte)),
ctypes.c_size_t(max(0, int(max_threads))),
)
)
return rc, out_hashes
def tail_nonces_batch(
self,
nonces: list[int] | np.ndarray,
*,
max_threads: int = 0,
) -> tuple[int, np.ndarray, np.ndarray]:
if not self.has_batch_tail:
raise RuntimeError("native verifier does not export bnrx_tail_nonce_batch")
nonce_np = _nonce_array(nonces)
count = int(nonce_np.size)
out_tails = np.empty((count,), dtype=np.uint64)
out_accepts = np.zeros((count,), dtype=np.uint8)
if count <= 0:
return 0, out_accepts, out_tails
with self._lock:
if not self._handle:
raise RuntimeError("native verifier handle is closed")
rc = int(
self._lib.bnrx_tail_nonce_batch(
self._handle,
nonce_np.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)),
ctypes.c_size_t(count),
out_tails.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)),
out_accepts.ctypes.data_as(ctypes.POINTER(ctypes.c_ubyte)),
ctypes.c_size_t(max(0, int(max_threads))),
)
)
return rc, out_accepts, out_tails
def dataset_words64(self) -> int:
with self._lock:
if not self._handle:
raise RuntimeError("native verifier handle is closed")
return int(self._lib.bnrx_dataset_words64(self._handle))
def export_dataset64(self) -> np.ndarray:
words = self.dataset_words64()
if words <= 0:
raise RuntimeError(self.last_error() or "bnrx_dataset_words64 returned 0")
arr = np.empty(words, dtype=np.uint64)
ptr = arr.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64))
with self._lock:
if not self._handle:
raise RuntimeError("native verifier handle is closed")
rc = int(
self._lib.bnrx_export_dataset64(
self._handle,
ptr,
ctypes.c_size_t(words),
)
)
if rc != 0:
raise RuntimeError(
self._last_error_unlocked() or f"bnrx_export_dataset64 failed with rc={rc}"
)
return arr
class CpuVerifier:
_ENV_DLL_KEYS = (
"BLOCKNET_RANDOMX_VERIFY_DLL",
"RANDOMX_VERIFY_DLL",
"BNRX_VERIFY_DLL",
)
_ENV_RUNTIME_KEYS = (
"BLOCKNET_RANDOMX_RUNTIME_DLL",
"RANDOMX_RUNTIME_DLL",
"RANDOMX_DLL",
)
_DEFAULT_LIB_NAMES = (
"MiningProject.dll",
"blocknet_randomx_verify.dll",
"randomx_verify.dll",
"bnrx_verify.dll",
"blocknet_randomx_verify.so",
"randomx_verify.so",
"libblocknet_randomx_verify.so",
"librandomx_verify.so",
"blocknet_randomx_verify.dylib",
"librandomx_verify.dylib",
)
_DEFAULT_RUNTIME_NAMES = (
"randomx-dll.dll",
"randomx.dll",
"librandomx.so",
"librandomx.dylib",
)
def __init__(
self,
dll_path: Optional[str] = None,
*,
randomx_runtime_dll_path: Optional[str] = None,
preload_randomx_runtime: bool = True,
nonce_offset: int = 39,
on_log: Optional[Callable[[str], None]] = None,
strict: bool = False,
) -> None:
self.nonce_offset = int(nonce_offset)
self.on_log = on_log
self.strict = bool(strict)
self._state_lock = threading.RLock()
self._handles_lock = threading.Lock()
self._tls = threading.local()
self._lib: Optional[ctypes.CDLL] = None
self._export_handle: Optional[_NativeHandle] = None
self._thread_handles: dict[int, _NativeHandle] = {}
self._disabled_reason: Optional[str] = None
self._current_prepared_job: Optional[_PreparedJob] = None
self._warm_batch_vms_target: int = 0
self._randomx_runtime_lib: Optional[ctypes.CDLL] = None
self._randomx_runtime_path: Optional[str] = None
self._dll_directory_handles: list[object] = []
try:
if preload_randomx_runtime:
self._randomx_runtime_lib = self._maybe_preload_randomx_runtime(randomx_runtime_dll_path)
resolved = self._resolve_library_path(dll_path)
if not resolved:
raise FileNotFoundError(
"No RandomX verifier library found. "
"Set BLOCKNET_RANDOMX_VERIFY_DLL or place a verifier DLL/SO next to the app."
)
self._lib = self._load_library(resolved)
self._export_handle = _NativeHandle(self._lib)
self._log(f"[verify] native verifier loaded: {resolved}")
if self._randomx_runtime_path:
self._log(f"[verify] preloaded RandomX runtime: {self._randomx_runtime_path}")
self._log(
"[verify] mode=per-thread handles + dedicated export handle "
"(native side is expected to share dataset/cache by seed)"
)
self._log(f"[verify] prepare_seed_export={'yes' if self.has_prepare_seed else 'no'}")
self._log(f"[verify] set_job_export={'yes' if self.has_set_job else 'no'}")
self._log(f"[verify] warm_batch_vms_export={'yes' if self.has_warm_batch_vms else 'no'}")
self._log(f"[verify] batch_verify_export={'yes' if self.has_batch_verify else 'no'}")
self._log(f"[verify] batch_hash_export={'yes' if self.has_batch_hash else 'no'}")
self._log(f"[verify] batch_tail_export={'yes' if self.has_batch_tail else 'no'}")
except Exception as exc:
self._disabled_reason = str(exc)
self._log(f"[verify] disabled: {self._disabled_reason}")
if self.strict:
raise
@property
def is_ready(self) -> bool:
return self._lib is not None and self._export_handle is not None and not self._disabled_reason
@property
def disabled_reason(self) -> str:
return self._disabled_reason or ""
@property
def has_dataset_exports(self) -> bool:
lib = self._lib
return (
lib is not None
and hasattr(lib, "bnrx_dataset_words64")
and hasattr(lib, "bnrx_export_dataset64")
)
@property
def has_prepare_seed(self) -> bool:
lib = self._lib
return lib is not None and hasattr(lib, "bnrx_prepare_seed")
@property
def has_set_job(self) -> bool:
lib = self._lib
return lib is not None and hasattr(lib, "bnrx_set_job")
@property
def has_warm_batch_vms(self) -> bool:
lib = self._lib
return lib is not None and hasattr(lib, "bnrx_warm_batch_vms")
@property
def has_batch_verify(self) -> bool:
lib = self._lib
return lib is not None and hasattr(lib, "bnrx_verify_nonce_batch")
@property
def has_hash_nonce(self) -> bool:
lib = self._lib
return lib is not None and hasattr(lib, "bnrx_hash_nonce")
@property
def has_batch_hash(self) -> bool:
lib = self._lib
return lib is not None and hasattr(lib, "bnrx_hash_nonce_batch")
@property
def has_batch_tail(self) -> bool:
lib = self._lib
return lib is not None and hasattr(lib, "bnrx_tail_nonce_batch")
@property
def current_dataset_fingerprint(self) -> Optional[bytes]:
with self._state_lock:
prepared = self._current_prepared_job
return prepared.seed_ctx.dataset_fingerprint if prepared is not None else None
def close(self) -> None:
with self._handles_lock:
export_handle = self._export_handle
self._export_handle = None
handles = list(self._thread_handles.values())
self._thread_handles.clear()
if export_handle is not None:
try:
export_handle.close()
except Exception:
pass
for handle in handles:
try:
handle.close()
except Exception:
pass
with self._state_lock:
self._current_prepared_job = None
self._lib = None
self._randomx_runtime_lib = None
self._randomx_runtime_path = None
self._dll_directory_handles.clear()
self._warm_batch_vms_target = 0
def __del__(self) -> None:
try:
self.close()
except Exception:
pass
def prepare_seed_for_job(self, job: MiningJob) -> None:
prepared = self._build_prepared_from_job(job)
with self._state_lock:
if not self.is_ready:
raise RuntimeError(self.disabled_reason or "native verifier is not available")
current = self._current_prepared_job
if current is not None and current.seed_ctx.fingerprint == prepared.seed_ctx.fingerprint:
return
export_handle = self._require_export_handle()
if self.has_prepare_seed:
export_handle.prepare_seed(prepared.seed_ctx)
else:
export_handle.prepare(prepared, self.nonce_offset)
with self._state_lock:
self._current_prepared_job = prepared
def set_job(self, job: MiningJob) -> None:
prepared = self._build_prepared_from_job(job)
with self._state_lock:
if not self.is_ready:
raise RuntimeError(self.disabled_reason or "native verifier is not available")
current = self._current_prepared_job
if (
current is not None
and current.fingerprint == prepared.fingerprint
and current.seed_ctx.fingerprint == prepared.seed_ctx.fingerprint
):
return
export_handle = self._require_export_handle()
if self.has_prepare_seed and self.has_set_job:
export_handle.prepare_seed(prepared.seed_ctx)
export_handle.set_job(prepared, self.nonce_offset)
else:
export_handle.prepare(prepared, self.nonce_offset)
with self._state_lock:
self._current_prepared_job = prepared
def warm_batch_vms(self, wanted: int) -> None:
wanted = max(0, int(wanted))
with self._state_lock:
self._warm_batch_vms_target = wanted
prepared = self._current_prepared_job
if wanted <= 0 or prepared is None or not self.has_warm_batch_vms:
return
handles: list[_NativeHandle] = []
export_handle = self._require_export_handle()
with self._handles_lock:
handles.append(export_handle)
handles.extend(self._thread_handles.values())
for handle in handles:
try:
if self.has_prepare_seed:
handle.prepare_seed(prepared.seed_ctx)
else:
handle.prepare(prepared, self.nonce_offset)
handle.warm_batch_vms(wanted)
except Exception as exc:
self._log(f"[verify] warm batch vms skipped for handle: {exc}")
def prepare_job(self, job: MiningJob) -> None:
prepared = self._build_prepared_from_job(job)
with self._state_lock:
if not self.is_ready:
raise RuntimeError(self.disabled_reason or "native verifier is not available")
current = self._current_prepared_job
if (
current is not None
and current.fingerprint == prepared.fingerprint
and current.seed_ctx.fingerprint == prepared.seed_ctx.fingerprint
):
return
export_handle = self._require_export_handle()
export_handle.prepare(prepared, self.nonce_offset)
with self._state_lock:
self._current_prepared_job = prepared
self._log(
f"[verify] prepared job job_id={job.job_id} "
f"height={job.height} algo={job.algo} "
f"full_target={1 if prepared.full_target else 0} "
f"target64={prepared.target64} assigned_work={prepared.assigned_work:.6f}"
)
def export_dataset_u64(self) -> np.ndarray:
with self._state_lock:
if not self.is_ready:
raise RuntimeError(self.disabled_reason or "native verifier is not available")
prepared = self._current_prepared_job
if prepared is None:
raise RuntimeError("no job is prepared")
if not self.has_dataset_exports:
raise RuntimeError(
"native verifier is missing dataset exports: "
"bnrx_dataset_words64 / bnrx_export_dataset64"
)
export_handle = self._require_export_handle()
if self.has_prepare_seed:
export_handle.prepare_seed(prepared.seed_ctx)
else:
export_handle.prepare(prepared, self.nonce_offset)
arr = export_handle.export_dataset64()
mib = arr.nbytes / (1024.0 * 1024.0)
self._log(f"[verify] exported RandomX dataset: words={arr.size} size={mib:.2f} MiB")
return arr
def verify(self, share: CandidateShare) -> Optional[VerifiedShare]:
verified, _credited_work = self.verify_with_work(share)
return verified
def verify_with_work(self, share: CandidateShare) -> tuple[Optional[VerifiedShare], float]:
results = self.label_shares_batch_with_hashes([share], max_threads=0)
if not results:
return None, 0.0
return results[0].verified, results[0].credited_work
def verify_batch_with_work(
self,
shares: list[CandidateShare],
*,
max_threads: int = 0,
) -> list[tuple[Optional[VerifiedShare], float]]:
labeled = self.label_shares_batch_with_hashes(shares, max_threads=max_threads)
return [(item.verified, item.credited_work) for item in labeled]
def rescue_scan_window(
self,
job: MiningJob,
start_nonce: int,
count: int,
*,
batch_size: int = 1024,
max_threads: int = 0,
) -> list[tuple[CandidateShare, VerifiedShare]]:
count = max(0, int(count))
batch_size = max(1, int(batch_size))
if count <= 0 or not self.is_ready:
return []
prepared = self._build_prepared_from_job(job)
handle = self._get_thread_handle()
handle.prepare(prepared, self.nonce_offset)
hits: list[tuple[CandidateShare, VerifiedShare]] = []
scanned = 0
while scanned < count:
this_batch = min(batch_size, count - scanned)
nonce_np = _nonce_range_array((int(start_nonce) + scanned) & 0xFFFFFFFF, this_batch)
hashes_np: Optional[np.ndarray] = None
if this_batch > 1 and self.has_batch_hash:
try:
rc, hashes_np = handle.hash_nonces_batch(nonce_np, max_threads=max_threads)
if rc != 0:
raise RuntimeError(
handle.last_error() or f"bnrx_hash_nonce_batch failed with rc={rc}"
)
except Exception as exc:
self._log(f"[verify] rescue hash batch fallback size={this_batch} reason={exc}")
hashes_np = None
if hashes_np is None and this_batch > 1 and self.has_batch_verify:
try:
rc, _accepts_np, hashes_np = handle.verify_nonces_batch(
nonce_np,
max_threads=max_threads,
)
if rc != 0:
raise RuntimeError(
handle.last_error() or f"bnrx_verify_nonce_batch failed with rc={rc}"
)
except Exception as exc:
self._log(f"[verify] rescue verify batch fallback size={this_batch} reason={exc}")
hashes_np = None
if hashes_np is not None:
for idx, nonce_u32 in enumerate(nonce_np):
cand = CandidateShare(
nonce=int(nonce_u32),
gpu_hash_hex="",
job_id=job.job_id,
blob_hex=job.blob_hex,
session_id=job.session_id,
target_hex=job.target_hex,
seed_hash_hex=job.seed_hash_hex,
source="cpu_rescue",
)
item = self._label_share_from_hash(prepared, cand, hashes_np[idx].tobytes())
if item.verified is not None:
hits.append((cand, item.verified))
else:
for nonce_u32 in nonce_np:
nonce_i = int(nonce_u32)
try:
if self.has_hash_nonce:
out_hash = handle.hash_nonce(nonce_i)
else:
rc, out_hash = handle.verify_nonce(nonce_i)
if rc < 0:
raise RuntimeError(
handle.last_error() or f"bnrx_verify_nonce failed with rc={rc}"
)
except Exception as exc:
self._log(f"[verify] rescue single nonce failed nonce={nonce_i:08x}: {exc}")
continue
cand = CandidateShare(
nonce=nonce_i,
gpu_hash_hex="",
job_id=job.job_id,
blob_hex=job.blob_hex,
session_id=job.session_id,