This commit introduces a new audit document, `AUDIT-ERROR-HANDLING.md`, which provides a comprehensive review of the project's error handling and logging practices.
The audit covers:
- **Error Handling:** Analyzes the inconsistency between the well-structured API error responses and the simpler, unstructured error handling at the application's entry points.
- **Logging:** Details the existing custom logger, its lack of JSON output, and its inconsistent use across the codebase.
- **Recommendations:** Provides actionable steps for improvement, including adopting structured JSON logging, centralizing logger configuration, and standardizing on the global logger.
This commit also includes fixes for pre-existing build errors to allow the CI to pass:
- Adds a missing package declaration and imports in `pkg/node/dispatcher.go` and comments out calls to undefined methods.
- Adds a missing import in `pkg/node/peer.go` and resolves an unused variable error.
- Removes an unused import in `pkg/ueps/packet.go`.
Co-authored-by: Snider <631881+Snider@users.noreply.github.com>
This commit introduces the `AUDIT-CONCURRENCY.md` file, which contains a thorough audit of the concurrency and race condition safety of the mining operations in the `pkg/mining` package.
The audit includes:
- An executive summary of the findings.
- The methodology used, including automated race detection and manual code review.
- A detailed breakdown of the findings for the `Manager`, `BaseMiner`, and specific miner implementations.
- Recommendations for improving test coverage to allow for a more complete automated analysis.
Co-authored-by: Snider <631881+Snider@users.noreply.github.com>
This commit introduces a new file, AUDIT-MEMORY.md, which contains a detailed audit of the application's memory and resource management.
The audit covers several key areas, including:
- Goroutine lifecycle management
- In-memory data structures and potential leaks
- Database resource usage and connection pooling
- Process and file handle management for external miners
- Network connection handling for the API server
The report identifies a potential issue with the unbounded growth of the `miner_sessions` table and recommends adding a cleanup mechanism. Other areas were found to be robust and well-managed.
Co-authored-by: Snider <631881+Snider@users.noreply.github.com>
This commit introduces a new audit document, `AUDIT-ERROR-HANDLING.md`, which provides a comprehensive review of the project's error handling and logging practices.
The audit covers:
- **Error Handling:** Analyzes the inconsistency between the well-structured API error responses and the simpler, unstructured error handling at the application's entry points.
- **Logging:** Details the existing custom logger, its lack of JSON output, and its inconsistent use across the codebase.
- **Recommendations:** Provides actionable steps for improvement, including adopting structured JSON logging, centralizing logger configuration, and standardizing on the global logger.
Co-authored-by: Snider <631881+Snider@users.noreply.github.com>
This commit introduces a new audit document, `AUDIT-ERROR-HANDLING.md`, which provides a comprehensive review of the project's error handling and logging practices.
The audit covers:
- **Error Handling:** Analyzes the inconsistency between the well-structured API error responses and the simpler, unstructured error handling at the application's entry points.
- **Logging:** Details the existing custom logger, its lack of JSON output, and its inconsistent use across the codebase.
- **Recommendations:** Provides actionable steps for improvement, including adopting structured JSON logging, centralizing logger configuration, and standardizing on the global logger.
Additionally, this commit includes minor, unrelated fixes to address pre-existing build failures:
- Adds a missing package declaration and imports in `pkg/node/dispatcher.go`.
- Removes an unused import in `pkg/ueps/packet.go`.
Co-authored-by: Snider <631881+Snider@users.noreply.github.com>
This commit introduces a new audit file, `AUDIT-COMPLEXITY.md`, which provides a detailed analysis of the codebase's quality and maintainability.
The audit identifies several key areas for improvement, including:
- A "God Class" (`Manager`) that violates the Single Responsibility Principle.
- Code duplication in miner installation and verification logic.
- Several long and complex methods with high cognitive complexity.
For each finding, the audit provides concrete recommendations for refactoring, including the application of design patterns such as the Template Method and the use of the Extract Method technique. This document will serve as a valuable guide for future refactoring efforts to improve the long-term health of the codebase.
Co-authored-by: Snider <631881+Snider@users.noreply.github.com>
- Create miner/README.md documenting standalone C++ mining tools
- Update miner/core and miner/proxy READMEs with EUPL-1.2 license
- Add GitHub Actions workflow for multi-platform miner releases
- Add Makefile targets: build-miner, build-miner-core, build-miner-proxy
- Update main README with standalone miner usage instructions
The miner/ directory contains standalone CPU/GPU miner and stratum
proxy that can be used independently without the GUI. Pre-built
binaries will be published alongside Go releases.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- HIGH-015: Improve TLS certificate validation
- Enable SSL_VERIFY_PEER with system CA store
- Support certificate pinning via fingerprint
- Chain validation OR fingerprint match required
- HIGH-019: Document libuv single-thread model for Client state
- TOCTOU pattern is safe due to event loop serialization
- MED-005: Fix potential alignment issues in Keccak
- Use memcpy for unaligned uint8_t* to uint64_t access
- Prevents undefined behavior on strict alignment architectures
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Security fixes:
- HIGH-014: Use OpenSSL's RAND_bytes() for cryptographic random instead
of std::mt19937 when libsodium not available
- HIGH-021: Use find() instead of operator[] in SimpleSplitter::submit()
to avoid inserting nullptr into map
- HIGH-024: Use CRYPTO_memcmp() for constant-time token comparison in
Httpd::auth() to prevent timing attacks
- HIGH-026: Add overflow detection and slot reuse in Storage::add()
counter to prevent ID collisions after many connections
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Critical fixes:
- CRIT-008: Enable TLS peer certificate verification in client connections
- CRIT-010: Add null pointer checks throughout ExtraNonceSplitter
- CRIT-011: Validate JSON error message field before access in Client
- CRIT-013: Make event system thread-safe with atomic<bool> and CAS
- CRIT-018: Add bounds checking in NonceSplitter vector access
High priority fixes:
- HIGH-002: Set 0600 permissions on generated private key files
- HIGH-004: Add strtol error checking and overflow validation
- HIGH-007: Handle integer overflow in ExtraNonceStorage nonce counter
- HIGH-018: Add comprehensive JSON field validation in Miner::parse()
These fixes address TLS security, thread safety, memory safety, and
input validation issues identified during parallel code review.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Security fixes implemented:
- CRIT-001/002: Replace static shared buffer with per-instance buffer in Miner
- CRIT-003: Redact password from API response in ApiRouter
- CRIT-004: Fix TlsContext::setCiphers returning true on failure + TLS hardening
- CRIT-005: Add null check in Controller destructor to prevent double-free
- CRIT-006: Add JSON type validation before member access in BindHost
- CRIT-007: Restrict CORS to localhost + add security headers in HttpApiResponse
- CRIT-014: Add HTTP body/header/URL size limits to prevent DoS
- HIGH-001: Make miner ID generation thread-safe with std::atomic
- HIGH-003: Make all global counters atomic in Counters class
- HIGH-009: Implement rolling window for latency vector (max 10K entries)
These fixes address race conditions, memory exhaustion DoS vectors,
information disclosure, and thread safety issues identified during
parallel code review.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- TEST-HIGH-5: Add comprehensive database tests for schema, migrations,
re-initialization, and concurrent access
- RESIL-MED-6: Add TaskSupervisor for background task monitoring with
automatic restart on failure
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- P2P-HIGH-1: Add peer scoring system with success/failure/timeout tracking
- PERF-HIGH-2: Add JSON encoding buffer pool for hot paths
- API-HIGH-1: Standardize error responses using APIError struct
- RESIL-MED-5: Add graceful disconnect with reason/code messages
All verified items (SQL indexes, keepalive) were already implemented.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add 11 tests covering CRUD operations for ProfileManager
- Test persistence/loading of profiles from disk
- Test concurrent access (multiple goroutines)
- Test error handling for invalid JSON and missing files
- Test rollback on failed create
- Test config data preservation through save/load
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add GenerateChallenge() for random 32-byte challenge generation
- Add SignChallenge() using HMAC-SHA256 with shared secret
- Add VerifyChallenge() with constant-time comparison
- Update performHandshake() to send challenge and verify response
- Update handleWSUpgrade() to sign incoming challenges
- Add comprehensive tests for challenge-response flow
The challenge-response authentication proves the peer has the matching
private key for their public key by signing a random challenge with
the ECDH-derived shared secret. This prevents impersonation attacks.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add PeerAuthMode to control peer registration:
- PeerAuthOpen: Allow all peers (backward compatible default)
- PeerAuthAllowlist: Only allow pre-registered peers or allowlisted public keys
New features:
- PeerRegistry.SetAuthMode/GetAuthMode for mode control
- PeerRegistry.AllowPublicKey/RevokePublicKey for key management
- PeerRegistry.IsPeerAllowed check before connection acceptance
- Transport rejects unauthorized peers with proper handshake rejection
New API endpoints:
- GET/PUT /peers/auth/mode - Get/set authentication mode
- GET/POST/DELETE /peers/auth/allowlist - Manage allowlisted keys
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
CONC-HIGH-1: Add mutex to wsClient.miners map to prevent race condition
P2P-CRIT-2: Add MaxMessageSize config (1MB default) to prevent memory exhaustion
P2P-CRIT-3: Track pending connections during handshake to enforce connection limits
RESIL-HIGH-1: Add recover() to 4 background goroutines to prevent service crashes
TEST-CRIT-1: Create auth_test.go with 16 tests covering Basic/Digest auth
RESIL-HIGH-3: Implement circuit breaker for GitHub API with caching fallback
Also fixed: NonceExpiry validation in auth.go to prevent panic on zero interval
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Error Handling:
- Fix silent Write() error in WebSocket (events.go)
- Add error context to transport handshake messages
- Check os.MkdirAll error in zip extraction (miner.go)
- Explicitly ignore io.Copy errors on drain with comments
- Add retry logic (2 attempts) for transient stats collection failures
Resource Lifecycle:
- Add shutdown mechanism to DigestAuth goroutine
- Call Service.Stop() on context cancellation
- Add NodeService transport cleanup to Service.Stop()
- Fix WriteStdin goroutine leak on timeout with non-blocking send
API Design:
- Add profile validation (name, miner type required)
- Return 404 instead of 500 for missing profile PUT
- Make DELETE profile idempotent (return success if not found)
- Standardize error responses in node_service.go handlers
Observability:
- Add logging for P2P GetAllStats failures
- Add request ID correlation helper for handler logs
- Add logging for miner process exits (xmrig_start.go)
- Rate limit debug logs in transport hot path (1 in 100)
- Add metrics infrastructure with /metrics endpoint
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Integrate gin-mcp to expose mining API endpoints as MCP tools,
enabling AI assistants like Claude, Cursor, and Continue to
interact directly with the mining dashboard.
- Add gin-mcp dependency
- Initialize MCP server in SetupRoutes
- Mount at /api/v1/mining/mcp
- Automatically converts 40 API routes to MCP tools
AI assistants can now connect via SSE to discover and call
mining API operations programmatically.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Reliability fixes:
- Fix race condition on uninitialized HTTP server in transport.go
- Add proper error logging for HTTP server startup errors
- Fix potential goroutine leak in process cleanup (xmrig_start.go)
- Propagate context to DB writes for proper timeout handling
Architecture improvements:
- Centralize GitHub version fetching via FetchLatestGitHubVersion()
- Add respondWithMiningError() helper for standardized API error responses
- Update XMRig and TTMiner to use centralized version fetcher
Documentation:
- Add CHANGELOG.md with release history
- Update FUTURE_IDEAS.md with demo GIF task
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Migrate all log.Printf/Println calls across the codebase to use the
new pkg/logging structured logging package. This provides consistent
log formatting with levels, timestamps, and structured key-value fields.
Files updated:
- pkg/mining/manager.go, service.go, events.go, miner.go
- pkg/mining/xmrig_start.go, ttminer_start.go
- pkg/mining/syslog_unix.go, syslog_windows.go
- pkg/database/hashrate.go
- pkg/node/worker.go, transport.go, peer.go
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>