ax(batch): remove redundant prose comments in source files
Delete inline comments that restate what the next line of code does (AX Principle 2). Affected: circuit_breaker.go, service.go, transport.go, worker.go, identity.go, peer.go, bufpool.go, settings_manager.go, node_service.go. Co-Authored-By: Charon <charon@lethean.io>
This commit is contained in:
parent
8c4e8bd8f2
commit
4e7d4d906b
10 changed files with 0 additions and 52 deletions
|
|
@ -52,7 +52,6 @@ func MarshalJSON(value interface{}) ([]byte, error) {
|
|||
data = data[:len(data)-1]
|
||||
}
|
||||
|
||||
// Return a copy since the buffer will be reused
|
||||
result := make([]byte, len(data))
|
||||
copy(result, data)
|
||||
return result, nil
|
||||
|
|
|
|||
|
|
@ -86,9 +86,7 @@ func (circuitBreaker *CircuitBreaker) State() CircuitState {
|
|||
|
||||
// result, err := circuitBreaker.Execute(func() (interface{}, error) { return fetchStats(ctx) })
|
||||
func (circuitBreaker *CircuitBreaker) Execute(fn func() (interface{}, error)) (interface{}, error) {
|
||||
// Check if we should allow this request
|
||||
if !circuitBreaker.allowRequest() {
|
||||
// Return cached result if available
|
||||
circuitBreaker.mutex.RLock()
|
||||
if circuitBreaker.cachedResult != nil && time.Since(circuitBreaker.lastCacheTime) < circuitBreaker.cacheDuration {
|
||||
result := circuitBreaker.cachedResult
|
||||
|
|
@ -103,10 +101,8 @@ func (circuitBreaker *CircuitBreaker) Execute(fn func() (interface{}, error)) (i
|
|||
return nil, ErrCircuitOpen
|
||||
}
|
||||
|
||||
// Execute the function
|
||||
result, err := fn()
|
||||
|
||||
// Record the result
|
||||
if err != nil {
|
||||
circuitBreaker.recordFailure()
|
||||
} else {
|
||||
|
|
@ -126,7 +122,6 @@ func (circuitBreaker *CircuitBreaker) allowRequest() bool {
|
|||
return true
|
||||
|
||||
case CircuitOpen:
|
||||
// Check if we should transition to half-open
|
||||
if time.Since(circuitBreaker.lastFailure) > circuitBreaker.config.ResetTimeout {
|
||||
circuitBreaker.state = CircuitHalfOpen
|
||||
circuitBreaker.successes = 0
|
||||
|
|
@ -178,7 +173,6 @@ func (circuitBreaker *CircuitBreaker) recordSuccess(result interface{}) {
|
|||
circuitBreaker.mutex.Lock()
|
||||
defer circuitBreaker.mutex.Unlock()
|
||||
|
||||
// Cache the successful result
|
||||
circuitBreaker.cachedResult = result
|
||||
circuitBreaker.lastCacheTime = time.Now()
|
||||
circuitBreaker.cachedErr = nil
|
||||
|
|
|
|||
|
|
@ -40,7 +40,6 @@ func NewNodeService() (*NodeService, error) {
|
|||
transport: transport,
|
||||
}
|
||||
|
||||
// nodeService.controller = node.NewController(nodeManager, peerRegistry, transport)
|
||||
nodeService.controller = node.NewController(nodeManager, peerRegistry, transport)
|
||||
nodeService.worker = node.NewWorker(nodeManager, transport)
|
||||
|
||||
|
|
|
|||
|
|
@ -159,7 +159,6 @@ func contentTypeValidationMiddleware() gin.HandlerFunc {
|
|||
return
|
||||
}
|
||||
|
||||
// Skip if no body expected
|
||||
if c.Request.ContentLength == 0 {
|
||||
c.Next()
|
||||
return
|
||||
|
|
@ -184,16 +183,12 @@ func contentTypeValidationMiddleware() gin.HandlerFunc {
|
|||
// router.Use(requestIDMiddleware()) // sets X-Request-ID on every request; uses incoming header if present, otherwise generates one
|
||||
func requestIDMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Use existing request ID from header if provided, otherwise generate one
|
||||
requestID := c.GetHeader("X-Request-ID")
|
||||
if requestID == "" {
|
||||
requestID = generateRequestID()
|
||||
}
|
||||
|
||||
// Set in context for use by handlers
|
||||
c.Set("requestID", requestID)
|
||||
|
||||
// Set in response header
|
||||
c.Header("X-Request-ID", requestID)
|
||||
|
||||
c.Next()
|
||||
|
|
@ -345,16 +340,11 @@ func requestTimeoutMiddleware(timeout time.Duration) gin.HandlerFunc {
|
|||
// Replace request context
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
|
||||
// Use atomic flag to prevent race condition between handler and timeout response
|
||||
// Only one of them should write to the response
|
||||
var responded int32
|
||||
|
||||
// Channel to signal completion
|
||||
done := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
c.Next()
|
||||
// Mark that the handler has completed (and likely written a response)
|
||||
atomic.StoreInt32(&responded, 1)
|
||||
close(done)
|
||||
}()
|
||||
|
|
|
|||
|
|
@ -160,7 +160,6 @@ func (settingsManager *SettingsManager) Get() *AppSettings {
|
|||
settingsManager.mutex.RLock()
|
||||
defer settingsManager.mutex.RUnlock()
|
||||
|
||||
// Return a copy to prevent concurrent modification
|
||||
settingsCopy := *settingsManager.settings
|
||||
return &settingsCopy
|
||||
}
|
||||
|
|
|
|||
|
|
@ -54,7 +54,6 @@ func MarshalJSON(value interface{}) ([]byte, error) {
|
|||
data = data[:len(data)-1]
|
||||
}
|
||||
|
||||
// Return a copy since the buffer will be reused
|
||||
result := make([]byte, len(data))
|
||||
copy(result, data)
|
||||
return result, nil
|
||||
|
|
|
|||
|
|
@ -110,7 +110,6 @@ func NewNodeManagerWithPaths(keyPath, configPath string) (*NodeManager, error) {
|
|||
configPath: configPath,
|
||||
}
|
||||
|
||||
// Try to load existing identity
|
||||
if err := manager.loadIdentity(); err != nil {
|
||||
// Identity doesn't exist yet, that's ok
|
||||
return manager, nil
|
||||
|
|
@ -134,7 +133,6 @@ func (manager *NodeManager) GetIdentity() *NodeIdentity {
|
|||
if manager.identity == nil {
|
||||
return nil
|
||||
}
|
||||
// Return a copy to prevent mutation
|
||||
identity := *manager.identity
|
||||
return &identity
|
||||
}
|
||||
|
|
@ -150,7 +148,6 @@ func (manager *NodeManager) GenerateIdentity(name string, role NodeRole) error {
|
|||
return &ProtocolError{Code: ErrCodeOperationFailed, Message: "failed to generate keypair: " + err.Error()}
|
||||
}
|
||||
|
||||
// Derive node ID from public key (first 16 bytes as hex = 32 char ID)
|
||||
pubKeyBytes := keyPair.PublicKey()
|
||||
hash := sha256.Sum256(pubKeyBytes)
|
||||
nodeID := hex.EncodeToString(hash[:16])
|
||||
|
|
@ -207,7 +204,6 @@ func (manager *NodeManager) DeriveSharedSecret(peerPubKeyBase64 string) ([]byte,
|
|||
return nil, &ProtocolError{Code: ErrCodeOperationFailed, Message: "failed to derive shared secret: " + err.Error()}
|
||||
}
|
||||
|
||||
// Hash the shared secret using SHA-256 (same pattern as Borg/trix)
|
||||
hash := sha256.Sum256(sharedSecret)
|
||||
return hash[:], nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -146,7 +146,6 @@ func NewPeerRegistryWithPath(peersPath string) (*PeerRegistry, error) {
|
|||
allowedPublicKeys: make(map[string]bool),
|
||||
}
|
||||
|
||||
// Try to load existing peers
|
||||
if err := registry.load(); err != nil {
|
||||
// No existing peers, that's ok
|
||||
registry.rebuildKDTree()
|
||||
|
|
@ -218,7 +217,6 @@ func (registry *PeerRegistry) IsPeerAllowed(peerID string, publicKey string) boo
|
|||
return true
|
||||
}
|
||||
|
||||
// Check if public key is allowlisted
|
||||
return keyAllowed
|
||||
}
|
||||
|
||||
|
|
@ -312,7 +310,6 @@ func (registry *PeerRegistry) GetPeer(id string) *Peer {
|
|||
return nil
|
||||
}
|
||||
|
||||
// Return a copy
|
||||
peerCopy := *peer
|
||||
return &peerCopy
|
||||
}
|
||||
|
|
|
|||
|
|
@ -156,7 +156,6 @@ func (limiter *PeerRateLimiter) Allow() bool {
|
|||
limiter.lastRefill = now
|
||||
}
|
||||
|
||||
// Check if we have tokens available
|
||||
if limiter.tokens > 0 {
|
||||
limiter.tokens--
|
||||
return true
|
||||
|
|
@ -327,7 +326,6 @@ func (transport *Transport) Connect(peer *Peer) (*PeerConnection, error) {
|
|||
}
|
||||
peerURL := url.URL{Scheme: scheme, Host: peer.Address, Path: transport.config.WSPath}
|
||||
|
||||
// Dial the peer with timeout to prevent hanging on unresponsive peers
|
||||
dialer := websocket.Dialer{
|
||||
HandshakeTimeout: 10 * time.Second,
|
||||
}
|
||||
|
|
@ -344,14 +342,11 @@ func (transport *Transport) Connect(peer *Peer) (*PeerConnection, error) {
|
|||
rateLimiter: NewPeerRateLimiter(100, 50), // 100 burst, 50/sec refill
|
||||
}
|
||||
|
||||
// Perform handshake with challenge-response authentication
|
||||
// This also derives and stores the shared secret in connection.SharedSecret
|
||||
if err := transport.performHandshake(connection); err != nil {
|
||||
conn.Close()
|
||||
return nil, &ProtocolError{Code: ErrCodeOperationFailed, Message: "handshake failed: " + err.Error()}
|
||||
}
|
||||
|
||||
// Store connection using the real peer ID from handshake
|
||||
transport.mutex.Lock()
|
||||
transport.connections[connection.Peer.ID] = connection
|
||||
transport.mutex.Unlock()
|
||||
|
|
@ -432,7 +427,6 @@ func (transport *Transport) handleWSUpgrade(responseWriter http.ResponseWriter,
|
|||
return
|
||||
}
|
||||
|
||||
// Track this connection as pending during handshake
|
||||
transport.pendingConns.Add(1)
|
||||
defer transport.pendingConns.Add(-1)
|
||||
|
||||
|
|
@ -507,7 +501,6 @@ func (transport *Transport) handleWSUpgrade(responseWriter http.ResponseWriter,
|
|||
return
|
||||
}
|
||||
|
||||
// Check if peer is allowed to connect (allowlist check)
|
||||
if !transport.registry.IsPeerAllowed(payload.Identity.ID, payload.Identity.PublicKey) {
|
||||
logging.Warn("peer connection rejected: not in allowlist", logging.Fields{
|
||||
"peer_id": payload.Identity.ID,
|
||||
|
|
@ -566,7 +559,6 @@ func (transport *Transport) handleWSUpgrade(responseWriter http.ResponseWriter,
|
|||
return
|
||||
}
|
||||
|
||||
// Sign the client's challenge to prove we have the matching private key
|
||||
var challengeResponse []byte
|
||||
if len(payload.Challenge) > 0 {
|
||||
challengeResponse = SignChallenge(payload.Challenge, sharedSecret)
|
||||
|
|
@ -584,7 +576,6 @@ func (transport *Transport) handleWSUpgrade(responseWriter http.ResponseWriter,
|
|||
return
|
||||
}
|
||||
|
||||
// First ack is unencrypted (peer needs to know our public key)
|
||||
acknowledgementData, err := MarshalJSON(acknowledgementMessage)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
|
|
@ -596,12 +587,10 @@ func (transport *Transport) handleWSUpgrade(responseWriter http.ResponseWriter,
|
|||
return
|
||||
}
|
||||
|
||||
// Store connection
|
||||
transport.mutex.Lock()
|
||||
transport.connections[peer.ID] = connection
|
||||
transport.mutex.Unlock()
|
||||
|
||||
// Update registry
|
||||
transport.registry.SetConnected(peer.ID, true)
|
||||
|
||||
// Start read loop
|
||||
|
|
@ -693,7 +682,6 @@ func (transport *Transport) performHandshake(pc *PeerConnection) error {
|
|||
return &ProtocolError{Code: ErrCodeOperationFailed, Message: "derive shared secret for challenge verification: " + err.Error()}
|
||||
}
|
||||
|
||||
// Verify the server's response to our challenge
|
||||
if len(ackPayload.ChallengeResponse) == 0 {
|
||||
return &ProtocolError{Code: ErrCodeUnauthorized, Message: "server did not provide challenge response"}
|
||||
}
|
||||
|
|
@ -701,10 +689,8 @@ func (transport *Transport) performHandshake(pc *PeerConnection) error {
|
|||
return &ProtocolError{Code: ErrCodeUnauthorized, Message: "challenge response verification failed: server may not have matching private key"}
|
||||
}
|
||||
|
||||
// Store the shared secret for later use
|
||||
pc.SharedSecret = sharedSecret
|
||||
|
||||
// Update the peer in registry with the real identity
|
||||
if err := transport.registry.UpdatePeer(pc.Peer); err != nil {
|
||||
// If update fails (peer not found with old ID), add as new
|
||||
transport.registry.AddPeer(pc.Peer)
|
||||
|
|
@ -799,7 +785,6 @@ func (transport *Transport) keepalive(pc *PeerConnection) {
|
|||
case <-transport.cancelContext.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
// Check if connection is still alive
|
||||
if time.Since(pc.LastActivity) > transport.config.PingInterval+transport.config.PongTimeout {
|
||||
transport.removeConnection(pc)
|
||||
return
|
||||
|
|
@ -899,7 +884,6 @@ func (pc *PeerConnection) GracefulClose(reason string, code int) error {
|
|||
}
|
||||
}
|
||||
|
||||
// Close the underlying connection
|
||||
err = pc.Conn.Close()
|
||||
})
|
||||
return err
|
||||
|
|
@ -909,16 +893,12 @@ func (pc *PeerConnection) GracefulClose(reason string, code int) error {
|
|||
// if err != nil { return err }
|
||||
// pc.Conn.WriteMessage(websocket.BinaryMessage, data)
|
||||
func (transport *Transport) encryptMessage(msg *Message, sharedSecret []byte) ([]byte, error) {
|
||||
// Serialize message to JSON (using pooled buffer for efficiency)
|
||||
msgData, err := MarshalJSON(msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create SMSG message
|
||||
smsgMsg := smsg.NewMessage(string(msgData))
|
||||
|
||||
// Encrypt using shared secret as password (base64 encoded)
|
||||
password := base64.StdEncoding.EncodeToString(sharedSecret)
|
||||
encrypted, err := smsg.Encrypt(smsgMsg, password)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -159,8 +159,6 @@ func (worker *Worker) handleGetStats(message *Message) (*Message, error) {
|
|||
continue
|
||||
}
|
||||
|
||||
// Convert to MinerStatsItem - this is a simplified conversion
|
||||
// The actual implementation would need to match the mining package's stats structure
|
||||
item := convertMinerStats(miner, minerStats)
|
||||
stats.Miners = append(stats.Miners, item)
|
||||
}
|
||||
|
|
@ -176,7 +174,6 @@ func convertMinerStats(miner MinerInstance, rawStats interface{}) MinerStatsItem
|
|||
Type: miner.GetType(),
|
||||
}
|
||||
|
||||
// Try to extract common fields from the stats
|
||||
if statsMap, ok := rawStats.(map[string]interface{}); ok {
|
||||
if hashrate, ok := statsMap["hashrate"].(float64); ok {
|
||||
item.Hashrate = hashrate
|
||||
|
|
@ -217,7 +214,6 @@ func (worker *Worker) handleStartMiner(message *Message) (*Message, error) {
|
|||
return nil, &ProtocolError{Code: ErrCodeInvalidMessage, Message: "miner type is required"}
|
||||
}
|
||||
|
||||
// Get the config from the profile or use the override
|
||||
var config interface{}
|
||||
if payload.Config != nil {
|
||||
config = payload.Config
|
||||
|
|
@ -231,7 +227,6 @@ func (worker *Worker) handleStartMiner(message *Message) (*Message, error) {
|
|||
return nil, &ProtocolError{Code: ErrCodeOperationFailed, Message: "no config provided and no profile manager configured"}
|
||||
}
|
||||
|
||||
// Start the miner
|
||||
miner, err := worker.minerManager.StartMiner(payload.MinerType, config)
|
||||
if err != nil {
|
||||
acknowledgement := MinerAckPayload{
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue