Commit graph

154 commits

Author SHA1 Message Date
google-labs-jules[bot]
c0775d9d8b Implement STIM bundle decryption and installation
- Updated `Worker.handleDeploy` to handle STIM bundles using `ExtractProfileBundle` and `ExtractMinerBundle`.
- Used `PeerConnection.SharedSecret` as the password for decryption.
- Implemented logic for `BundleProfile`, `BundleMiner`, and `BundleFull`.
- Fixed broken files `pkg/node/dispatcher.go` and `pkg/node/peer.go` to ensure compilation and testing.
- Updated tests in `pkg/node/worker_test.go` and added coverage for deployment logic.
2026-01-06 21:58:30 +00:00
9f1ec97a60
Add DispatchUEPS function for packet processing
Implement the DispatchUEPS function to handle various packet intents and apply threat score checks.
2026-01-03 16:03:40 +00:00
775c35c772
Implement ReadAndVerify function for UEPS frames 2026-01-03 16:01:58 +00:00
dbd36374b2
Add SendEthicalPacket method for secure packet sending
Implemented SendEthicalPacket method to send packets securely using a shared secret.
2026-01-03 16:00:41 +00:00
6ffcb353c0
Implement UEPS packet structure and signing 2026-01-03 15:59:33 +00:00
snider
d4e131b1a3 feat: Enhance testing framework with C++ test builds and GitHub Actions integration 2026-01-02 18:05:56 +00:00
snider
c3837d118c feat: Add comprehensive testing framework and initial test cases for core components 2026-01-02 17:53:49 +00:00
snider
919b17ee9e fix: Address multiple security issues and add unit tests for various components 2026-01-02 17:39:53 +00:00
snider
1101248397 fix: Address 22 security findings from parallel code review (Pass 2)
Security fixes implemented:
- CRIT-001: SSRF IPv6 bypass protection (localhost, link-local, ULA, mapped)
- CRIT-002: cn_heavyZen3Memory leak fix with cleanup function
- CRIT-003: HTTP header size DoS prevention (8KB/16KB limits)
- CRIT-004: patchAsmVariants null check after allocation
- CRIT-005: autoPause race condition fix with atomics
- HIGH-001: OpenSSL strchr null pointer check
- HIGH-002: uv_loop_close error handling
- HIGH-004/005/006: Miner.cpp race conditions (atomic reset, mutex protection)
- HIGH-007: m_workersMemory dangling pointer fix
- HIGH-008: JIT buffer overflow bounds checking
- HIGH-009: Bearer prefix timing attack mitigation
- HIGH-010: CORS origin restriction to localhost
- HIGH-011: Per-IP connection limits (10 per IP) for DoS protection
- HIGH-012: SSRF 172.x RFC1918 range validation
- MED-002: pthread_join return value check on macOS
- MED-004: OclKawPowRunner exception-safe initialization
- MED-005: Generic error messages to prevent info disclosure
- MED-006: CRLF header injection prevention

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 19:28:22 +00:00
snider
b33b8eb843 fix: Address 3 security findings from code review (batch 8)
- 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>
2025-12-31 19:27:50 +00:00
snider
48a5f34661 fix: Address 4 security findings from code review (batch 7)
- CRIT-016: Document use-after-free safety mechanism in Client::onClose
- HIGH-006: Add IP-based rate limiting for API authentication
  (max 5 failures, 5 minute block time, periodic cleanup)
- HIGH-010: Document miner pointer lifetime constraint in CloseEvent
- MED-003: Improve TLS hardening comments for clarity

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 19:22:51 +00:00
snider
8fb240967a fix: Address 9 security findings from code review (batch 6)
Security fixes:
- CRIT-012: Add compile-time bounds checking in Job::setBlob()
- CRIT-017: Add header count limit (64 max) to prevent DoS
- HIGH-005: Disable TLSv1.0 and TLSv1.1 (BEAST/POODLE vulnerable)
- HIGH-008: Document signal handler safety (libuv defers to event loop)
- HIGH-011: Fix memory leak in BindHost using String copy constructor
- HIGH-023: Document JSON type safety check in Client::parse()

Quality improvements:
- MED-002: Add security headers (X-Content-Type-Options, X-Frame-Options, CSP)
- MED-007: Add URL length validation (8KB limit)
- MED-009: Reduce self-signed cert validity from 10 years to 1 year

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 19:14:24 +00:00
snider
c77cdb0076 fix: Address 9 security findings from code review (batch 5)
Security fixes:
- HIGH-017: Add timeout cleanup for Client results/callbacks maps
- HIGH-020: Fix iterator invalidation in SimpleSplitter::tick()
- HIGH-022: Add bounds checking in EthStratum height parsing
- HIGH-025: Remove improper CloseHandle on Windows std handles
- HIGH-027: Use std::nothrow for Miner allocation with proper null check

Quality/stability fixes:
- MED-001: Use explicit uint64_t max for custom diff validation
- MED-004: Add fork() error logging with strerror
- MED-006: Add null checks in Controller methods for safe operation
- MED-008: Optimize NonceMapper with single map lookup

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 18:59:24 +00:00
snider
ab0535ed86 fix: Address 4 additional security findings in proxy (batch 4)
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>
2025-12-31 18:45:40 +00:00
snider
daca391375 fix: Address 5 additional security findings in proxy (batch 3)
Critical fixes:
- CRIT-009: Document lifetime constraint on LoginEvent references to
  prevent use-after-free (architectural fix requires larger refactor)
- CRIT-015: Add proper libuv handle cleanup with uv_walk() before
  uv_loop_close() to prevent resource leaks

High priority fixes:
- HIGH-012: Log warning when LineReader truncates oversized lines
- HIGH-013: Add division-by-zero check in Job::setTarget() for
  malformed target values
- HIGH-016: Add MAX_UPSTREAMS limit (1000) in NonceSplitter to prevent
  unbounded memory growth under DoS conditions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 18:41:36 +00:00
snider
3d8423f6e1 fix: Address 9 additional security findings in proxy (batch 2)
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>
2025-12-31 18:31:48 +00:00
snider
354fd5da28 fix: Address 10 critical and high security findings in proxy
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>
2025-12-31 18:22:28 +00:00
snider
d99dd77449 feat: Add API configuration service and enhance security validation in commands 2025-12-31 17:46:25 +00:00
snider
4072bdaf0d fix: Address 16 security findings from parallel code review
Critical fixes (6):
- CRIT-001/002: Add safeKeyPrefix() to prevent panic on short public keys
- CRIT-003/004: Add sync.Once pattern for thread-safe singleton initialization
- CRIT-005: Harden console ANSI parser with length limits and stricter validation
- CRIT-006: Add client-side input validation for profile creation

High priority fixes (10):
- HIGH-001: Add secondary timeout in TTMiner to prevent goroutine leak
- HIGH-002: Verify atomic flag prevents timeout middleware race
- HIGH-004: Add LimitReader (100MB) to prevent decompression bombs
- HIGH-005: Add Lines parameter validation (max 10000) in worker
- HIGH-006: Add TLS 1.2+ config with secure cipher suites
- HIGH-007: Add pool URL format and wallet length validation
- HIGH-008: Add SIGHUP handling and force cleanup on Stop() failure
- HIGH-009: Add WebSocket message size limit and event type validation
- HIGH-010: Refactor to use takeUntil(destroy$) for observable cleanup
- HIGH-011: Add sanitizeErrorDetails() with debug mode control

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 17:44:49 +00:00
snider
ae68119329 feat: Rename XMRig references to Miner and add miner.cpp for new platform 2025-12-31 16:38:48 +00:00
snider
09df6f0e4f feat: Add security and resilience middleware
- SEC-MED-3: Add CSRF protection middleware for browser requests
- RESIL-MED-8: Add request timeout middleware (30s default)
- API-MED-7: Add Cache-Control headers for appropriate endpoints
- Update CORS to allow X-Requested-With header

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 15:54:37 +00:00
snider
3d8247c757 feat: Add database migration tests and task supervisor
- 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>
2025-12-31 15:50:17 +00:00
snider
41cc0c295c feat: Implement multiple code review improvements
- 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>
2025-12-31 15:45:25 +00:00
snider
a48ce861da feat: Implement 8 more findings from 109-finding code review
HIGH priority fixes:
- RESIL-HIGH-2: ProfileManager graceful degradation on init failure
- PERF-HIGH-1: HTTP client connection pooling with transport config
- P2P-HIGH-4: Per-peer rate limiting (100 burst, 50/sec refill)
- P2P-HIGH-2: Message deduplication with 5-min TTL cache
- API-HIGH-2: Config validation for pool URLs, wallets, threads, algos

MEDIUM priority fixes:
- RESIL-MED-4: Health check endpoints (/health, /ready) with component status
- SEC-MED-1: Already using constant-time comparison (verified)
- CONC-MED-5: Already using non-blocking broadcast (verified)

Already implemented (verified):
- P2P-HIGH-3: Handshake timeout already at 10s

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 15:32:07 +00:00
snider
d2f3ea8323 test: Add comprehensive profile_manager_test.go (TEST-CRIT-2)
- 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>
2025-12-31 15:20:00 +00:00
snider
a5ed7ebee6 feat: Implement challenge-response authentication for P2P (P2P-CRIT-4)
- 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>
2025-12-31 15:16:00 +00:00
snider
f65db3f5c4 feat: Implement peer allowlist for P2P security (P2P-CRIT-1)
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>
2025-12-31 15:06:52 +00:00
snider
87b426480b fix: Implement 6 quick wins from 109-finding code review
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>
2025-12-31 15:03:46 +00:00
snider
d7b38195ac docs: Add comprehensive 109-finding code review from 8 Opus agents
Captured all findings from 8-domain specialized review:
- 7 Critical (P2P auth, message limits, test coverage gaps)
- 19 High (race conditions, resilience, circuit breakers)
- 49 Medium (API design, architecture, performance)
- 34 Low (polish, documentation, best practices)

Includes quick wins checklist and phased implementation roadmap.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 14:53:08 +00:00
snider
8a8a175835 chore: Add Playwright test artifacts to gitignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 14:40:21 +00:00
snider
d533164893 fix: Comprehensive code hardening from 4-domain Opus review
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>
2025-12-31 14:33:30 +00:00
snider
6b73a4b84b feat: Add MCP (Model Context Protocol) server integration
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>
2025-12-31 14:12:44 +00:00
snider
c2ff474386 feat: Add API authentication and comprehensive code review fixes
Security:
- Add HTTP Basic/Digest authentication middleware (enable via MINING_API_AUTH env)
- Fix WebSocket origin check with proper URL parsing
- Add max limit (10000) to remote log lines request
- Improve CLI args validation with stricter patterns

Networking:
- Fix WebSocket double-close with sync.Once in PeerConnection
- Add 10s dial timeout for WebSocket connections
- Reset write deadline after failed sends
- Fix handler race in Transport.OnMessage with RWMutex
- Make EventHub.Stop() idempotent, buffer channels to prevent goroutine leaks

Code Simplification:
- Extract AtomicWriteFile helper to reduce duplication across 4 files
- Remove redundant MinerTypeRegistry, use MinerFactory instead
- Register simulated miner in MinerFactory
- Remove dead portToString() code from manager.go

Documentation:
- Add Advanced API Authentication section to FUTURE_IDEAS.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 14:07:26 +00:00
snider
fa3047a314 refactor: Add reliability fixes, centralized version fetching, and CHANGELOG
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>
2025-12-31 13:33:42 +00:00
snider
84635c3c17 docs: Add future ideas and enhancement roadmap
Document potential enhancements identified during code review:
- Telegram/Discord monitoring bot
- Pool auto-discovery with pools.json
- Profitability calculator with CoinGecko API
- One-click deploy templates (Unraid, Proxmox, DO, K8s)
- Community visibility improvements
- Additional ideas (GPU temps, scheduling, auto-switching)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 13:09:44 +00:00
snider
185bfd13dd test: Add error path unit tests for context cancellation and cleanup
- Add context cancellation tests for database InsertHashratePoint
- Add context timeout tests for database operations
- Add NopStore context handling tests
- Add container shutdown timeout and double-shutdown tests
- Add repository concurrent update, corrupt file, and permission tests
- Verify all error paths handle edge cases gracefully

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 13:04:20 +00:00
snider
3a9f9e32e2 refactor: Add StatsCollector pattern with miner type identification
- Add GetType() method to Miner interface for proper type identification
- Create MinerType constants (MinerTypeXMRig, MinerTypeTTMiner, MinerTypeSimulated)
- Add MinerTypeRegistry for centralized miner type discovery
- Create FetchJSONStats generic helper to reduce HTTP stats code duplication
- Replace fragile string prefix matching in manager.go with GetType() calls
- Simplify xmrig_stats.go and ttminer_stats.go using shared HTTPStatsConfig

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 13:02:01 +00:00
snider
34f860309f refactor: Add reliability fixes and architecture improvements
Reliability fixes:
- Fix HTTP response body drainage in xmrig, ttminer, miner
- Fix database init race condition (nil before close)
- Fix empty minerType bug in P2P StartMinerPayload
- Add context timeout to InsertHashratePoint (5s default)

Architecture improvements:
- Extract HashrateStore interface with DefaultStore/NopStore
- Create ServiceContainer for centralized initialization
- Extract protocol response handler (ValidateResponse, ParseResponse)
- Create generic FileRepository[T] with atomic writes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 12:43:46 +00:00
snider
89f74aebff refactor: Replace log.Printf with structured logging
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>
2025-12-31 11:48:45 +00:00
snider
07c00430b6 docs: Add Mermaid architecture diagrams
Add visual diagrams to ARCHITECTURE.md:
- System overview diagram showing all components
- Data flow sequence diagram for miner start
- WebSocket event flow diagram

Diagrams render automatically on GitHub and in MkDocs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 11:20:03 +00:00
snider
ddcf39b7ee feat: Add structured logging package
Create pkg/logging with:
- Log levels: Debug, Info, Warn, Error
- Structured fields support (key-value pairs)
- Component-based logging (WithComponent)
- Global logger convenience functions
- ParseLevel for configuration
- Full test coverage

The package provides a migration path from log.Printf to
structured logging without external dependencies.

Example usage:
  logging.Info("miner started", logging.Fields{"name": minerName})
  logger := logging.New(cfg).WithComponent("Manager")
  logger.Warn("connection lost", logging.Fields{"pool": pool})

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 11:18:22 +00:00
snider
91e7d0f484 perf: Optimize collectMinerStats() for parallel execution
- Collect stats from multiple miners concurrently using goroutines
- Minimize lock duration by taking a snapshot of miners early
- Remove redundant existence check (snapshot is sufficient)
- Extract collectSingleMinerStats for cleaner code
- Add early return when no miners are present

This reduces overall stats collection time when multiple miners
are running, as API calls now happen in parallel instead of
sequentially.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 11:16:38 +00:00
snider
d82cd10013 docs: Document logical groupings in Miner interface
Add comprehensive documentation comments to the Miner interface
explaining the logical grouping of methods:
- Lifecycle: Install, Uninstall, Start, Stop
- Stats: GetStats
- Info: GetName, GetPath, GetBinaryPath, CheckInstallation, GetLatestVersion
- History: GetHashrateHistory, AddHashratePoint, ReduceHashrateHistory
- IO: GetLogs, WriteStdin

This documents the interface structure without introducing breaking
changes from actual interface splitting.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 11:13:40 +00:00
snider
50cde8bdf3 refactor: Add MinerFactory to centralize miner instantiation
- Create pkg/mining/miner_factory.go with factory pattern
- Support for miner type aliases (e.g., "ttminer" -> "tt-miner")
- Add global convenience functions: CreateMiner, IsMinerSupported, etc.
- Replace 5 duplicate switch statements in manager.go and service.go
- Makes adding new miner types simpler (single registration point)
- Full test coverage in miner_factory_test.go

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 11:12:33 +00:00
snider
2a30744a08 test: Add race condition tests and fix AVG float64 scan bug
- Add pkg/mining/manager_race_test.go with concurrent miner tests
- Add pkg/database/database_race_test.go with concurrent DB tests
- Add TestCleanupRetention, TestGetHashrateHistoryTimeRange tests
- Add TestMultipleMinerStats, TestIsInitialized tests
- Fix AVG() float64 to int scan error in GetHashrateStats
- Fix AVG() float64 to int scan error in GetAllMinerStats
- Fix throttle tests to use NewManagerForSimulation to avoid
  autostart conflicts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 11:07:29 +00:00
snider
95ae55e4fa feat: Add rate limiter with cleanup and custom error types
Rate Limiter:
- Extract rate limiting to pkg/mining/ratelimiter.go with proper lifecycle
- Add Stop() method to gracefully shutdown cleanup goroutine
- Add RateLimiter.Middleware() for Gin integration
- Add ClientCount() for monitoring
- Fix goroutine leak in previous inline implementation

Custom Errors:
- Add pkg/mining/errors.go with MiningError type
- Define error codes: MINER_NOT_FOUND, INSTALL_FAILED, TIMEOUT, etc.
- Add predefined error constructors (ErrMinerNotFound, ErrStartFailed, etc.)
- Support error chaining with WithCause, WithDetails, WithSuggestion
- Include HTTP status codes and retry policies

Service:
- Add Service.Stop() method for graceful cleanup
- Update CLI commands to use context.Background() for Manager methods

Tests:
- Add comprehensive tests for RateLimiter (token bucket, multi-IP, refill)
- Add comprehensive tests for MiningError (codes, status, retryable)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 10:56:26 +00:00
snider
d1417a1a3c docs: Add community files and improve onboarding
- Add CODE_OF_CONDUCT.md at repository root
- Add CONTRIBUTORS.md to recognize contributors
- Add GitHub issue templates (bug report, feature request)
- Add GitHub pull request template
- Add Docker quickstart to README (fastest path to try)
- Update Contributing section with links to guidelines

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 10:43:52 +00:00
snider
749dd76f9c fix: Update tests to handle autostart behavior
- TestStartMiner_Ugly: Add algorithm to config for consistent instance naming,
  ensuring duplicate detection works correctly
- TestListMiners_Good: Account for autostarted miners by checking delta instead
  of absolute count
- TestListMiners: Renamed from TestListMinersEmpty since autostart may add miners
- Add defer manager.Stop() to all tests in mining_test.go for proper cleanup

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 10:17:14 +00:00
snider
b454bbd6d6 feat: Add context propagation, state sync, and tests
- Add context.Context to ManagerInterface methods (StartMiner, StopMiner, UninstallMiner)
- Add WebSocket state sync on client connect (sends current miner states)
- Add EventStateSync event type and SetStateProvider method
- Add manager lifecycle tests (idempotent stop, context cancellation, shutdown timeout)
- Add database tests (initialization, hashrate storage, stats)
- Add EventHub tests (creation, broadcast, client count, state provider)
- Update all test files for new context-aware API

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 10:10:39 +00:00
snider
0c8b2d999b feat: Add rate limiting, race condition fix, and shutdown improvements
- Add rate limiting middleware (10 req/s with burst of 20)
- Add atomic UpdateMinersConfig to fix config race conditions
- Add WebSocket connection limits (max 100 connections)
- Add graceful shutdown timeout (10s max wait for goroutines)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-31 09:51:48 +00:00