Skip to content

Feature/full implementation - #8

Open
ufomasters77-ship-it wants to merge 11 commits into
vishwamartur:mainfrom
ufomasters77-ship-it:feature/full-implementation
Open

Feature/full implementation#8
ufomasters77-ship-it wants to merge 11 commits into
vishwamartur:mainfrom
ufomasters77-ship-it:feature/full-implementation

Conversation

@ufomasters77-ship-it

Copy link
Copy Markdown

No description provided.

… wallets, generators, CMake, configs, README
…putation + early-exit) with test harness; update CMake to build tests
…CL guarded), stubbed check_batch; prepare for full GPU PBKDF2 implementation
…into gpu_engine, update CMake to compile CUDA kernel when ENABLE_CUDA=ON
@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@ufomasters77-ship-it, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 38 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: bc21b16d-f637-45ea-b1af-38c6d5e1bbec

📥 Commits

Reviewing files that changed from the base of the PR and between fddcc81 and 33d851a.

📒 Files selected for processing (57)
  • AVX2_PROGRESS.md
  • CMakeLists.txt
  • CMakeLists.txt.updated
  • README.md
  • cmake_add_sha512_avx2.txt
  • config/cluster.yaml
  • config/recovery.yaml
  • include/btc/engine.h
  • src/core/engine.cpp
  • src/core/password_generator.cpp
  • src/core/password_generator.h
  • src/core/pcfg_generator.cpp
  • src/core/pcfg_generator.h
  • src/core/rules_engine.cpp
  • src/core/rules_engine.h
  • src/crypto/pbkdf2_hmac_sha512.cpp
  • src/crypto/pbkdf2_hmac_sha512.cpp.updated
  • src/crypto/pbkdf2_hmac_sha512.h
  • src/crypto/sha512_avx2.cpp
  • src/crypto/sha512_avx2.h
  • src/crypto/sha512_avx2_impl.cpp
  • src/crypto/sha512_avx2_impl.h
  • src/crypto/sha512_avx2_impl_intrinsics.cpp
  • src/crypto/sha512_portable.cpp
  • src/crypto/sha512_portable.h
  • src/gpu/cuda_kernel.cu
  • src/gpu/gpu_backend_forward.h
  • src/gpu/gpu_engine.cpp
  • src/gpu/gpu_engine.cpp.updated2
  • src/gpu/gpu_engine.h
  • src/gpu/gpu_engine_opencl.cpp
  • src/gpu/opencl_kernel.cl
  • src/gpu/opencl_pbdkf2.cl
  • src/gpu/opencl_pbdkf2.cl.updated
  • src/gpu/pbkdf2_cuda.cu
  • src/gpu/pbkdf2_cuda.h
  • src/main.cpp
  • src/utils/checkpoint.cpp
  • src/utils/checkpoint.h
  • src/utils/file_utils.cpp
  • src/utils/file_utils.h
  • src/utils/io_utils.cpp
  • src/utils/io_utils.h
  • src/utils/logger.cpp
  • src/utils/logger.h
  • src/utils/thread_pool.cpp
  • src/utils/thread_pool.h
  • src/wallets/armory_wallet.cpp
  • src/wallets/armory_wallet.h
  • src/wallets/bdb_parser.cpp
  • src/wallets/bdb_parser.h
  • src/wallets/bitcoin_core_wallet.cpp
  • src/wallets/bitcoin_core_wallet.h
  • src/wallets/electrum_wallet.cpp
  • src/wallets/electrum_wallet.h
  • tests/pbkdf2_test.cpp
  • tests/sha512_bench.cpp
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…ic (compute capability/multiprocessors), expose selected_device/name, and forward check_batch to backend-specific implementations; tuned for older GPUs (e.g., GTX 750 Ti).
@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Add CPU+CUDA PBKDF2-HMAC-SHA512 path, GPU probing, and skeleton recovery engine

✨ Enhancement 🧪 Tests ⚙️ Configuration changes 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Introduce a minimal CLI + Engine skeleton to drive dictionary/bruteforce recovery flows.
• Implement optimized PBKDF2-HMAC-SHA512 on CPU and a first-pass CUDA kernel.
• Add CMake targets and a PBKDF2 correctness test harness; simplify example configs/docs.
Diagram

graph TD
  cli["src/main.cpp"] --> engine["btc::Engine"] --> wallet["wallet parsers"] --> pbkdf2["PBKDF2 CPU"]
  engine --> gpu["gpu::GPUEngine"] --> cuda["pbkdf2_cuda_kernel"]
  cli --> cfg[("config/recovery.yaml")]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use OpenSSL-only PBKDF2 (CPU) + postpone custom PBKDF2
  • ➕ Avoids maintaining a bespoke PBKDF2/HMAC implementation
  • ➕ Reduces correctness and side-channel risk surface
  • ➕ Simplifies portability and testing requirements
  • ➖ Less room for early-exit/prefix-compare optimizations
  • ➖ Harder to share logic with CUDA/OpenCL implementations later
2. GPU offload via a proven cracking kernel strategy (hashcat-style layout)
  • ➕ Established memory/layout patterns for large candidate batches
  • ➕ Avoids device-side malloc/free and reduces per-thread overhead
  • ➕ Easier to extend to multiple dkLen blocks and multiple salts/targets
  • ➖ More up-front architectural work and data marshaling
  • ➖ May require adopting/porting more complex kernel code
3. Make build sources explicit instead of GLOB_RECURSE for mixed C++/CUDA
  • ➕ More deterministic builds and clearer review of compiled units
  • ➕ Avoids accidentally compiling incompatible legacy sources
  • ➕ Easier to gate CUDA/OpenCL compilation correctly
  • ➖ Requires ongoing CMake maintenance as files are added/removed

Recommendation: The direction (CPU PBKDF2 with HMAC precompute + GPU batch plumbing) is reasonable for performance milestones, but the current implementation should tighten build gating and integration boundaries. In particular: (1) avoid compiling CUDA/OpenCL sources unless the corresponding language/toolchain is enabled, (2) eliminate device-side malloc/free in the CUDA HMAC path (preallocate fixed buffers or redesign message handling), and (3) reconcile the logging API change with existing modules to prevent link/ODR issues. If those are addressed, the PR’s approach is a good foundation for subsequent full wallet verification and GPU PBKDF2 expansion.

Files changed (43) +1255 / -2045

Enhancement (34) +1076 / -0
engine.hAdd btc::Engine public API (PIMPL) +30/-0

Add btc::Engine public API (PIMPL)

• Defines a minimal Engine interface for initialization and running recovery using wallet/hash inputs, dictionary path, thread count, and GPU enable flag.

include/btc/engine.h

engine.cppImplement Engine skeleton: target loading + simple dict/bruteforce loops +92/-0

Implement Engine skeleton: target loading + simple dict/bruteforce loops

• Adds a basic Engine implementation that extracts bitcoin2john-style targets from a wallet file or hash file, then runs placeholder dictionary and brute-force candidate evaluation using PBKDF2.

src/core/engine.cpp

password_generator.cppAdd simple dictionary loader and brute-force generator +24/-0

Add simple dictionary loader and brute-force generator

• Implements a basic password generator that loads dictionary lines and brute-forces lowercase+digit candidates via callback.

src/core/password_generator.cpp

password_generator.hDeclare PasswordGenerator API +15/-0

Declare PasswordGenerator API

• Defines the dictionary loading and brute-force callback API used by the Engine skeleton.

src/core/password_generator.h

pcfg_generator.cppAdd PCFG generator stub implementation +4/-0

Add PCFG generator stub implementation

• Introduces a placeholder PCFGGenerator with no functional training/usage yet.

src/core/pcfg_generator.cpp

pcfg_generator.hAdd PCFG generator stub header +10/-0

Add PCFG generator stub header

• Declares PCFGGenerator and an inline no-op training method as a future extension point.

src/core/pcfg_generator.h

rules_engine.cppAdd basic word mangling rules +15/-0

Add basic word mangling rules

• Implements a small set of simple transformations (lower/upper/capitalize/reverse) to expand dictionary candidates.

src/core/rules_engine.cpp

rules_engine.hDeclare RulesEngine interface +8/-0

Declare RulesEngine interface

• Declares a static apply() helper returning rule-expanded variants of an input word.

src/core/rules_engine.h

pbkdf2_hmac_sha512.cppImplement PBKDF2-HMAC-SHA512 with HMAC precompute and early-exit +121/-0

Implement PBKDF2-HMAC-SHA512 with HMAC precompute and early-exit

• Adds a custom PBKDF2-HMAC-SHA512 implementation that precomputes HMAC ipad/opad blocks for the password and supports an optional target-prefix compare to exit early on mismatch; includes an OpenSSL delegate fallback for comparison.

src/crypto/pbkdf2_hmac_sha512.cpp

pbkdf2_hmac_sha512.hExpose PBKDF2 API and OpenSSL fallback wrapper +22/-0

Expose PBKDF2 API and OpenSSL fallback wrapper

• Defines the CPU PBKDF2 function signature with optional early-exit prefix parameters and a wrapper for PKCS5_PBKDF2_HMAC compatibility testing.

src/crypto/pbkdf2_hmac_sha512.h

sha512_avx2.cppAdd SHA-512 fallback shim (OpenSSL-backed) +11/-0

Add SHA-512 fallback shim (OpenSSL-backed)

• Introduces a placeholder for future AVX2 SHA-512 acceleration while currently delegating to OpenSSL for correctness.

src/crypto/sha512_avx2.cpp

sha512_avx2.hDeclare SHA-512 fallback function +5/-0

Declare SHA-512 fallback function

• Adds the header for the SHA-512 fallback routine used as a future optimization hook.

src/crypto/sha512_avx2.h

cuda_kernel.cuAdd CUDA test kernel placeholder +7/-0

Add CUDA test kernel placeholder

• Introduces a minimal CUDA kernel used as a stub/smoke-test style placeholder.

src/gpu/cuda_kernel.cu

gpu_engine.cppImplement GPU backend probing and CUDA batch-check scaffolding +157/-0

Implement GPU backend probing and CUDA batch-check scaffolding

• Adds GPUEngine with CUDA/OpenCL device probing (guarded by ENABLE_CUDA/ENABLE_OPENCL) and a CUDA path that marshals candidate blobs and launches pbkdf2_cuda_kernel, returning a matched index if found.

src/gpu/gpu_engine.cpp

gpu_engine.hDeclare GPUEngine interface +22/-0

Declare GPUEngine interface

• Defines initialization, availability check, and batch candidate submission API for GPU-accelerated checking.

src/gpu/gpu_engine.h

opencl_kernel.clAdd OpenCL test kernel placeholder +5/-0

Add OpenCL test kernel placeholder

• Adds a trivial OpenCL kernel stub for future OpenCL-based acceleration work.

src/gpu/opencl_kernel.cl

pbkdf2_cuda.cuAdd CUDA PBKDF2-HMAC-SHA512 kernel with device SHA-512 +253/-0

Add CUDA PBKDF2-HMAC-SHA512 kernel with device SHA-512

• Implements device-side SHA-512, HMAC with precomputed ipad/opad, and a PBKDF2 loop for the first derived-key block per candidate; supports optional prefix comparison and writes a match index via atomicCAS.

src/gpu/pbkdf2_cuda.cu

pbkdf2_cuda.hDeclare CUDA PBKDF2 kernel entrypoint +13/-0

Declare CUDA PBKDF2 kernel entrypoint

• Adds the extern "C" __global__ declaration for pbkdf2_cuda_kernel used by GPUEngine.

src/gpu/pbkdf2_cuda.h

checkpoint.cppAdd checkpoint file read/write helpers +16/-0

Add checkpoint file read/write helpers

• Implements minimal checkpoint persistence utilities for saving/restoring progress state.

src/utils/checkpoint.cpp

checkpoint.hDeclare checkpoint helpers +9/-0

Declare checkpoint helpers

• Defines the checkpoint API used by higher-level recovery orchestration (future use).

src/utils/checkpoint.h

file_utils.cppAdd basic file existence and read helpers +23/-0

Add basic file existence and read helpers

• Implements file_exists, read_lines, and read_file helpers used across engine and wallet parsing stubs.

src/utils/file_utils.cpp

file_utils.hDeclare file utility helpers +11/-0

Declare file utility helpers

• Adds the header for file utility functions used by multiple modules.

src/utils/file_utils.h

io_utils.cppAdd lightweight argv parser for new CLI +23/-0

Add lightweight argv parser for new CLI

• Implements simple flag parsing for wallet/hash/dict/threads/batch/gpu/output options and prints a minimal usage line.

src/utils/io_utils.cpp

io_utils.hDefine io::Options and parse_args +20/-0

Define io::Options and parse_args

• Introduces the Options struct consumed by main and returned by parse_args().

src/utils/io_utils.h

logger.hAdd minimal logger helper declarations +9/-0

Add minimal logger helper declarations

• Declares utils::log_info and utils::log_error used by the new Engine/GPU codepaths.

src/utils/logger.h

thread_pool.cppAdd simple thread pool implementation +47/-0

Add simple thread pool implementation

• Implements a basic worker pool with a task queue and cooperative shutdown semantics.

src/utils/thread_pool.cpp

thread_pool.hDeclare ThreadPool API +22/-0

Declare ThreadPool API

• Defines the ThreadPool interface used by the recovery engine skeleton for parallel work (future expansion).

src/utils/thread_pool.h

armory_wallet.cppAdd Armory wallet parser stub +6/-0

Add Armory wallet parser stub

• Introduces a placeholder Armory parsing function that currently returns false.

src/wallets/armory_wallet.cpp

armory_wallet.hDeclare Armory wallet parser stub +6/-0

Declare Armory wallet parser stub

• Adds the header for parse_armory_file used as a future extension point.

src/wallets/armory_wallet.h

bdb_parser.cppAdd heuristic bitcoin2john line extraction from wallet file +30/-0

Add heuristic bitcoin2john line extraction from wallet file

• Implements a simple scan for "$bitcoin$" markers to extract bitcoin2john-like hash lines from a wallet file blob.

src/wallets/bdb_parser.cpp

bdb_parser.hDefine WalletHashes and wallet parse entrypoints +17/-0

Define WalletHashes and wallet parse entrypoints

• Introduces a minimal result struct and parser declarations for BDB/Bitcoin Core/Electrum/Armory formats (mostly stubbed).

src/wallets/bdb_parser.h

bitcoin_core_wallet.hAdd minimal Bitcoin Core wallet header +7/-0

Add minimal Bitcoin Core wallet header

• Provides a small header exposing the heuristic address extraction function.

src/wallets/bitcoin_core_wallet.h

electrum_wallet.cppAdd naive Electrum wallet detection stub +10/-0

Add naive Electrum wallet detection stub

• Adds a simple parser that checks if a file appears to be JSON and returns true/false accordingly.

src/wallets/electrum_wallet.cpp

electrum_wallet.hDeclare Electrum wallet parser stub +6/-0

Declare Electrum wallet parser stub

• Adds the header for the Electrum parsing stub used by higher-level flows.

src/wallets/electrum_wallet.h

Refactor (3) +32 / -1346
main.cppReplace legacy CLI with minimal argument parsing + Engine invocation +14/-186

Replace legacy CLI with minimal argument parsing + Engine invocation

• Removes the prior rich getopt-based CLI and RecoveryEngine wiring, replacing it with io::parse_args and a call into btc::Engine for a skeleton run.

src/main.cpp

logger.cppReplace Logger class usage with simple utils::log_info/log_error +9/-174

Replace Logger class usage with simple utils::log_info/log_error

• Drops the prior Logger singleton implementation in favor of minimal thread-safe stdout/stderr logging helpers.

src/utils/logger.cpp

bitcoin_core_wallet.cppReplace full Bitcoin Core wallet implementation with heuristic stub +9/-986

Replace full Bitcoin Core wallet implementation with heuristic stub

• Removes the prior full-featured Bitcoin Core wallet handling and replaces it with a minimal heuristic that scans file content for address-like strings.

src/wallets/bitcoin_core_wallet.cpp

Tests (1) +54 / -0
pbkdf2_test.cppAdd PBKDF2 correctness tests vs OpenSSL +54/-0

Add PBKDF2 correctness tests vs OpenSSL

• Adds a small executable that runs several PBKDF2 vectors and compares the custom implementation against OpenSSL's PKCS5_PBKDF2_HMAC output.

tests/pbkdf2_test.cpp

Documentation (1) +1 / -431
README.mdReplace README with milestone/update note +1/-431

Replace README with milestone/update note

• Collapses the previous full project documentation into a short update line referencing PBKDF2 HMAC precomputation and tests.

README.md

Other (4) +92 / -268
CMakeLists.txtSimplify build: single recovery binary + PBKDF2 test target +26/-176

Simplify build: single recovery binary + PBKDF2 test target

• Replaces the prior multi-option build with a simplified executable target, optional CUDA/OpenCL compile definitions, and a standalone pbkdf2_test target wired into CTest.

CMakeLists.txt

CMakeLists.txt.updatedAdd alternate CMake variant with CUDA source property and GPU smoke test +55/-0

Add alternate CMake variant with CUDA source property and GPU smoke test

• Introduces a secondary CMake file showing explicit CUDA language enabling for pbkdf2_cuda.cu and an additional gpu_test target plus CTest registration.

CMakeLists.txt.updated

cluster.yamlReduce cluster config to a minimal example stub +4/-55

Reduce cluster config to a minimal example stub

• Replaces the detailed cluster deployment configuration with a minimal example containing node count/id and coordinator address.

config/cluster.yaml

recovery.yamlSimplify recovery config keys and defaults +7/-37

Simplify recovery config keys and defaults

• Replaces the extensive recovery configuration with a compact example (threads, batch, gpu backend flags, checkpoint/output format).

config/recovery.yaml

…d forward prototypes; update CMake to find OpenCL and build OpenCL/CUDA pipeline
@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (12) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Unconditional CUDA sources 🐞 Bug ☼ Reliability
Description
CMakeLists.txt always adds .cu sources (and src/gpu/cuda_kernel.cu) even when ENABLE_CUDA is
OFF, so default CPU-only builds can fail because the CUDA language/toolchain isn’t enabled.
enable_language(CUDA) is only executed conditionally after the target is already created.
Code

CMakeLists.txt[R17-31]

+file(GLOB_RECURSE SRC_FILES src/*.cpp src/*.c src/*.cu)

-set(UTILS_SOURCES
-    src/utils/crypto_utils.cpp
-    src/utils/file_utils.cpp
-    src/utils/string_utils.cpp
-    src/utils/logger.cpp
-)
+# Main binary
+add_executable(recovery ${SRC_FILES} src/gpu/cuda_kernel.cu)

-set(GPU_SOURCES)
-if(CUDA_FOUND)
-    set(GPU_SOURCES ${GPU_SOURCES}
-        src/gpu/cuda_recovery.cu
-        src/gpu/cuda_utils.cu
-        src/gpu/cuda_integrated.cpp
-    )
-endif()
+target_link_libraries(recovery PRIVATE OpenSSL::SSL OpenSSL::Crypto Threads::Threads)

-if(OpenCL_FOUND)
-    set(GPU_SOURCES ${GPU_SOURCES}
-        src/gpu/opencl_recovery.cpp
-        src/gpu/opencl_utils.cpp
-        src/gpu/integrated_gpu.cpp
-    )
+if(NOT MSVC)
+    target_compile_options(recovery PRIVATE -Wall -Wextra -Wpedantic)
endif()

-# Main executable
-add_executable(btc-recovery
-    src/main.cpp
-    ${CORE_SOURCES}
-    ${WALLET_SOURCES}
-    ${UTILS_SOURCES}
-    ${GPU_SOURCES}
-)
-
-# Link libraries
-target_link_libraries(btc-recovery
-    ${CMAKE_THREAD_LIBS_INIT}
-    ${OPENSSL_LIBRARIES}
-    ${CURL_LIBRARIES}
-    ${JSONCPP_LIBRARIES}
-)
-
-if(CUDA_FOUND)
-    target_link_libraries(btc-recovery ${CUDA_LIBRARIES})
+if(ENABLE_CUDA)
+    enable_language(CUDA)
+    target_compile_definitions(recovery PRIVATE ENABLE_CUDA=1)
endif()
Evidence
The build file includes .cu sources regardless of ENABLE_CUDA, but only enables the CUDA
language when the option is set, creating a CPU build/configure failure.

CMakeLists.txt[17-31]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`recovery` includes CUDA (`.cu`) sources unconditionally, but CUDA is only enabled when `ENABLE_CUDA` is ON. This breaks CPU-only builds.

### Issue Context
- `file(GLOB_RECURSE ...)` includes `src/*.cu` regardless of options.
- `add_executable(recovery ... src/gpu/cuda_kernel.cu)` adds a `.cu` file unconditionally.
- `enable_language(CUDA)` is executed only inside `if(ENABLE_CUDA)` and after target creation.

### Fix Focus Areas
- CMakeLists.txt[17-35]

### Suggested fix
- Move `enable_language(CUDA)` before any `.cu` sources are added.
- Only glob/add `.cu` sources when `ENABLE_CUDA` is ON (or split `SRC_FILES` into CPU vs CUDA lists).
- Only add `src/gpu/cuda_kernel.cu` when CUDA is enabled.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. CUDA header in CPU build 🐞 Bug ☼ Reliability
Description
src/gpu/gpu_engine.cpp includes pbkdf2_cuda.h unconditionally, but that header uses the
CUDA-only __global__ qualifier which will not compile with a normal C++ compiler. This breaks
non-CUDA builds even if no CUDA codepath is executed.
Code

src/gpu/gpu_engine.cpp[R83-90]

+bool gpu::GPUEngine::is_available() const { return p->available; }
+
+#include "src/gpu/pbkdf2_cuda.h"
+
+bool gpu::GPUEngine::check_batch(const std::vector<std::string> &candidates, std::string &out_password) {
+    std::lock_guard<std::mutex> lk(p->m);
+    if (!p->available) return false;
+
Evidence
The include is unconditional, and the included header contains __global__, which is not valid in a
standard C++ compilation unit.

src/gpu/gpu_engine.cpp[83-90]
src/gpu/pbkdf2_cuda.h[1-13]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
A non-CUDA translation unit includes a header containing CUDA-specific syntax (`__global__`). When `ENABLE_CUDA` is OFF, the compiler will still parse the header and fail.

### Issue Context
- `gpu_engine.cpp` includes `src/gpu/pbkdf2_cuda.h` outside `#ifdef ENABLE_CUDA`.
- `pbkdf2_cuda.h` declares a `__global__` kernel.

### Fix Focus Areas
- src/gpu/gpu_engine.cpp[83-90]
- src/gpu/pbkdf2_cuda.h[1-13]

### Suggested fix
- Wrap the include with `#ifdef ENABLE_CUDA` (or make `pbkdf2_cuda.h` itself guard CUDA qualifiers).
- Prefer a CUDA-agnostic host header that declares a normal C++ wrapper function, implemented in a `.cu` file, rather than exposing `__global__` in headers compiled by C++.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Deleting unique_ptr member 🐞 Bug ≡ Correctness
Description
btc::Engine stores its implementation in a std::unique_ptr, but the destructor does delete p;,
which is invalid C++ and prevents compilation. Even if corrected to compile, manual deletion defeats
RAII and risks ownership bugs.
Code

src/core/engine.cpp[R28-30]

+btc::Engine::Engine(): p(new Impl()){}
+btc::Engine::~Engine(){ delete p; }
+
Evidence
The header defines p as a std::unique_ptr, but the implementation tries to delete it directly.

include/btc/engine.h[25-28]
src/core/engine.cpp[28-30]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`btc::Engine` uses `std::unique_ptr<Impl> p`, but the destructor manually deletes `p`.

### Issue Context
`p` is a `std::unique_ptr`, so it should be destroyed automatically; manual `delete` is both incorrect and unnecessary.

### Fix Focus Areas
- include/btc/engine.h[25-28]
- src/core/engine.cpp[28-30]

### Suggested fix
- Replace `btc::Engine::~Engine(){ delete p; }` with `btc::Engine::~Engine() = default;` (or an empty destructor body).
- Do not manually free `p` anywhere else; use `p.reset()` only if you need early release.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (4)
4. Missing vector include 🐞 Bug ≡ Correctness
Description
src/gpu/gpu_engine.h uses std::vector in its public API but does not include <vector>, making
compilation depend on include order and likely failing in files that include it first. This header
is not self-contained.
Code

src/gpu/gpu_engine.h[R1-16]

+#pragma once
+#include <string>
+
+namespace gpu {
+
+class GPUEngine {
+public:
+    GPUEngine();
+    ~GPUEngine();
+
+    bool init(const std::string &backend = "auto");
+    bool is_available() const;
+
+    // Submit a batch of candidates for checking. Returns true if password found and writes to out_password.
+    bool check_batch(const std::vector<std::string> &candidates, std::string &out_password);
+
Evidence
The header includes only <string> but declares a method using std::vector<std::string>.

src/gpu/gpu_engine.h[1-16]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`gpu_engine.h` references `std::vector` but does not include the standard header that defines it.

### Issue Context
Public headers must be self-contained; relying on transitive includes breaks compilation depending on include order.

### Fix Focus Areas
- src/gpu/gpu_engine.h[1-16]

### Suggested fix
- Add `#include <vector>` at the top of `src/gpu/gpu_engine.h`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Missing functional include 🐞 Bug ≡ Correctness
Description
src/core/password_generator.h uses std::function but does not include <functional>, so
translation units including it can fail to compile. engine.cpp includes this header without
including <functional> first.
Code

src/core/password_generator.h[R1-15]

+#pragma once
+#include <string>
+#include <vector>
+
+class PasswordGenerator {
+public:
+    PasswordGenerator();
+    ~PasswordGenerator();
+
+    // stream dictionary words
+    std::vector<std::string> load_dict(const std::string &path);
+
+    // simple brute-force generator (only lowercase and digits for skeleton)
+    void brute_force(int min_len, int max_len, std::function<void(const std::string&)> callback);
+};
Evidence
The header declares std::function without including <functional>, making it non-self-contained.

src/core/password_generator.h[1-15]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`PasswordGenerator::brute_force` takes a `std::function` but the header does not include `<functional>`.

### Issue Context
Headers should include everything needed for their declarations.

### Fix Focus Areas
- src/core/password_generator.h[1-15]

### Suggested fix
- Add `#include <functional>` to `src/core/password_generator.h`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Invalid preprocessor line 🐞 Bug ≡ Correctness
Description
tests/pbkdf2_test.cpp begins with # Simple ..., which is treated as a preprocessor directive and
will not compile. This breaks the pbkdf2_test target and the ctest registration added in CMake.
Code

tests/pbkdf2_test.cpp[R1-2]

+# Simple PBKDF2 test program comparing our implementation to OpenSSL's PKCS5_PBKDF2_HMAC
+#include <iostream>
Evidence
The first line is a raw # ... string, not a valid directive or comment, so compilation fails
immediately.

tests/pbkdf2_test.cpp[1-3]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The test file starts with `# Simple ...`, which is not a valid C++ comment.

### Issue Context
At the start of a line, `#` indicates a preprocessor directive; `# Simple` is invalid.

### Fix Focus Areas
- tests/pbkdf2_test.cpp[1-2]

### Suggested fix
- Replace the first line with `// Simple PBKDF2 test program ...` (or wrap it in `/* ... */`).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Invalid header preprocessor line 🐞 Bug ≡ Correctness
Description
src/wallets/bitcoin_core_wallet.h begins with # Minimal ..., which is treated as a preprocessor
directive and will not compile. Any file including this header will fail to build.
Code

src/wallets/bitcoin_core_wallet.h[R1-2]

+# Minimal bitcoin_core_wallet parser header
+#pragma once
Evidence
The header’s first line uses # as if it were a comment, which is invalid in C/C++.

src/wallets/bitcoin_core_wallet.h[1-3]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The header begins with `# Minimal ...`, which is not valid C++ and breaks preprocessing.

### Issue Context
This is intended to be a comment, but `#` is reserved for preprocessor directives.

### Fix Focus Areas
- src/wallets/bitcoin_core_wallet.h[1-3]

### Suggested fix
- Change the first line to `// Minimal bitcoin_core_wallet parser header`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

8. PBKDF2 missing algorithm include 🐞 Bug ≡ Correctness
Description
pbkdf2_hmac_sha512.cpp uses std::min without including <algorithm>, so compilation may fail
depending on the standard library and include order. This is a portability/build correctness issue.
Code

src/crypto/pbkdf2_hmac_sha512.cpp[R100-103]

+        // copy T to out
+        size_t offset = (i-1) * SHA512_DIGEST_SIZE;
+        size_t copy_len = std::min((size_t)SHA512_DIGEST_SIZE, dkLen - offset);
+        memcpy(out.data() + offset, T.data(), copy_len);
Evidence
The file’s includes do not contain <algorithm>, yet the implementation calls std::min.

src/crypto/pbkdf2_hmac_sha512.cpp[1-6]
src/crypto/pbkdf2_hmac_sha512.cpp[100-104]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`std::min` is used but `<algorithm>` is not included.

### Issue Context
Relying on transitive includes from OpenSSL or other headers is non-portable.

### Fix Focus Areas
- src/crypto/pbkdf2_hmac_sha512.cpp[1-6]
- src/crypto/pbkdf2_hmac_sha512.cpp[100-104]

### Suggested fix
- Add `#include <algorithm>` to `src/crypto/pbkdf2_hmac_sha512.cpp`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


9. ThreadPool missing algorithm include 🐞 Bug ≡ Correctness
Description
thread_pool.cpp uses std::max but does not include <algorithm>, making compilation depend on
transitive includes. This can break builds when headers change or across toolchains.
Code

src/utils/thread_pool.cpp[R16-18]

+    Impl(size_t n) {
+        if (n == 0) n = std::max<size_t>(1, std::thread::hardware_concurrency());
+        for (size_t i = 0; i < n; ++i) {
Evidence
The file uses std::max but its include list does not provide <algorithm>.

src/utils/thread_pool.cpp[1-8]
src/utils/thread_pool.cpp[16-19]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`std::max` is used without including `<algorithm>`.

### Issue Context
This is a new translation unit; it should include all required standard headers explicitly.

### Fix Focus Areas
- src/utils/thread_pool.cpp[1-8]
- src/utils/thread_pool.cpp[16-19]

### Suggested fix
- Add `#include <algorithm>` near the top of `src/utils/thread_pool.cpp`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


10. PBKDF2 prefix check incomplete 🐞 Bug ≡ Correctness
Description
pbkdf2_hmac_sha512 only compares target_prefix against the first derived block (i == 1), and
if the prefix spans additional blocks it never compares the remaining bytes. This can return true
even when later prefix bytes don’t match.
Code

src/crypto/pbkdf2_hmac_sha512.cpp[R105-117]

+        // Early-exit optimization: if caller provided a target prefix to compare and that prefix
+        // lies within the first block produced (i==1), compare only that prefix_len bytes and
+        // return quickly if mismatch. This avoids computing further blocks when the prefix doesn't match.
+        if (target_prefix && target_prefix_len > 0 && i == 1) {
+            size_t cmp = std::min(copy_len, target_prefix_len);
+            if (memcmp(out.data(), target_prefix, cmp) != 0) {
+                return false; // early exit: prefix mismatch
+            }
+            // if target_prefix_len > copy_len we cannot decide yet; continue
+            if (target_prefix_len <= copy_len) {
+                // prefix matches; if the caller only wanted to check prefix they can inspect out.
+            }
+        }
Evidence
The comparison is gated by i == 1, and there is no subsequent comparison for i > 1 even though
the code explicitly notes the undecidable case.

src/crypto/pbkdf2_hmac_sha512.cpp[105-117]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The optional `target_prefix` early-exit logic compares only bytes available in block 1, and does not validate the remaining prefix bytes when `target_prefix_len` extends beyond the first block.

### Issue Context
The comment states “cannot decide yet; continue”, but no later block comparison exists.

### Fix Focus Areas
- src/crypto/pbkdf2_hmac_sha512.cpp[105-117]

### Suggested fix
- Track how many prefix bytes have been verified.
- After each block copy into `out`, compare the newly-produced segment against the corresponding segment of `target_prefix` (up to `target_prefix_len`) and return false on mismatch.
- Alternatively, if the intent is “only compare up to first block”, enforce/validate `target_prefix_len <= 64` and document it.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (2)
11. CUDA kernel heap allocation 🐞 Bug ➹ Performance
Description
The CUDA PBKDF2 implementation performs device-side malloc/free inside hmac_sha512_precomp,
which runs in the hot PBKDF2 loop. This can drastically reduce throughput and may fail under
device-heap pressure depending on GPU/device heap configuration.
Code

src/gpu/pbkdf2_cuda.cu[R142-166]

+// HMAC-SHA512 using ipad/opad precomputed blocks (128 bytes each)
+__device__ void hmac_sha512_precomp(const unsigned char ipad[128], const unsigned char opad[128],
+                                    const unsigned char *data, size_t data_len, unsigned char out[64]) {
+    unsigned char tmp[64];
+    // Inner
+    // Build inner message = ipad || data
+    // We will process with sha512 by allocating buffer of (128 + data_len)
+    // For small data lengths avoid dynamic alloc: use stack when possible
+    // For simplicity, we'll create a small buffer for data <= (1<<20) which is fine for our salt sizes
+    // Create concatenated buffer
+    unsigned char *inner_buf = (unsigned char*)malloc(128 + data_len);
+    if (!inner_buf) { // out with zeros
+        for (int i=0;i<64;++i) out[i]=0; return;
+    }
+    memcpy(inner_buf, ipad, 128);
+    if (data && data_len) memcpy(inner_buf + 128, data, data_len);
+    sha512(inner_buf, 128 + data_len, tmp);
+    free(inner_buf);
+
+    // Outer: opad || tmp
+    unsigned char outer_buf[128 + 64];
+    memcpy(outer_buf, opad, 128);
+    memcpy(outer_buf + 128, tmp, 64);
+    sha512(outer_buf, 128 + 64, out);
+}
Evidence
The device function explicitly calls malloc/free to build ipad || data, and this function is
used inside the per-thread PBKDF2 implementation.

src/gpu/pbkdf2_cuda.cu[142-166]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`hmac_sha512_precomp` allocates a buffer (`malloc(128 + data_len)`) and frees it for every HMAC call. PBKDF2 calls HMAC once for U1 and once per iteration, so this adds repeated allocations per candidate.

### Issue Context
PBKDF2 uses fixed-size inputs here (ipad/opad are 128 bytes; salt/U are small), so the allocation is avoidable.

### Fix Focus Areas
- src/gpu/pbkdf2_cuda.cu[142-166]

### Suggested fix
- Replace heap allocation with a fixed-size local buffer sized for the maximum expected `data_len` (e.g., handle salt_len up to a bounded maximum).
- Or rework `sha512()` to accept two segments (ipad + data) without concatenation.
- If heap allocation remains, document and configure the device heap size explicitly and handle allocation failure in a way that cannot create false matches.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


12. CUDA salt buffer overflow 🐞 Bug ⛨ Security
Description
pbkdf2_cuda_kernel copies salt_len bytes into a fixed salt_block[256] without bounds checking,
so a large salt can overflow the buffer and corrupt memory. This is a correctness/safety bug in the
GPU implementation.
Code

src/gpu/pbkdf2_cuda.cu[R206-212]

+    // Prepare salt || INT(1)
+    unsigned char salt_block[256];
+    int sb_len = 0;
+    if (salt_len > 0) { memcpy(salt_block, salt, salt_len); sb_len += salt_len; }
+    // INT(1) big-endian
+    salt_block[sb_len+0] = 0x00; salt_block[sb_len+1] = 0x00; salt_block[sb_len+2] = 0x00; salt_block[sb_len+3] = 0x01;
+    sb_len += 4;
Evidence
The kernel uses a fixed-size stack buffer but copies salt_len bytes into it without checking
capacity, then appends 4 bytes.

src/gpu/pbkdf2_cuda.cu[206-213]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`salt_block` is a fixed 256-byte array, but the kernel does `memcpy(salt_block, salt, salt_len)` without checking that `salt_len` fits.

### Issue Context
The kernel then appends 4 bytes for `INT(1)`, so the maximum safe `salt_len` is 252.

### Fix Focus Areas
- src/gpu/pbkdf2_cuda.cu[206-213]

### Suggested fix
- Add an explicit guard: if `salt_len < 0` or `salt_len > 252`, return early (no match) or clamp safely.
- Consider making `salt_block` sized based on the maximum supported salt length and document that limit in the host-side API.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment thread CMakeLists.txt
Comment on lines +17 to 31
file(GLOB_RECURSE SRC_FILES src/*.cpp src/*.c src/*.cu)

set(UTILS_SOURCES
src/utils/crypto_utils.cpp
src/utils/file_utils.cpp
src/utils/string_utils.cpp
src/utils/logger.cpp
)
# Main binary
add_executable(recovery ${SRC_FILES} src/gpu/cuda_kernel.cu)

set(GPU_SOURCES)
if(CUDA_FOUND)
set(GPU_SOURCES ${GPU_SOURCES}
src/gpu/cuda_recovery.cu
src/gpu/cuda_utils.cu
src/gpu/cuda_integrated.cpp
)
endif()
target_link_libraries(recovery PRIVATE OpenSSL::SSL OpenSSL::Crypto Threads::Threads)

if(OpenCL_FOUND)
set(GPU_SOURCES ${GPU_SOURCES}
src/gpu/opencl_recovery.cpp
src/gpu/opencl_utils.cpp
src/gpu/integrated_gpu.cpp
)
if(NOT MSVC)
target_compile_options(recovery PRIVATE -Wall -Wextra -Wpedantic)
endif()

# Main executable
add_executable(btc-recovery
src/main.cpp
${CORE_SOURCES}
${WALLET_SOURCES}
${UTILS_SOURCES}
${GPU_SOURCES}
)

# Link libraries
target_link_libraries(btc-recovery
${CMAKE_THREAD_LIBS_INIT}
${OPENSSL_LIBRARIES}
${CURL_LIBRARIES}
${JSONCPP_LIBRARIES}
)

if(CUDA_FOUND)
target_link_libraries(btc-recovery ${CUDA_LIBRARIES})
if(ENABLE_CUDA)
enable_language(CUDA)
target_compile_definitions(recovery PRIVATE ENABLE_CUDA=1)
endif()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. Unconditional cuda sources 🐞 Bug ☼ Reliability

CMakeLists.txt always adds .cu sources (and src/gpu/cuda_kernel.cu) even when ENABLE_CUDA is
OFF, so default CPU-only builds can fail because the CUDA language/toolchain isn’t enabled.
enable_language(CUDA) is only executed conditionally after the target is already created.
Agent Prompt
### Issue description
`recovery` includes CUDA (`.cu`) sources unconditionally, but CUDA is only enabled when `ENABLE_CUDA` is ON. This breaks CPU-only builds.

### Issue Context
- `file(GLOB_RECURSE ...)` includes `src/*.cu` regardless of options.
- `add_executable(recovery ... src/gpu/cuda_kernel.cu)` adds a `.cu` file unconditionally.
- `enable_language(CUDA)` is executed only inside `if(ENABLE_CUDA)` and after target creation.

### Fix Focus Areas
- CMakeLists.txt[17-35]

### Suggested fix
- Move `enable_language(CUDA)` before any `.cu` sources are added.
- Only glob/add `.cu` sources when `ENABLE_CUDA` is ON (or split `SRC_FILES` into CPU vs CUDA lists).
- Only add `src/gpu/cuda_kernel.cu` when CUDA is enabled.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread src/gpu/gpu_engine.cpp
Comment on lines +83 to +90
bool gpu::GPUEngine::is_available() const { return p->available; }

#include "src/gpu/pbkdf2_cuda.h"

bool gpu::GPUEngine::check_batch(const std::vector<std::string> &candidates, std::string &out_password) {
std::lock_guard<std::mutex> lk(p->m);
if (!p->available) return false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

2. Cuda header in cpu build 🐞 Bug ☼ Reliability

src/gpu/gpu_engine.cpp includes pbkdf2_cuda.h unconditionally, but that header uses the
CUDA-only __global__ qualifier which will not compile with a normal C++ compiler. This breaks
non-CUDA builds even if no CUDA codepath is executed.
Agent Prompt
### Issue description
A non-CUDA translation unit includes a header containing CUDA-specific syntax (`__global__`). When `ENABLE_CUDA` is OFF, the compiler will still parse the header and fail.

### Issue Context
- `gpu_engine.cpp` includes `src/gpu/pbkdf2_cuda.h` outside `#ifdef ENABLE_CUDA`.
- `pbkdf2_cuda.h` declares a `__global__` kernel.

### Fix Focus Areas
- src/gpu/gpu_engine.cpp[83-90]
- src/gpu/pbkdf2_cuda.h[1-13]

### Suggested fix
- Wrap the include with `#ifdef ENABLE_CUDA` (or make `pbkdf2_cuda.h` itself guard CUDA qualifiers).
- Prefer a CUDA-agnostic host header that declares a normal C++ wrapper function, implemented in a `.cu` file, rather than exposing `__global__` in headers compiled by C++.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread src/core/engine.cpp
Comment on lines +28 to +30
btc::Engine::Engine(): p(new Impl()){}
btc::Engine::~Engine(){ delete p; }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

3. Deleting unique_ptr member 🐞 Bug ≡ Correctness

btc::Engine stores its implementation in a std::unique_ptr, but the destructor does delete p;,
which is invalid C++ and prevents compilation. Even if corrected to compile, manual deletion defeats
RAII and risks ownership bugs.
Agent Prompt
### Issue description
`btc::Engine` uses `std::unique_ptr<Impl> p`, but the destructor manually deletes `p`.

### Issue Context
`p` is a `std::unique_ptr`, so it should be destroyed automatically; manual `delete` is both incorrect and unnecessary.

### Fix Focus Areas
- include/btc/engine.h[25-28]
- src/core/engine.cpp[28-30]

### Suggested fix
- Replace `btc::Engine::~Engine(){ delete p; }` with `btc::Engine::~Engine() = default;` (or an empty destructor body).
- Do not manually free `p` anywhere else; use `p.reset()` only if you need early release.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread src/gpu/gpu_engine.h
Comment on lines +1 to +16
#pragma once
#include <string>

namespace gpu {

class GPUEngine {
public:
GPUEngine();
~GPUEngine();

bool init(const std::string &backend = "auto");
bool is_available() const;

// Submit a batch of candidates for checking. Returns true if password found and writes to out_password.
bool check_batch(const std::vector<std::string> &candidates, std::string &out_password);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

4. Missing vector include 🐞 Bug ≡ Correctness

src/gpu/gpu_engine.h uses std::vector in its public API but does not include <vector>, making
compilation depend on include order and likely failing in files that include it first. This header
is not self-contained.
Agent Prompt
### Issue description
`gpu_engine.h` references `std::vector` but does not include the standard header that defines it.

### Issue Context
Public headers must be self-contained; relying on transitive includes breaks compilation depending on include order.

### Fix Focus Areas
- src/gpu/gpu_engine.h[1-16]

### Suggested fix
- Add `#include <vector>` at the top of `src/gpu/gpu_engine.h`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +1 to +15
#pragma once
#include <string>
#include <vector>

class PasswordGenerator {
public:
PasswordGenerator();
~PasswordGenerator();

// stream dictionary words
std::vector<std::string> load_dict(const std::string &path);

// simple brute-force generator (only lowercase and digits for skeleton)
void brute_force(int min_len, int max_len, std::function<void(const std::string&)> callback);
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

5. Missing functional include 🐞 Bug ≡ Correctness

src/core/password_generator.h uses std::function but does not include <functional>, so
translation units including it can fail to compile. engine.cpp includes this header without
including <functional> first.
Agent Prompt
### Issue description
`PasswordGenerator::brute_force` takes a `std::function` but the header does not include `<functional>`.

### Issue Context
Headers should include everything needed for their declarations.

### Fix Focus Areas
- src/core/password_generator.h[1-15]

### Suggested fix
- Add `#include <functional>` to `src/core/password_generator.h`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +100 to +103
// copy T to out
size_t offset = (i-1) * SHA512_DIGEST_SIZE;
size_t copy_len = std::min((size_t)SHA512_DIGEST_SIZE, dkLen - offset);
memcpy(out.data() + offset, T.data(), copy_len);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

8. Pbkdf2 missing algorithm include 🐞 Bug ≡ Correctness

pbkdf2_hmac_sha512.cpp uses std::min without including <algorithm>, so compilation may fail
depending on the standard library and include order. This is a portability/build correctness issue.
Agent Prompt
### Issue description
`std::min` is used but `<algorithm>` is not included.

### Issue Context
Relying on transitive includes from OpenSSL or other headers is non-portable.

### Fix Focus Areas
- src/crypto/pbkdf2_hmac_sha512.cpp[1-6]
- src/crypto/pbkdf2_hmac_sha512.cpp[100-104]

### Suggested fix
- Add `#include <algorithm>` to `src/crypto/pbkdf2_hmac_sha512.cpp`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread src/utils/thread_pool.cpp
Comment on lines +16 to +18
Impl(size_t n) {
if (n == 0) n = std::max<size_t>(1, std::thread::hardware_concurrency());
for (size_t i = 0; i < n; ++i) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

9. Threadpool missing algorithm include 🐞 Bug ≡ Correctness

thread_pool.cpp uses std::max but does not include <algorithm>, making compilation depend on
transitive includes. This can break builds when headers change or across toolchains.
Agent Prompt
### Issue description
`std::max` is used without including `<algorithm>`.

### Issue Context
This is a new translation unit; it should include all required standard headers explicitly.

### Fix Focus Areas
- src/utils/thread_pool.cpp[1-8]
- src/utils/thread_pool.cpp[16-19]

### Suggested fix
- Add `#include <algorithm>` near the top of `src/utils/thread_pool.cpp`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +105 to +117
// Early-exit optimization: if caller provided a target prefix to compare and that prefix
// lies within the first block produced (i==1), compare only that prefix_len bytes and
// return quickly if mismatch. This avoids computing further blocks when the prefix doesn't match.
if (target_prefix && target_prefix_len > 0 && i == 1) {
size_t cmp = std::min(copy_len, target_prefix_len);
if (memcmp(out.data(), target_prefix, cmp) != 0) {
return false; // early exit: prefix mismatch
}
// if target_prefix_len > copy_len we cannot decide yet; continue
if (target_prefix_len <= copy_len) {
// prefix matches; if the caller only wanted to check prefix they can inspect out.
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

10. Pbkdf2 prefix check incomplete 🐞 Bug ≡ Correctness

pbkdf2_hmac_sha512 only compares target_prefix against the first derived block (i == 1), and
if the prefix spans additional blocks it never compares the remaining bytes. This can return true
even when later prefix bytes don’t match.
Agent Prompt
### Issue description
The optional `target_prefix` early-exit logic compares only bytes available in block 1, and does not validate the remaining prefix bytes when `target_prefix_len` extends beyond the first block.

### Issue Context
The comment states “cannot decide yet; continue”, but no later block comparison exists.

### Fix Focus Areas
- src/crypto/pbkdf2_hmac_sha512.cpp[105-117]

### Suggested fix
- Track how many prefix bytes have been verified.
- After each block copy into `out`, compare the newly-produced segment against the corresponding segment of `target_prefix` (up to `target_prefix_len`) and return false on mismatch.
- Alternatively, if the intent is “only compare up to first block”, enforce/validate `target_prefix_len <= 64` and document it.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread src/gpu/pbkdf2_cuda.cu
Comment on lines +142 to +166
// HMAC-SHA512 using ipad/opad precomputed blocks (128 bytes each)
__device__ void hmac_sha512_precomp(const unsigned char ipad[128], const unsigned char opad[128],
const unsigned char *data, size_t data_len, unsigned char out[64]) {
unsigned char tmp[64];
// Inner
// Build inner message = ipad || data
// We will process with sha512 by allocating buffer of (128 + data_len)
// For small data lengths avoid dynamic alloc: use stack when possible
// For simplicity, we'll create a small buffer for data <= (1<<20) which is fine for our salt sizes
// Create concatenated buffer
unsigned char *inner_buf = (unsigned char*)malloc(128 + data_len);
if (!inner_buf) { // out with zeros
for (int i=0;i<64;++i) out[i]=0; return;
}
memcpy(inner_buf, ipad, 128);
if (data && data_len) memcpy(inner_buf + 128, data, data_len);
sha512(inner_buf, 128 + data_len, tmp);
free(inner_buf);

// Outer: opad || tmp
unsigned char outer_buf[128 + 64];
memcpy(outer_buf, opad, 128);
memcpy(outer_buf + 128, tmp, 64);
sha512(outer_buf, 128 + 64, out);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

11. Cuda kernel heap allocation 🐞 Bug ➹ Performance

The CUDA PBKDF2 implementation performs device-side malloc/free inside hmac_sha512_precomp,
which runs in the hot PBKDF2 loop. This can drastically reduce throughput and may fail under
device-heap pressure depending on GPU/device heap configuration.
Agent Prompt
### Issue description
`hmac_sha512_precomp` allocates a buffer (`malloc(128 + data_len)`) and frees it for every HMAC call. PBKDF2 calls HMAC once for U1 and once per iteration, so this adds repeated allocations per candidate.

### Issue Context
PBKDF2 uses fixed-size inputs here (ipad/opad are 128 bytes; salt/U are small), so the allocation is avoidable.

### Fix Focus Areas
- src/gpu/pbkdf2_cuda.cu[142-166]

### Suggested fix
- Replace heap allocation with a fixed-size local buffer sized for the maximum expected `data_len` (e.g., handle salt_len up to a bounded maximum).
- Or rework `sha512()` to accept two segments (ipad + data) without concatenation.
- If heap allocation remains, document and configure the device heap size explicitly and handle allocation failure in a way that cannot create false matches.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread src/gpu/pbkdf2_cuda.cu
Comment on lines +206 to +212
// Prepare salt || INT(1)
unsigned char salt_block[256];
int sb_len = 0;
if (salt_len > 0) { memcpy(salt_block, salt, salt_len); sb_len += salt_len; }
// INT(1) big-endian
salt_block[sb_len+0] = 0x00; salt_block[sb_len+1] = 0x00; salt_block[sb_len+2] = 0x00; salt_block[sb_len+3] = 0x01;
sb_len += 4;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

12. Cuda salt buffer overflow 🐞 Bug ⛨ Security

pbkdf2_cuda_kernel copies salt_len bytes into a fixed salt_block[256] without bounds checking,
so a large salt can overflow the buffer and corrupt memory. This is a correctness/safety bug in the
GPU implementation.
Agent Prompt
### Issue description
`salt_block` is a fixed 256-byte array, but the kernel does `memcpy(salt_block, salt, salt_len)` without checking that `salt_len` fits.

### Issue Context
The kernel then appends 4 bytes for `INT(1)`, so the maximum safe `salt_len` is 252.

### Fix Focus Areas
- src/gpu/pbkdf2_cuda.cu[206-213]

### Suggested fix
- Add an explicit guard: if `salt_len < 0` or `salt_len > 252`, return early (no match) or clamp safely.
- Consider making `salt_block` sized based on the maximum supported salt length and document that limit in the host-side API.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

…ture detection (AVX2/AVX-512) and integrate dispatcher into PBKDF2 HMAC path. AVX implementations are TODO but the dispatch and integration are in place.
…CL kernel with full SHA-512+HMAC PBKDF2 first-block implementation for correctness; add headers
…benchmark; update CMake additions for AVX2 target and benchmark
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant