Compare commits
No commits in common. "master" and "phase-1-pow" have entirely different histories.
master
...
phase-1-po
|
|
@ -1,14 +0,0 @@
|
|||
with-expecter: true
|
||||
dir: "{{.InterfaceDir}}/mocks"
|
||||
filename: "mock_{{.InterfaceName | snakecase}}.go"
|
||||
mockname: "Mock{{.InterfaceName}}"
|
||||
outpkg: "mocks"
|
||||
packages:
|
||||
hash-of-wisdom/internal/service:
|
||||
interfaces:
|
||||
QuoteService:
|
||||
ChallengeGenerator:
|
||||
ChallengeVerifier:
|
||||
hash-of-wisdom/internal/controller:
|
||||
interfaces:
|
||||
WisdomService:
|
||||
36
Dockerfile
36
Dockerfile
|
|
@ -1,36 +0,0 @@
|
|||
# Build stage
|
||||
FROM golang:1.24-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy go mod files
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
# Copy source code
|
||||
COPY . .
|
||||
|
||||
# Build server
|
||||
RUN CGO_ENABLED=0 go build -o hash-of-wisdom ./cmd/server
|
||||
|
||||
# Runtime stage
|
||||
FROM alpine:3.19
|
||||
|
||||
# Create non-root user
|
||||
RUN addgroup -g 1001 -S hash-of-wisdom && \
|
||||
adduser -u 1001 -S hash-of-wisdom -G hash-of-wisdom
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy binary and config from builder stage with correct ownership
|
||||
COPY --from=builder --chown=hash-of-wisdom:hash-of-wisdom /app/hash-of-wisdom .
|
||||
COPY --from=builder --chown=hash-of-wisdom:hash-of-wisdom /app/config.yaml .
|
||||
|
||||
# Switch to non-root user
|
||||
USER hash-of-wisdom
|
||||
|
||||
# Expose ports
|
||||
EXPOSE 8080 8081
|
||||
|
||||
# Run server with config file
|
||||
CMD ["./hash-of-wisdom", "-config", "config.yaml"]
|
||||
86
README.md
86
README.md
|
|
@ -1,86 +0,0 @@
|
|||
# Hash of Wisdom
|
||||
|
||||
A TCP server implementing the "Word of Wisdom" concept with proof-of-work challenges to protect against DDoS attacks.
|
||||
|
||||
## Overview
|
||||
|
||||
The Hash of Wisdom server requires clients to solve computational puzzles (proof-of-work) before receiving wise quotes. This approach prevents spam and DDoS attacks by requiring clients to invest CPU time for each request.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Prerequisites
|
||||
- Go 1.24.3+
|
||||
- Docker (optional)
|
||||
- [Task](https://taskfile.dev/) (optional, but recommended)
|
||||
|
||||
### Building
|
||||
```bash
|
||||
# Build server
|
||||
go build -o hash-of-wisdom ./cmd/server
|
||||
|
||||
# Build client
|
||||
go build -o client ./cmd/client
|
||||
```
|
||||
|
||||
### Running
|
||||
|
||||
#### Using Task (Recommended)
|
||||
```bash
|
||||
# Most useful command - run all checks
|
||||
task check
|
||||
|
||||
# Start server
|
||||
task server -- -config config.yaml
|
||||
|
||||
# Connect client
|
||||
task client -- --addr=localhost:8080
|
||||
|
||||
# Run tests
|
||||
task test
|
||||
|
||||
# See coverage
|
||||
task test-coverage
|
||||
|
||||
# See all available commands
|
||||
task --list
|
||||
```
|
||||
|
||||
#### Manual Commands
|
||||
```bash
|
||||
# Start server (uses config.yaml by default)
|
||||
./hash-of-wisdom
|
||||
|
||||
# Or with custom config
|
||||
./hash-of-wisdom -config /path/to/config.yaml
|
||||
|
||||
# Connect with client
|
||||
./client -addr localhost:8080
|
||||
|
||||
# Run tests
|
||||
go test ./...
|
||||
```
|
||||
|
||||
### Using Docker
|
||||
```bash
|
||||
# Build image
|
||||
docker build -t hash-of-wisdom .
|
||||
|
||||
# Run container
|
||||
docker run -p 8080:8080 -p 8081:8081 hash-of-wisdom
|
||||
```
|
||||
|
||||
### Monitoring
|
||||
- Metrics: http://localhost:8081/metrics (Prometheus format with Go runtime stats)
|
||||
- Profiling: http://localhost:8081/debug/pprof/
|
||||
|
||||
## Documentation
|
||||
|
||||
### Protocol & Implementation
|
||||
- [Protocol Specification](docs/PROTOCOL.md) - Binary protocol definition
|
||||
- [PoW Algorithm Analysis](docs/POW_ANALYSIS.md) - Algorithm selection rationale and comparison
|
||||
- [Implementation Plan](docs/IMPLEMENTATION.md) - Development phases and progress
|
||||
- [Package Structure](docs/PACKAGES.md) - Code organization and package responsibilities
|
||||
- [Architecture Choices](docs/ARCHITECTURE.md) - Design decisions and patterns
|
||||
|
||||
### Production Readiness
|
||||
- [Production Readiness Guide](docs/PRODUCTION_READINESS.md) - Requirements for production deployment
|
||||
40
Taskfile.yml
40
Taskfile.yml
|
|
@ -74,7 +74,7 @@ tasks:
|
|||
mocks:
|
||||
desc: Generate mocks using mockery
|
||||
cmds:
|
||||
- go run github.com/vektra/mockery/v2@latest
|
||||
- mockery
|
||||
|
||||
check:
|
||||
desc: Run all checks (fmt, build, test, lint)
|
||||
|
|
@ -93,41 +93,3 @@ tasks:
|
|||
desc: Alias for cpu-burner
|
||||
cmds:
|
||||
- task: cpu-burner
|
||||
|
||||
server:
|
||||
desc: Build and run the server
|
||||
cmds:
|
||||
- go build -o hash-of-wisdom ./cmd/server
|
||||
- ./hash-of-wisdom {{.CLI_ARGS}}
|
||||
|
||||
server-config:
|
||||
desc: Build and run the server with custom config
|
||||
cmds:
|
||||
- go build -o hash-of-wisdom ./cmd/server
|
||||
- ./hash-of-wisdom -config {{.CONFIG | default "config.yaml"}}
|
||||
|
||||
client:
|
||||
desc: Build and run the client
|
||||
cmds:
|
||||
- go build -o client ./cmd/client
|
||||
- ./client {{.CLI_ARGS | default "-addr localhost:8080"}}
|
||||
|
||||
docker-build:
|
||||
desc: Build Docker image
|
||||
cmds:
|
||||
- docker build -t hash-of-wisdom .
|
||||
|
||||
docker-run:
|
||||
desc: Run Docker container
|
||||
cmds:
|
||||
- docker run -p 8080:8080 -p 8081:8081 hash-of-wisdom
|
||||
|
||||
metrics:
|
||||
desc: Check metrics endpoint
|
||||
cmds:
|
||||
- curl -s http://localhost:8081/metrics
|
||||
|
||||
integration:
|
||||
desc: Run integration tests only
|
||||
cmds:
|
||||
- go test -v ./test/integration/...
|
||||
|
|
|
|||
|
|
@ -1,134 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/pow/solver"
|
||||
"hash-of-wisdom/internal/protocol"
|
||||
)
|
||||
|
||||
func main() {
|
||||
serverAddr := flag.String("addr", "localhost:8080", "server address")
|
||||
flag.Parse()
|
||||
|
||||
fmt.Printf("Connecting to Word of Wisdom server at %s\n", *serverAddr)
|
||||
|
||||
// Step 1: Get challenge
|
||||
challengeResp, err := requestChallenge(*serverAddr)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to get challenge: %v", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Received challenge with difficulty %d\n", challengeResp.Challenge.Difficulty)
|
||||
|
||||
// Step 2: Solve challenge
|
||||
fmt.Println("Solving challenge...")
|
||||
start := time.Now()
|
||||
|
||||
s := solver.NewSolver()
|
||||
solution, err := s.Solve(context.Background(), challengeResp.Challenge)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to solve challenge: %v", err)
|
||||
}
|
||||
|
||||
solveTime := time.Since(start)
|
||||
fmt.Printf("Challenge solved in %v with nonce %d\n", solveTime, solution.Nonce)
|
||||
|
||||
// Step 3: Submit solution and get quote
|
||||
err = submitSolution(*serverAddr, challengeResp.Challenge, solution.Nonce)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to submit solution: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func requestChallenge(serverAddr string) (*protocol.ChallengeResponse, error) {
|
||||
// Connect with timeout
|
||||
conn, err := net.DialTimeout("tcp", serverAddr, 5*time.Second)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
// Request challenge
|
||||
fmt.Println("Requesting challenge...")
|
||||
challengeReq := &protocol.ChallengeRequest{}
|
||||
if err := challengeReq.Encode(conn); err != nil {
|
||||
return nil, fmt.Errorf("failed to send challenge request: %w", err)
|
||||
}
|
||||
|
||||
// Receive challenge
|
||||
decoder := protocol.NewMessageDecoder()
|
||||
msg, err := decoder.Decode(conn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to receive challenge: %w", err)
|
||||
}
|
||||
|
||||
if msg.Type != protocol.ChallengeResponseType {
|
||||
return nil, fmt.Errorf("unexpected response type: %v", msg.Type)
|
||||
}
|
||||
|
||||
// Parse challenge
|
||||
challengeResp := &protocol.ChallengeResponse{}
|
||||
if err := challengeResp.Decode(msg.PayloadStream); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse challenge: %w", err)
|
||||
}
|
||||
|
||||
return challengeResp, nil
|
||||
}
|
||||
|
||||
func submitSolution(serverAddr string, chall *challenge.Challenge, nonce uint64) error {
|
||||
// Connect with timeout
|
||||
conn, err := net.DialTimeout("tcp", serverAddr, 5*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to connect: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
// Submit solution
|
||||
solutionReq := &protocol.SolutionRequest{
|
||||
Challenge: *chall,
|
||||
Nonce: nonce,
|
||||
}
|
||||
|
||||
fmt.Println("Submitting solution...")
|
||||
if err := solutionReq.Encode(conn); err != nil {
|
||||
return fmt.Errorf("failed to send solution: %w", err)
|
||||
}
|
||||
|
||||
// Receive quote or error
|
||||
decoder := protocol.NewMessageDecoder()
|
||||
msg, err := decoder.Decode(conn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to receive response: %w", err)
|
||||
}
|
||||
|
||||
switch msg.Type {
|
||||
case protocol.QuoteResponseType:
|
||||
solutionResp := &protocol.SolutionResponse{}
|
||||
if err := solutionResp.Decode(msg.PayloadStream); err != nil {
|
||||
return fmt.Errorf("failed to parse quote: %w", err)
|
||||
}
|
||||
fmt.Printf("\nQuote received:\n\"%s\"\n— %s\n", solutionResp.Quote.Text, solutionResp.Quote.Author)
|
||||
case protocol.ErrorResponseType:
|
||||
errorResp := &protocol.ErrorResponse{}
|
||||
if err := errorResp.Decode(msg.PayloadStream); err != nil {
|
||||
fmt.Println("Error: Contact administrator")
|
||||
return nil
|
||||
}
|
||||
if errorResp.Code == protocol.ErrServerError {
|
||||
fmt.Println("Error: Contact administrator")
|
||||
} else {
|
||||
fmt.Printf("Error: %s\n", errorResp.Message)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unexpected response type: %v", msg.Type)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -1,104 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"hash-of-wisdom/internal/config"
|
||||
"hash-of-wisdom/internal/lib/sl"
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/quotes"
|
||||
"hash-of-wisdom/internal/server"
|
||||
"hash-of-wisdom/internal/service"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
_ "net/http/pprof"
|
||||
)
|
||||
|
||||
func main() {
|
||||
configPath := flag.String("config", "", "path to configuration file")
|
||||
flag.Parse()
|
||||
|
||||
// Load configuration
|
||||
cfg, err := config.Load(*configPath)
|
||||
if err != nil {
|
||||
slog.Error("failed to load config", sl.Err(err))
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
logger := slog.Default()
|
||||
logger.Info("starting word of wisdom server", "address", cfg.Server.Address)
|
||||
|
||||
// Create components using config
|
||||
challengeConfig, err := challenge.NewConfig(
|
||||
challenge.WithDefaultDifficulty(cfg.PoW.Difficulty),
|
||||
challenge.WithMaxDifficulty(cfg.PoW.MaxDifficulty),
|
||||
challenge.WithChallengeTTL(cfg.PoW.TTL),
|
||||
challenge.WithHMACSecret([]byte(cfg.PoW.HMACSecret)),
|
||||
)
|
||||
if err != nil {
|
||||
logger.Error("failed to create challenge config", sl.Err(err))
|
||||
os.Exit(1)
|
||||
}
|
||||
generator := challenge.NewGenerator(challengeConfig)
|
||||
verifier := challenge.NewVerifier(challengeConfig)
|
||||
quoteService := quotes.NewHTTPService()
|
||||
|
||||
// Wire up service
|
||||
genAdapter := service.NewGeneratorAdapter(generator)
|
||||
wisdomService := service.NewWisdomService(genAdapter, verifier, quoteService)
|
||||
|
||||
// Create server configuration
|
||||
serverConfig := &server.Config{
|
||||
Address: cfg.Server.Address,
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: cfg.Server.Timeouts.Read,
|
||||
Write: cfg.Server.Timeouts.Write,
|
||||
Connection: cfg.Server.Timeouts.Connection,
|
||||
},
|
||||
}
|
||||
|
||||
// Go runtime metrics are automatically registered by default registry
|
||||
|
||||
// Start metrics and pprof HTTP server
|
||||
go func() {
|
||||
http.Handle("/metrics", promhttp.Handler())
|
||||
logger.Info("starting metrics server", "address", cfg.Metrics.Address)
|
||||
if err := http.ListenAndServe(cfg.Metrics.Address, nil); err != nil {
|
||||
logger.Error("metrics server failed", sl.Err(err))
|
||||
}
|
||||
}()
|
||||
|
||||
// Create context that cancels on interrupt signals
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
|
||||
// Create server
|
||||
srv := server.NewTCPServer(wisdomService, serverConfig,
|
||||
server.WithLogger(logger))
|
||||
|
||||
// Start server
|
||||
if err := srv.Start(ctx); err != nil {
|
||||
logger.Error("failed to start server", sl.Err(err))
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
logger.Info("server ready - press ctrl+c to stop")
|
||||
|
||||
// Wait for context cancellation (signal received)
|
||||
<-ctx.Done()
|
||||
|
||||
// Graceful shutdown
|
||||
logger.Info("shutting down server")
|
||||
if err := srv.Stop(); err != nil {
|
||||
logger.Error("error during shutdown", sl.Err(err))
|
||||
} else {
|
||||
logger.Info("server stopped gracefully")
|
||||
}
|
||||
|
||||
}
|
||||
22
config.yaml
22
config.yaml
|
|
@ -1,22 +0,0 @@
|
|||
server:
|
||||
address: ":8080"
|
||||
timeouts:
|
||||
read: 5s
|
||||
write: 5s
|
||||
connection: 15s
|
||||
|
||||
pow:
|
||||
difficulty: 25
|
||||
max_difficulty: 30
|
||||
ttl: 5m
|
||||
hmac_secret: "development-secret-change-in-production"
|
||||
|
||||
quotes:
|
||||
timeout: 10s
|
||||
|
||||
metrics:
|
||||
address: ":8081"
|
||||
|
||||
logging:
|
||||
level: "info"
|
||||
format: "text"
|
||||
|
|
@ -1,330 +0,0 @@
|
|||
# Architecture Choices
|
||||
|
||||
This document explains the key architectural decisions made in the Hash of Wisdom project and the reasoning behind them.
|
||||
|
||||
## Overall Architecture
|
||||
|
||||
### Clean Architecture
|
||||
We follow Clean Architecture principles with clear layer separation:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ Infrastructure Layer │ ← cmd/, internal/server, internal/protocol
|
||||
├─────────────────────────────────────┤
|
||||
│ Application Layer │ ← internal/application (message handling)
|
||||
├─────────────────────────────────────┤
|
||||
│ Domain Layer │ ← internal/service, internal/pow (business logic)
|
||||
├─────────────────────────────────────┤
|
||||
│ External Layer │ ← internal/quotes (external APIs)
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Benefits**:
|
||||
- **Testability**: Each layer can be unit tested independently
|
||||
- **Maintainability**: Changes in one layer don't cascade
|
||||
- **Flexibility**: Easy to swap implementations (e.g., different quote sources)
|
||||
- **Domain Focus**: Core business rules are isolated and protected
|
||||
|
||||
## Protocol Design
|
||||
|
||||
### Binary Protocol with JSON Payloads
|
||||
Choice: Custom binary protocol with JSON-encoded message bodies
|
||||
|
||||
**Why Binary Protocol**:
|
||||
- **Performance**: Efficient framing and length prefixes
|
||||
- **Reliability**: Clear message boundaries prevent parsing issues
|
||||
- **Extensibility**: Easy to add message types and versions
|
||||
|
||||
**Why JSON Payloads**:
|
||||
- **Simplicity**: Standard library support, easy debugging
|
||||
- **Flexibility**: Schema evolution without breaking compatibility
|
||||
- **Tooling**: Excellent tooling and human readability
|
||||
|
||||
**Alternative Considered**: Pure binary (Protocol Buffers)
|
||||
- **Rejected Because**: Added complexity without significant benefit for our use case
|
||||
- **Trade-off**: Slightly larger payload size for much simpler implementation
|
||||
|
||||
### Stateless Challenge Design
|
||||
Choice: HMAC-signed challenges with all state embedded
|
||||
|
||||
```go
|
||||
type Challenge struct {
|
||||
Target string `json:"target"` // "quotes"
|
||||
Timestamp int64 `json:"timestamp"` // Unix timestamp
|
||||
Difficulty int `json:"difficulty"` // Leading zero bits
|
||||
Random string `json:"random"` // Entropy
|
||||
Signature string `json:"signature"` // HMAC-SHA256
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits**:
|
||||
- **Scalability**: No server-side session storage required
|
||||
- **Reliability**: Challenges survive server restarts
|
||||
- **Security**: HMAC prevents tampering and replay attacks
|
||||
- **Simplicity**: No cache management or cleanup needed
|
||||
|
||||
**Alternative Considered**: Session-based challenges
|
||||
- **Rejected Because**: Requires distributed session management for horizontal scaling
|
||||
|
||||
## Proof-of-Work Algorithm
|
||||
|
||||
### SHA-256 with Leading Zero Bits
|
||||
Choice: SHA-256 hashing with difficulty measured as leading zero bits
|
||||
|
||||
**Why SHA-256**:
|
||||
- **Security**: Cryptographically secure, extensively tested
|
||||
- **Performance**: Hardware-optimized on most platforms
|
||||
- **Standardization**: Well-known algorithm with predictable properties
|
||||
|
||||
**Why Leading Zero Bits**:
|
||||
- **Linear Scaling**: Each bit doubles the difficulty (2^n complexity)
|
||||
- **Simplicity**: Easy to verify and understand
|
||||
- **Flexibility**: Fine-grained difficulty adjustment
|
||||
|
||||
**Alternative Considered**: Scrypt/Argon2 (memory-hard functions)
|
||||
- **Rejected Because**: Excessive complexity for DDoS protection use case
|
||||
- **Trade-off**: ASIC resistance not needed for temporary challenges
|
||||
|
||||
### Difficulty Range: 4-30 Bits
|
||||
Choice: Configurable difficulty with reasonable bounds
|
||||
|
||||
- **Minimum (4 bits)**: ~16 attempts average, sub-second solve time
|
||||
- **Maximum (30 bits)**: ~1 billion attempts, several seconds on modern CPU
|
||||
- **Default (4 bits)**: Balance between protection and user experience
|
||||
|
||||
## Server Architecture
|
||||
|
||||
### TCP Server with Per-Connection Goroutines
|
||||
Choice: Custom TCP server with one goroutine per connection
|
||||
|
||||
```go
|
||||
func (s *TCPServer) Start(ctx context.Context) error {
|
||||
// Start listener
|
||||
listener, err := net.Listen("tcp", s.config.Address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Start accept loop in goroutine
|
||||
go s.acceptLoop(ctx)
|
||||
return nil // Returns immediately
|
||||
}
|
||||
|
||||
func (s *TCPServer) acceptLoop(ctx context.Context) {
|
||||
for {
|
||||
conn, err := s.listener.Accept()
|
||||
if err != nil || ctx.Done() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Launch handler in goroutine with WaitGroup tracking
|
||||
s.wg.Add(1)
|
||||
go func() {
|
||||
defer s.wg.Done()
|
||||
s.handleConnection(ctx, conn)
|
||||
}()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits**:
|
||||
- **Concurrency**: Each connection handled in separate goroutine
|
||||
- **Non-blocking Start**: Server starts in background, returns immediately
|
||||
- **Graceful Shutdown**: WaitGroup ensures all connections finish before stop
|
||||
- **Context Cancellation**: Proper cleanup when context is cancelled
|
||||
- **Resource Control**: Connection timeouts prevent resource exhaustion
|
||||
|
||||
**Alternative Considered**: HTTP/REST API
|
||||
- **Rejected Because**: Test task requirements
|
||||
|
||||
### Connection Security: Multi-Level Timeouts
|
||||
Choice: Layered timeout protection against various attacks
|
||||
|
||||
1. **Connection Timeout (15s)**: Maximum total connection lifetime
|
||||
2. **Read Timeout (5s)**: Maximum time between incoming bytes
|
||||
3. **Write Timeout (5s)**: Maximum time to send response
|
||||
|
||||
**Protects Against**:
|
||||
- **Slowloris**: Slow read timeout prevents slow header attacks
|
||||
- **Slow POST**: Connection timeout limits total request time
|
||||
- **Resource Exhaustion**: Automatic cleanup of stale connections
|
||||
|
||||
## Configuration Management
|
||||
|
||||
### cleanenv with YAML + Environment Variables
|
||||
Choice: File-based configuration with environment variable overrides
|
||||
|
||||
```yaml
|
||||
# config.yaml
|
||||
server:
|
||||
address: ":8080"
|
||||
|
||||
pow:
|
||||
difficulty: 4
|
||||
```
|
||||
|
||||
```bash
|
||||
# Environment override
|
||||
export POW_DIFFICULTY=8
|
||||
```
|
||||
|
||||
**Benefits**:
|
||||
- **Development**: Easy configuration files for local development
|
||||
- **Production**: Environment variables for containerized deployments
|
||||
- **Validation**: Built-in validation and type conversion
|
||||
- **Documentation**: Self-documenting with struct tags
|
||||
|
||||
**Alternative Considered**: Pure environment variables
|
||||
- **Rejected Because**: Harder to manage complex configurations
|
||||
|
||||
## Observability Architecture
|
||||
|
||||
### Prometheus Metrics
|
||||
Choice: Prometheus format metrics with essential measurements
|
||||
|
||||
**Application Metrics**:
|
||||
- `wisdom_requests_total` - All incoming requests
|
||||
- `wisdom_request_errors_total{error_type}` - Errors by type
|
||||
- `wisdom_request_duration_seconds` - Request processing time
|
||||
- `wisdom_quotes_served_total` - Successfully served quotes
|
||||
|
||||
**Go Runtime Metrics** (automatically exported):
|
||||
- `go_memstats_*` - Memory allocation and GC statistics
|
||||
- `go_goroutines` - Current number of goroutines
|
||||
- `go_gc_duration_seconds` - Garbage collection duration
|
||||
- `process_*` - Process-level CPU, memory, and file descriptor stats
|
||||
|
||||
**Design Principle**: Simple metrics that provide actionable insights
|
||||
- **Avoided**: Complex multi-dimensional metrics
|
||||
- **Focus**: Essential health and performance indicators
|
||||
- **Runtime Visibility**: Go collector provides deep runtime observability
|
||||
|
||||
### Metrics at Infrastructure Layer
|
||||
Choice: Collect metrics in TCP server, not business logic
|
||||
|
||||
```go
|
||||
// In TCP server (infrastructure)
|
||||
metrics.RequestsTotal.Inc()
|
||||
start := time.Now()
|
||||
response, err := s.wisdomApplication.HandleMessage(ctx, msg)
|
||||
metrics.RequestDuration.Observe(time.Since(start).Seconds())
|
||||
```
|
||||
|
||||
**Benefits**:
|
||||
- **Separation of Concerns**: Business logic stays pure
|
||||
- **Consistency**: All requests measured the same way
|
||||
- **Performance**: Minimal overhead in critical path
|
||||
|
||||
## Design Patterns
|
||||
|
||||
### Dependency Injection
|
||||
All major components use constructor injection:
|
||||
```go
|
||||
server := server.NewTCPServer(wisdomApplication, config, options...)
|
||||
service := service.NewWisdomService(generator, verifier, quoteService)
|
||||
```
|
||||
|
||||
**Benefits**:
|
||||
- **Testing**: Easy to inject mocks and stubs
|
||||
- **Configuration**: Runtime assembly of components
|
||||
- **Decoupling**: Components don't know about concrete implementations
|
||||
|
||||
### Interface Segregation
|
||||
Small, focused interfaces for easy testing:
|
||||
```go
|
||||
type ChallengeGenerator interface {
|
||||
GenerateChallenge(ctx context.Context) (*Challenge, error)
|
||||
}
|
||||
|
||||
type QuoteService interface {
|
||||
GetQuote(ctx context.Context) (string, error)
|
||||
}
|
||||
```
|
||||
|
||||
### Functional Options
|
||||
Flexible configuration with sensible defaults:
|
||||
```go
|
||||
server := NewTCPServer(application, config,
|
||||
WithLogger(logger),
|
||||
)
|
||||
```
|
||||
|
||||
### Clean Architecture Implementation
|
||||
See the layer diagram in the Overall Architecture section above for package organization.
|
||||
|
||||
## Testing Architecture
|
||||
|
||||
### Layered Testing Strategy
|
||||
1. **Unit Tests**: Each package tested independently with mocks
|
||||
2. **Integration Tests**: End-to-end tests with real TCP connections
|
||||
3. **Benchmark Tests**: Performance validation for PoW algorithms
|
||||
|
||||
```go
|
||||
// Unit test with mocks
|
||||
func TestWisdomService_HandleMessage(t *testing.T) {
|
||||
mockGenerator := &MockGenerator{}
|
||||
mockVerifier := &MockVerifier{}
|
||||
mockQuotes := &MockQuoteService{}
|
||||
|
||||
service := NewWisdomService(mockGenerator, mockVerifier, mockQuotes)
|
||||
// Test business logic in isolation
|
||||
}
|
||||
|
||||
// Integration test with real components
|
||||
func TestTCPServer_SlowlorisProtection(t *testing.T) {
|
||||
// Start real server, make slow connection
|
||||
// Verify server doesn't hang
|
||||
}
|
||||
```
|
||||
|
||||
## Security Architecture
|
||||
|
||||
### Defense in Depth
|
||||
Multiple security layers working together:
|
||||
|
||||
1. **HMAC Authentication**: Prevents challenge tampering
|
||||
2. **Timestamp Validation**: Prevents replay attacks (5-minute TTL)
|
||||
3. **Connection Timeouts**: Prevents resource exhaustion
|
||||
4. **Proof-of-Work**: Rate limiting through computational cost
|
||||
5. **Input Validation**: All protocol messages validated
|
||||
|
||||
### Threat Model
|
||||
**Primary Threats Addressed**:
|
||||
- **DDoS Attacks**: PoW makes attacks expensive
|
||||
- **Resource Exhaustion**: Connection timeouts and limits
|
||||
- **Protocol Attacks**: Binary framing prevents confusion
|
||||
- **Replay Attacks**: Timestamp validation in challenges
|
||||
|
||||
**Threats NOT Addressed** (by design):
|
||||
- **Authentication**: Public service, no user accounts
|
||||
- **Authorization**: All valid solutions get quotes
|
||||
- **Data Confidentiality**: Quotes are public information
|
||||
|
||||
## Trade-offs Made
|
||||
|
||||
### Simplicity vs Performance
|
||||
- **Chose**: Simple JSON payloads over binary serialization
|
||||
- **Trade-off**: ~30% larger messages for easier debugging and maintenance
|
||||
|
||||
### Memory vs CPU
|
||||
- **Chose**: Stateless challenges requiring CPU verification
|
||||
- **Trade-off**: More CPU per request for better scalability
|
||||
|
||||
### Flexibility vs Optimization
|
||||
- **Chose**: Interface-based design with dependency injection
|
||||
- **Trade-off**: Small runtime overhead for much better testability
|
||||
|
||||
### Features vs Complexity
|
||||
- **Chose**: Essential features only (no rate limiting, user accounts, etc.)
|
||||
- **Benefit**: Clean, focused implementation that does one thing well
|
||||
|
||||
## Future Architecture Considerations
|
||||
|
||||
For production scaling, consider:
|
||||
1. **Quote Service Enhancement**: Caching, fallback quotes, multiple API sources
|
||||
2. **Load Balancing**: Multiple server instances behind load balancer
|
||||
3. **Rate Limiting**: Per-IP request limiting for additional protection
|
||||
4. **Monitoring**: Full observability stack (Prometheus, Grafana, alerting)
|
||||
5. **Security**: TLS encryption for sensitive deployments
|
||||
|
||||
The current architecture provides a solid foundation for these enhancements while maintaining simplicity and focus.
|
||||
|
|
@ -38,83 +38,121 @@
|
|||
- [X] Test edge cases (expired challenges, invalid HMAC, wrong difficulty)
|
||||
- [X] Performance tests for concurrent challenge operations
|
||||
|
||||
## Phase 2: Quote Handler
|
||||
**Goal**: Simple quote service with public API using resty
|
||||
## Phase 2: Basic Server Architecture
|
||||
- [ ] Set up dependency injection framework (wire/dig)
|
||||
- [ ] Create core interfaces and contracts
|
||||
- [ ] Set up structured logging (zerolog/logrus)
|
||||
- [ ] Set up metrics collection (prometheus)
|
||||
- [ ] Create configuration management
|
||||
- [ ] Integrate PoW package into server architecture
|
||||
|
||||
- [X] Add resty dependency to go.mod
|
||||
- [X] Create quote service package
|
||||
- [X] Implement quote fetching with HTTP client
|
||||
- [X] Add basic error handling
|
||||
## Phase 3: Quote Management System
|
||||
- [ ] Define quote storage interface
|
||||
- [ ] Implement in-memory quote repository (fake)
|
||||
- [ ] Create quote selection service (random)
|
||||
- [ ] Load initial quote collection from file/config
|
||||
- [ ] Add quote validation and sanitization
|
||||
- [ ] Write unit tests for quote management
|
||||
|
||||
## Phase 3: Service Layer Implementation
|
||||
**Goal**: Complete service layer with DI for handling requests (untied from TCP presentation)
|
||||
## Phase 4: TCP Protocol Implementation
|
||||
- [ ] Implement binary message protocol codec
|
||||
- [ ] Create protocol message types and structures
|
||||
- [ ] Implement connection handler with proper error handling
|
||||
- [ ] Add message serialization/deserialization (JSON)
|
||||
- [ ] Create protocol state machine
|
||||
- [ ] Implement connection lifecycle management
|
||||
- [ ] Write unit tests for protocol components
|
||||
|
||||
- [X] Create service layer interfaces and contracts
|
||||
- [X] Implement quote request service workflow
|
||||
- [X] Integrate PoW challenge generation and verification
|
||||
- [X] Set up simple dependency wiring
|
||||
- [X] Implement full request-response cycle
|
||||
- [X] Add comprehensive service layer tests
|
||||
- [X] Add error handling and validation
|
||||
- [X] Create public concrete WisdomService type
|
||||
- [X] Add workflow tests with real PoW implementations
|
||||
- [X] Add unsuccessful flow tests for invalid solutions
|
||||
## Phase 5: Server Core & Request Handling
|
||||
- [ ] Implement TCP server with connection pooling
|
||||
- [ ] Create request router and handler dispatcher
|
||||
- [ ] Add connection timeout and lifecycle management
|
||||
- [ ] Implement graceful shutdown mechanism
|
||||
- [ ] Add request/response logging middleware
|
||||
- [ ] Create health check endpoints
|
||||
- [ ] Write integration tests for server core
|
||||
|
||||
## Phase 4: Binary Protocol Implementation
|
||||
- [X] Implement binary message protocol codec with Reader/Writer abstraction
|
||||
- [X] Create protocol message types and structures
|
||||
- [X] Add message serialization/deserialization (JSON)
|
||||
- [X] Implement protocol parsing with proper error handling
|
||||
- [X] Create message validation and bounds checking
|
||||
- [X] Write unit tests for protocol components
|
||||
## Phase 6: DDOS Protection & Rate Limiting
|
||||
- [ ] Implement IP-based connection limiting
|
||||
- [ ] Create rate limiting service with time windows
|
||||
- [ ] Add automatic difficulty adjustment based on load
|
||||
- [ ] Implement temporary IP blacklisting
|
||||
- [ ] Create circuit breaker for overload protection
|
||||
- [ ] Add monitoring for attack detection
|
||||
- [ ] Write tests for protection mechanisms
|
||||
|
||||
## Phase 5: Binary Protocol Reworking & Application Layer Integration
|
||||
- [X] Refactor protocol codec into streaming MessageDecoder
|
||||
- [X] Implement streaming message processing with io.Reader
|
||||
- [X] Create request/response encoding and decoding methods
|
||||
- [X] Add comprehensive round-trip testing for protocol validation
|
||||
- [X] Update application layer to use streaming Message interface
|
||||
- [X] Fix application tests for new protocol design
|
||||
## Phase 7: Observability & Monitoring
|
||||
- [ ] Add structured logging throughout application
|
||||
- [ ] Implement metrics for key performance indicators:
|
||||
- [ ] Active connections count
|
||||
- [ ] Challenge generation rate
|
||||
- [ ] Solution verification rate
|
||||
- [ ] Success/failure ratios
|
||||
- [ ] Response time histograms
|
||||
- [ ] Create logging middleware for request tracing
|
||||
- [ ] Add error categorization and reporting
|
||||
- [ ] Implement health check endpoints
|
||||
|
||||
## Phase 6: TCP Server & Connection Management
|
||||
- [X] Implement TCP server with connection handling
|
||||
- [X] Add dual timeout protection:
|
||||
- [X] Connection timeout (max total connection time)
|
||||
- [X] Read timeout (max idle time between bytes - slowloris protection)
|
||||
- [X] Implement proper connection lifecycle management
|
||||
- [X] Create protocol state machine for request/response flow
|
||||
- [X] Add graceful connection cleanup and error handling
|
||||
- [X] Add slog structured logging to TCP server
|
||||
- [X] Implement functional options pattern for server configuration
|
||||
- [X] Update cmd/server to use new TCP server with logging
|
||||
## Phase 8: Configuration & Environment Setup
|
||||
- [ ] Create configuration structure with validation
|
||||
- [ ] Support environment variables and config files
|
||||
- [ ] Add configuration for different environments (dev/prod)
|
||||
- [ ] Implement feature flags for protection levels
|
||||
- [ ] Create deployment configuration templates
|
||||
- [ ] Add configuration validation and defaults
|
||||
|
||||
## Phase 7: Client Implementation
|
||||
- [X] Create client application structure
|
||||
- [X] Implement PoW solver algorithm on client side
|
||||
- [X] Create client-side protocol implementation
|
||||
- [X] Add retry logic and error handling
|
||||
- [X] Implement connection management
|
||||
- [X] Create CLI interface for client with flag support
|
||||
- [X] Add symmetric encode/decode to protocol package for client use
|
||||
- [X] Update protocol to use separate connections per request-response
|
||||
- [X] Write comprehensive slowloris protection integration tests
|
||||
- [X] Verify server successfully handles slow reader attacks
|
||||
- [X] Verify server successfully handles slow writer attacks
|
||||
- [X] Test end-to-end client-server communication flow
|
||||
## Phase 9: Client Implementation
|
||||
- [ ] Create client application structure
|
||||
- [ ] Implement PoW solver algorithm
|
||||
- [ ] Create client-side protocol implementation
|
||||
- [ ] Add retry logic and error handling
|
||||
- [ ] Implement connection management
|
||||
- [ ] Create CLI interface for client
|
||||
- [ ] Add client metrics and logging
|
||||
- [ ] Write client unit and integration tests
|
||||
|
||||
## Phase 8: Server Instrumentation & Configuration
|
||||
- [X] Add `/metrics` HTTP endpoint for Prometheus collection
|
||||
- [X] Add `/debug/pprof` endpoint for performance profiling
|
||||
- [X] Create Dockerfile to build server image
|
||||
- [X] Implement configuration management using cleanenv library
|
||||
- [X] Read configuration from file with environment variable support
|
||||
## Phase 10: Docker & Deployment
|
||||
- [ ] Create multi-stage Dockerfile for server
|
||||
- [ ] Create Dockerfile for client
|
||||
- [ ] Create docker-compose.yml for local development
|
||||
- [ ] Add docker-compose for production deployment
|
||||
- [ ] Create health check scripts for containers
|
||||
- [ ] Add environment-specific configurations
|
||||
- [ ] Create deployment documentation
|
||||
|
||||
## Phase 9: Documentation
|
||||
- [X] Create comprehensive README.md with project overview and quick start
|
||||
- [X] Document package structure and responsibilities
|
||||
- [X] Document architecture choices and design decisions
|
||||
- [X] Update production readiness assessment
|
||||
## Phase 11: Testing & Quality Assurance
|
||||
- [ ] Write comprehensive unit tests (>80% coverage):
|
||||
- [ ] PoW algorithm tests
|
||||
- [ ] Protocol handler tests
|
||||
- [ ] Rate limiting tests
|
||||
- [ ] Quote service tests
|
||||
- [ ] Configuration tests
|
||||
- [ ] Create integration tests:
|
||||
- [ ] End-to-end client-server communication
|
||||
- [ ] Load testing scenarios
|
||||
- [ ] Failure recovery tests
|
||||
- [ ] DDOS protection validation
|
||||
- [ ] Add benchmark tests for performance validation
|
||||
- [ ] Create stress testing scenarios
|
||||
|
||||
## Phase 12: Documentation & Final Polish
|
||||
- [ ] Write comprehensive README with setup instructions
|
||||
- [ ] Create API documentation for all interfaces
|
||||
- [ ] Add inline code documentation
|
||||
- [ ] Create deployment guide
|
||||
- [ ] Write troubleshooting guide
|
||||
- [ ] Add performance tuning recommendations
|
||||
- [ ] Create monitoring and alerting guide
|
||||
|
||||
## Phase 13: Production Readiness Checklist
|
||||
- [ ] Security audit of all components
|
||||
- [ ] Performance benchmarking and optimization
|
||||
- [ ] Memory leak detection and prevention
|
||||
- [ ] Resource cleanup validation
|
||||
- [ ] Error handling coverage review
|
||||
- [ ] Logging security (no sensitive data exposure)
|
||||
- [ ] Configuration security (secrets management)
|
||||
- [ ] Container security hardening
|
||||
|
||||
## Directory Structure
|
||||
```
|
||||
|
|
@ -137,3 +175,13 @@
|
|||
├── deployments/ # Deployment configurations
|
||||
└── docs/ # Additional documentation
|
||||
```
|
||||
|
||||
## Success Criteria
|
||||
- [ ] Server handles 1000+ concurrent connections
|
||||
- [ ] PoW protection prevents DDOS attacks effectively
|
||||
- [ ] All tests pass with >80% code coverage
|
||||
- [ ] Docker containers build and run successfully
|
||||
- [ ] Client successfully solves challenges and receives quotes
|
||||
- [ ] Comprehensive logging and metrics in place
|
||||
- [ ] Production-ready error handling and recovery
|
||||
- [ ] Clear documentation for deployment and operation
|
||||
|
|
|
|||
147
docs/PACKAGES.md
147
docs/PACKAGES.md
|
|
@ -1,147 +0,0 @@
|
|||
# Package Structure
|
||||
|
||||
This document explains the organization and responsibilities of all packages in the Hash of Wisdom project.
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
/
|
||||
├── cmd/ # Application entry points
|
||||
│ ├── server/ # Server application
|
||||
│ └── client/ # Client application
|
||||
├── internal/ # Private application packages
|
||||
│ ├── application/ # Application layer (message handling)
|
||||
│ ├── config/ # Configuration management
|
||||
│ ├── lib/ # Shared utilities
|
||||
│ ├── metrics/ # Prometheus metrics
|
||||
│ ├── pow/ # Proof-of-Work implementation
|
||||
│ ├── protocol/ # Binary protocol codec
|
||||
│ ├── quotes/ # Quote service
|
||||
│ ├── server/ # TCP server implementation
|
||||
│ └── service/ # Business logic layer
|
||||
├── test/ # Integration tests
|
||||
└── docs/ # Documentation
|
||||
```
|
||||
|
||||
## Package Responsibilities
|
||||
|
||||
### `cmd/server`
|
||||
**Entry point for the TCP server application**
|
||||
- Parses command-line flags and configuration
|
||||
- Initializes all components with dependency injection
|
||||
- Starts TCP server and metrics endpoints
|
||||
- Handles graceful shutdown signals
|
||||
|
||||
### `cmd/client`
|
||||
**Entry point for the client application**
|
||||
- Command-line interface for connecting to server
|
||||
- Handles proof-of-work solving on client side
|
||||
- Manages TCP connection lifecycle
|
||||
|
||||
### `internal/config`
|
||||
**Configuration management with cleanenv**
|
||||
- Defines configuration structures with YAML/env tags
|
||||
- Loads configuration from files and environment variables
|
||||
- Provides sensible defaults for all settings
|
||||
- Supports both development and production configurations
|
||||
|
||||
### `internal/lib/sl`
|
||||
**Shared logging utilities**
|
||||
- Structured logging helpers for consistent log formatting
|
||||
- Error attribute helpers for slog integration
|
||||
|
||||
### `internal/metrics`
|
||||
**Prometheus metrics collection**
|
||||
- Defines application-specific metrics (requests, errors, duration)
|
||||
- Provides simple counters and histograms for monitoring
|
||||
- Integrated at the infrastructure layer (TCP server)
|
||||
|
||||
### `internal/pow`
|
||||
**Proof-of-Work implementation**
|
||||
|
||||
#### `internal/pow/challenge`
|
||||
- **Challenge Generation**: Creates HMAC-signed stateless challenges
|
||||
- **Verification**: Validates solutions against original challenges
|
||||
- **Security**: HMAC authentication prevents tampering
|
||||
- **Configuration**: Difficulty scaling, TTL management, secrets
|
||||
|
||||
#### `internal/pow/solver`
|
||||
- **Solution Finding**: Brute-force nonce search with SHA-256
|
||||
- **Optimization**: Efficient bit counting for difficulty verification
|
||||
- **Client-side**: Used by client to solve server challenges
|
||||
|
||||
### `internal/protocol`
|
||||
**Binary protocol codec**
|
||||
- **Message Types**: Challenge requests/responses, solution requests/responses, errors
|
||||
- **Encoding/Decoding**: JSON-based message serialization
|
||||
- **Streaming**: MessageDecoder for reading from TCP connections
|
||||
- **Validation**: Message structure and field validation
|
||||
- See [Protocol Specification](PROTOCOL.md) for detailed message flow and format
|
||||
|
||||
### `internal/quotes`
|
||||
**Quote service implementation**
|
||||
- **HTTP Client**: Fetches quotes from external APIs using resty
|
||||
- **Interface**: Clean abstraction for quote retrieval
|
||||
- **Error Handling**: Graceful degradation for network issues
|
||||
- **Timeout Management**: Configurable request timeouts
|
||||
|
||||
### `internal/server`
|
||||
**TCP server implementation**
|
||||
|
||||
#### `internal/server/tcp.go`
|
||||
- **Connection Management**: Accept, handle, cleanup TCP connections
|
||||
- **Protocol Integration**: Uses protocol package for message handling
|
||||
- **Security**: Connection timeouts, slowloris protection
|
||||
- **Metrics**: Request tracking at infrastructure layer
|
||||
- **Lifecycle**: Graceful startup/shutdown with context
|
||||
|
||||
#### `internal/server/config.go`
|
||||
- **Server Configuration**: Network settings, timeouts
|
||||
- **Functional Options**: Builder pattern for server customization
|
||||
|
||||
### `internal/application`
|
||||
**Application layer (message handling and coordination)**
|
||||
- **WisdomApplication**: Protocol message handler and coordinator
|
||||
- **Message Processing**: Handles challenge and solution requests from protocol layer
|
||||
- **Response Generation**: Creates appropriate protocol responses
|
||||
- **Service Coordination**: Orchestrates calls to business logic layer
|
||||
- **Error Handling**: Converts service errors to protocol error responses
|
||||
|
||||
### `internal/service`
|
||||
**Business logic layer (core domain services)**
|
||||
- **WisdomService**: Main business logic coordinator
|
||||
- **Challenge Workflow**: Manages challenge generation and validation
|
||||
- **Solution Workflow**: Handles solution verification and quote retrieval
|
||||
- **Clean Architecture**: Pure business logic, no I/O dependencies
|
||||
- **Testing**: Easily mockable interfaces for unit testing
|
||||
|
||||
**Service Dependencies**:
|
||||
- `ChallengeGenerator` - Creates new challenges
|
||||
- `ChallengeVerifier` - Validates submitted solutions
|
||||
- `QuoteService` - Retrieves quotes after successful validation
|
||||
|
||||
### `test/integration`
|
||||
**End-to-end integration tests**
|
||||
- **Slowloris Protection**: Tests server resilience against slow attacks
|
||||
- **Connection Timeouts**: Validates timeout configurations
|
||||
- **Full Workflow**: Tests complete client-server interaction
|
||||
- **Real Components**: Uses actual TCP connections and protocol
|
||||
|
||||
## Dependency Flow
|
||||
|
||||
```
|
||||
cmd/server
|
||||
↓
|
||||
internal/config → internal/server → internal/application → internal/service
|
||||
↓ ↓ ↓
|
||||
internal/protocol internal/protocol internal/pow
|
||||
internal/metrics internal/quotes
|
||||
```
|
||||
|
||||
## Architecture Benefits
|
||||
|
||||
This package structure provides:
|
||||
- **Clear Separation**: Each package has a single, well-defined responsibility
|
||||
- **Testability**: Dependencies are injected, making testing straightforward
|
||||
- **Maintainability**: Changes are isolated to specific layers
|
||||
- **Scalability**: Clean interfaces allow for easy implementation swapping
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
# Production Readiness Assessment
|
||||
|
||||
## Current Implementation Status
|
||||
|
||||
### ✅ Core Functionality (Complete)
|
||||
- **Proof of Work System**: SHA-256 hashcash with HMAC-signed stateless challenges
|
||||
- **Binary Protocol**: Custom TCP protocol with JSON payloads and proper framing
|
||||
- **TCP Server**: Connection handling with timeout protection against slowloris attacks
|
||||
- **Client Application**: CLI tool with challenge solving and solution submission
|
||||
- **Service Layer**: Clean architecture with dependency injection
|
||||
- **Quote System**: External API integration for inspirational quotes
|
||||
- **Security**: HMAC authentication, replay protection, input validation
|
||||
- **Testing**: Comprehensive unit tests and slowloris protection integration tests
|
||||
|
||||
### ✅ Observability & Configuration (Complete)
|
||||
- **Metrics Endpoint**: Prometheus metrics at `/metrics` with application and Go runtime KPIs
|
||||
- **Application Metrics**: Request tracking, error categorization, duration histograms, quotes served
|
||||
- **Go Runtime Metrics**: Memory stats, GC metrics, goroutine counts, process stats (auto-registered)
|
||||
- **Profiler Endpoint**: Go pprof integration at `/debug/pprof/` for performance debugging
|
||||
- **Structured Logging**: slog integration throughout server components with consistent formatting
|
||||
- **Configuration**: cleanenv-based config management with YAML files and environment variables
|
||||
- **Containerization**: Production-ready Dockerfile with security best practices
|
||||
- **Error Handling**: Proper error propagation and categorization
|
||||
- **Graceful Shutdown**: Context-based shutdown with connection draining
|
||||
|
||||
## Remaining Components for Production
|
||||
|
||||
### Critical for Production
|
||||
1. **Connection Pooling & Resource Management** (worker pools, connection limits)
|
||||
2. **Rate Limiting & DDoS Protection**
|
||||
3. **Secret Management** (HMAC keys, external API credentials)
|
||||
4. **Advanced Monitoring & Alerting**
|
||||
5. **Advanced Configuration Management**
|
||||
6. **Health Checks** (graceful shutdown already implemented)
|
||||
|
||||
### Important for Scale
|
||||
7. **Security Hardening**
|
||||
8. **Quote Service Enhancement** (caching, fallback quotes, multiple sources)
|
||||
9. **Load Testing & Performance**
|
||||
10. **Documentation & Runbooks**
|
||||
|
||||
### Nice to Have
|
||||
11. **Advanced Observability**
|
||||
12. **Chaos Engineering**
|
||||
13. **Automated Deployment**
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
### High Risk Areas
|
||||
- **No rate limiting**: Vulnerable to sophisticated DDoS attacks
|
||||
- **Hardcoded secrets**: HMAC keys in configuration files (not properly secured)
|
||||
- **Limited monitoring**: Basic metrics but no alerting or attack detection
|
||||
- **Single point of failure**: No redundancy or failover
|
||||
|
||||
### Medium Risk Areas
|
||||
- **Memory management**: Potential leaks under high load
|
||||
- **External dependencies**: Quote API could become bottleneck
|
||||
- **Configuration drift**: Manual configuration prone to errors
|
||||
|
||||
## Current Architecture Strengths
|
||||
|
||||
The existing implementation provides an excellent foundation:
|
||||
- **Clean Architecture**: Proper separation of concerns with dependency injection
|
||||
- **Security-First Design**: HMAC authentication, replay protection, and timeout protection
|
||||
- **Stateless Operation**: HMAC-signed challenges enable horizontal scaling
|
||||
- **Graceful Shutdown**: Proper context handling and connection draining
|
||||
- **Comprehensive Testing**: Proven slowloris protection and unit test coverage
|
||||
- **Observability Ready**: Prometheus metrics, pprof profiling, structured logging
|
||||
- **Standard Protocols**: Industry-standard approaches (TCP, JSON, SHA-256)
|
||||
- **Container Ready**: Production Dockerfile with security best practices
|
||||
|
|
@ -31,37 +31,27 @@ For detailed analysis of alternative PoW algorithms and comprehensive justificat
|
|||
|
||||
## Protocol Flow
|
||||
|
||||
### Challenge Request Flow
|
||||
### Successful Flow
|
||||
```
|
||||
Client Server
|
||||
| |
|
||||
|-------- CHALLENGE_REQUEST ------------->|
|
||||
| |
|
||||
|<------- CHALLENGE_RESPONSE -------------| (HMAC-signed)
|
||||
| |
|
||||
[Connection closes]
|
||||
```
|
||||
|
||||
### Solution Submission Flow
|
||||
```
|
||||
Client Server
|
||||
| |
|
||||
|-------- SOLUTION_REQUEST -------------->|
|
||||
| |
|
||||
|<------- QUOTE_RESPONSE -----------------| (if solution valid)
|
||||
| |
|
||||
[Connection closes]
|
||||
```
|
||||
|
||||
### Error Flow
|
||||
```
|
||||
Client Server
|
||||
| |
|
||||
|-------- CHALLENGE_REQUEST ------------->|
|
||||
|<------- CHALLENGE_RESPONSE -------------|
|
||||
|-------- SOLUTION_REQUEST (invalid) ---->|
|
||||
| |
|
||||
|<------- ERROR_RESPONSE -----------------| (if solution invalid)
|
||||
| |
|
||||
[Connection closes]
|
||||
```
|
||||
|
||||
## Message Format
|
||||
|
|
@ -262,21 +252,12 @@ Server verifies solutions through the following steps:
|
|||
## Connection Management
|
||||
|
||||
### Connection Lifecycle
|
||||
|
||||
The protocol uses separate TCP connections for challenge requests and solution submissions:
|
||||
|
||||
#### Challenge Request:
|
||||
1. **Connect**: Client establishes TCP connection to server
|
||||
2. **Request**: Client sends CHALLENGE_REQUEST
|
||||
3. **Receive**: Client receives CHALLENGE_RESPONSE with HMAC-signed challenge
|
||||
4. **Disconnect**: Connection closes automatically
|
||||
|
||||
#### Solution Submission:
|
||||
1. **Solve**: Client solves PoW challenge offline
|
||||
2. **Connect**: Client establishes new TCP connection to server
|
||||
3. **Submit**: Client sends SOLUTION_REQUEST with challenge and nonce
|
||||
4. **Receive**: Client receives QUOTE_RESPONSE or ERROR_RESPONSE
|
||||
5. **Disconnect**: Connection closes automatically
|
||||
2. **Challenge**: Client requests and receives HMAC-signed challenge
|
||||
3. **Solve**: Client solves PoW challenge offline (can take time)
|
||||
4. **Submit**: Client submits solution with challenge proof
|
||||
5. **Receive**: Client receives quote (if valid) or error (if invalid)
|
||||
6. **Disconnect**: Connection closes automatically after response
|
||||
|
||||
### Timeouts and Limits
|
||||
|
||||
|
|
|
|||
28
go.mod
28
go.mod
|
|
@ -2,30 +2,4 @@ module hash-of-wisdom
|
|||
|
||||
go 1.24.3
|
||||
|
||||
require (
|
||||
github.com/go-resty/resty/v2 v2.16.5
|
||||
github.com/ilyakaznacheev/cleanenv v1.5.0
|
||||
github.com/prometheus/client_golang v1.23.0
|
||||
github.com/stretchr/testify v1.10.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.2.1 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.65.0 // indirect
|
||||
github.com/prometheus/procfs v0.16.1 // indirect
|
||||
github.com/stretchr/objx v0.5.2 // indirect
|
||||
golang.org/x/net v0.40.0 // indirect
|
||||
golang.org/x/sys v0.33.0 // indirect
|
||||
golang.org/x/time v0.8.0 // indirect
|
||||
google.golang.org/protobuf v1.36.6 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 // indirect
|
||||
)
|
||||
require github.com/stretchr/testify v1.10.0 // indirect
|
||||
|
|
|
|||
58
go.sum
58
go.sum
|
|
@ -1,60 +1,2 @@
|
|||
github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak=
|
||||
github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-resty/resty/v2 v2.16.5 h1:hBKqmWrr7uRc3euHVqmh1HTHcKn99Smr7o5spptdhTM=
|
||||
github.com/go-resty/resty/v2 v2.16.5/go.mod h1:hkJtXbA2iKHzJheXYvQ8snQES5ZLGKMwQ07xAwp/fiA=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/ilyakaznacheev/cleanenv v1.5.0 h1:0VNZXggJE2OYdXE87bfSSwGxeiGt9moSR2lOrsHHvr4=
|
||||
github.com/ilyakaznacheev/cleanenv v1.5.0/go.mod h1:a5aDzaJrLCQZsazHol1w8InnDcOX0OColm64SlIi6gk=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.23.0 h1:ust4zpdl9r4trLY/gSjlm07PuiBq2ynaXXlptpfy8Uc=
|
||||
github.com/prometheus/client_golang v1.23.0/go.mod h1:i/o0R9ByOnHX0McrTMTyhYvKE4haaf2mW08I+jGAjEE=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.65.0 h1:QDwzd+G1twt//Kwj/Ww6E9FQq1iVMmODnILtW1t2VzE=
|
||||
github.com/prometheus/common v0.65.0/go.mod h1:0gZns+BLRQ3V6NdaerOhMbwwRbNh9hkGINtQAsP5GS8=
|
||||
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
|
||||
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
||||
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
|
||||
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
|
||||
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
||||
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg=
|
||||
golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
|
||||
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 h1:slmdOY3vp8a7KQbHkL+FLbvbkgMqmXojpFUO/jENuqQ=
|
||||
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3/go.mod h1:oVgVk4OWVDi43qWBEyGhXgYxt7+ED4iYNpTngSLX2Iw=
|
||||
|
|
|
|||
|
|
@ -1,88 +0,0 @@
|
|||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/protocol"
|
||||
"hash-of-wisdom/internal/quotes"
|
||||
)
|
||||
|
||||
// Response represents an encodable response that can write itself to a connection
|
||||
type Response interface {
|
||||
Encode(w io.Writer) error
|
||||
}
|
||||
|
||||
// WisdomService defines the interface for the wisdom service
|
||||
type WisdomService interface {
|
||||
GenerateChallenge(ctx context.Context, resource string) (*challenge.Challenge, error)
|
||||
VerifySolution(ctx context.Context, solution *challenge.Solution) error
|
||||
GetQuote(ctx context.Context) (*quotes.Quote, error)
|
||||
}
|
||||
|
||||
// WisdomApplication handles the Word of Wisdom application logic
|
||||
type WisdomApplication struct {
|
||||
wisdomService WisdomService
|
||||
}
|
||||
|
||||
// NewWisdomApplication creates a new wisdom application handler
|
||||
func NewWisdomApplication(wisdomService WisdomService) *WisdomApplication {
|
||||
return &WisdomApplication{
|
||||
wisdomService: wisdomService,
|
||||
}
|
||||
}
|
||||
|
||||
// HandleMessage processes a protocol message and returns an encodable response
|
||||
func (a *WisdomApplication) HandleMessage(ctx context.Context, msg *protocol.Message) (Response, error) {
|
||||
switch msg.Type {
|
||||
case protocol.ChallengeRequestType:
|
||||
return a.handleChallengeRequest(ctx)
|
||||
case protocol.SolutionRequestType:
|
||||
return a.handleSolutionRequest(ctx, msg)
|
||||
default:
|
||||
return &protocol.ErrorResponse{
|
||||
Code: protocol.ErrMalformedMessage,
|
||||
Message: fmt.Sprintf("unsupported message type: 0x%02x", msg.Type),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// handleChallengeRequest processes challenge requests
|
||||
func (a *WisdomApplication) handleChallengeRequest(ctx context.Context) (Response, error) {
|
||||
challenge, err := a.wisdomService.GenerateChallenge(ctx, "quotes")
|
||||
if err != nil {
|
||||
return &protocol.ErrorResponse{Code: protocol.ErrServerError, Message: "Contact administrator"}, nil
|
||||
}
|
||||
|
||||
return &protocol.ChallengeResponse{Challenge: challenge}, nil
|
||||
}
|
||||
|
||||
// handleSolutionRequest processes solution requests
|
||||
func (a *WisdomApplication) handleSolutionRequest(ctx context.Context, msg *protocol.Message) (Response, error) {
|
||||
// Parse solution request
|
||||
var solutionReq protocol.SolutionRequest
|
||||
if err := solutionReq.Decode(msg.PayloadStream); err != nil {
|
||||
return &protocol.ErrorResponse{Code: protocol.ErrMalformedMessage, Message: "invalid solution format"}, nil
|
||||
}
|
||||
|
||||
// Create solution object
|
||||
solution := &challenge.Solution{
|
||||
Challenge: solutionReq.Challenge,
|
||||
Nonce: solutionReq.Nonce,
|
||||
}
|
||||
|
||||
// Verify solution
|
||||
if err := a.wisdomService.VerifySolution(ctx, solution); err != nil {
|
||||
return &protocol.ErrorResponse{Code: protocol.ErrInvalidSolution, Message: "solution verification failed"}, nil
|
||||
}
|
||||
|
||||
// Get quote
|
||||
quote, err := a.wisdomService.GetQuote(ctx)
|
||||
if err != nil {
|
||||
return &protocol.ErrorResponse{Code: protocol.ErrServerError, Message: "Contact administrator"}, nil
|
||||
}
|
||||
|
||||
return &protocol.SolutionResponse{Quote: quote}, nil
|
||||
}
|
||||
|
|
@ -1,324 +0,0 @@
|
|||
package application
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hash-of-wisdom/internal/application/mocks"
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/protocol"
|
||||
"hash-of-wisdom/internal/quotes"
|
||||
"hash-of-wisdom/internal/service"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewWisdomApplication(t *testing.T) {
|
||||
mockService := mocks.NewMockWisdomService(t)
|
||||
app := NewWisdomApplication(mockService)
|
||||
|
||||
assert.NotNil(t, app)
|
||||
assert.Equal(t, mockService, app.wisdomService)
|
||||
}
|
||||
|
||||
func TestWisdomApplication_HandleMessage_UnsupportedType(t *testing.T) {
|
||||
mockService := mocks.NewMockWisdomService(t)
|
||||
app := NewWisdomApplication(mockService)
|
||||
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.MessageType(0xFF), // Invalid type
|
||||
PayloadLength: 0,
|
||||
PayloadStream: nil,
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Type assert to ErrorResponse
|
||||
errorResponse, ok := response.(*protocol.ErrorResponse)
|
||||
require.True(t, ok, "Expected ErrorResponse")
|
||||
assert.Equal(t, protocol.ErrMalformedMessage, errorResponse.Code)
|
||||
assert.Contains(t, errorResponse.Message, "unsupported message type: 0xff")
|
||||
}
|
||||
|
||||
func TestWisdomApplication_HandleChallengeRequest_Success(t *testing.T) {
|
||||
mockService := mocks.NewMockWisdomService(t)
|
||||
app := NewWisdomApplication(mockService)
|
||||
|
||||
// Mock successful challenge generation
|
||||
testChallenge := &challenge.Challenge{
|
||||
Resource: "quotes",
|
||||
Timestamp: 12345,
|
||||
Difficulty: 4,
|
||||
Random: []byte("test"),
|
||||
HMAC: []byte("signature"),
|
||||
}
|
||||
|
||||
mockService.On("GenerateChallenge", mock.Anything, "quotes").Return(testChallenge, nil)
|
||||
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.ChallengeRequestType,
|
||||
PayloadLength: 0,
|
||||
PayloadStream: nil,
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Type assert to ChallengeResponse
|
||||
challengeResponse, ok := response.(*protocol.ChallengeResponse)
|
||||
require.True(t, ok, "Expected ChallengeResponse")
|
||||
assert.Equal(t, testChallenge, challengeResponse.Challenge)
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
}
|
||||
|
||||
func TestWisdomApplication_HandleChallengeRequest_ServiceError(t *testing.T) {
|
||||
mockService := mocks.NewMockWisdomService(t)
|
||||
app := NewWisdomApplication(mockService)
|
||||
|
||||
// Mock service error
|
||||
mockService.On("GenerateChallenge", mock.Anything, "quotes").Return(nil, errors.New("service error"))
|
||||
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.ChallengeRequestType,
|
||||
PayloadLength: 0,
|
||||
PayloadStream: nil,
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Type assert to ErrorResponse
|
||||
errorResponse, ok := response.(*protocol.ErrorResponse)
|
||||
require.True(t, ok, "Expected ErrorResponse")
|
||||
assert.Equal(t, protocol.ErrServerError, errorResponse.Code)
|
||||
assert.Equal(t, "Contact administrator", errorResponse.Message)
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
}
|
||||
|
||||
func TestWisdomApplication_HandleSolutionRequest_Success(t *testing.T) {
|
||||
mockService := mocks.NewMockWisdomService(t)
|
||||
app := NewWisdomApplication(mockService)
|
||||
|
||||
// Create test solution request
|
||||
testChallenge := challenge.Challenge{
|
||||
Resource: "quotes",
|
||||
Timestamp: 12345,
|
||||
Difficulty: 4,
|
||||
Random: []byte("test"),
|
||||
HMAC: []byte("signature"),
|
||||
}
|
||||
|
||||
solutionPayload := protocol.SolutionRequest{
|
||||
Challenge: testChallenge,
|
||||
Nonce: 12345,
|
||||
}
|
||||
|
||||
payloadJSON, err := json.Marshal(solutionPayload)
|
||||
require.NoError(t, err)
|
||||
|
||||
testQuote := "es.Quote{
|
||||
Text: "Test quote",
|
||||
Author: "Test Author",
|
||||
}
|
||||
|
||||
// Mock successful verification and quote retrieval
|
||||
mockService.On("VerifySolution", mock.Anything, mock.AnythingOfType("*challenge.Solution")).Return(nil)
|
||||
mockService.On("GetQuote", mock.Anything).Return(testQuote, nil)
|
||||
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.SolutionRequestType,
|
||||
PayloadLength: uint32(len(payloadJSON)),
|
||||
PayloadStream: bytes.NewReader(payloadJSON),
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Type assert to SolutionResponse
|
||||
solutionResponse, ok := response.(*protocol.SolutionResponse)
|
||||
require.True(t, ok, "Expected SolutionResponse")
|
||||
assert.Equal(t, testQuote, solutionResponse.Quote)
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
}
|
||||
|
||||
func TestWisdomApplication_HandleSolutionRequest_InvalidJSON(t *testing.T) {
|
||||
mockService := mocks.NewMockWisdomService(t)
|
||||
app := NewWisdomApplication(mockService)
|
||||
|
||||
invalidJSON := []byte("invalid json")
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.SolutionRequestType,
|
||||
PayloadLength: uint32(len(invalidJSON)),
|
||||
PayloadStream: bytes.NewReader(invalidJSON),
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Type assert to ErrorResponse
|
||||
errorResponse, ok := response.(*protocol.ErrorResponse)
|
||||
require.True(t, ok, "Expected ErrorResponse")
|
||||
assert.Equal(t, protocol.ErrMalformedMessage, errorResponse.Code)
|
||||
assert.Equal(t, "invalid solution format", errorResponse.Message)
|
||||
|
||||
mockService.AssertNotCalled(t, "VerifySolution")
|
||||
mockService.AssertNotCalled(t, "GetQuote")
|
||||
}
|
||||
|
||||
func TestWisdomApplication_HandleSolutionRequest_VerificationFailed(t *testing.T) {
|
||||
mockService := mocks.NewMockWisdomService(t)
|
||||
app := NewWisdomApplication(mockService)
|
||||
|
||||
// Create test solution request
|
||||
testChallenge := challenge.Challenge{
|
||||
Resource: "quotes",
|
||||
Timestamp: 12345,
|
||||
Difficulty: 4,
|
||||
Random: []byte("test"),
|
||||
HMAC: []byte("signature"),
|
||||
}
|
||||
|
||||
solutionPayload := protocol.SolutionRequest{
|
||||
Challenge: testChallenge,
|
||||
Nonce: 12345,
|
||||
}
|
||||
|
||||
payloadJSON, err := json.Marshal(solutionPayload)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Mock verification failure
|
||||
mockService.On("VerifySolution", mock.Anything, mock.AnythingOfType("*challenge.Solution")).Return(service.ErrInvalidSolution)
|
||||
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.SolutionRequestType,
|
||||
PayloadLength: uint32(len(payloadJSON)),
|
||||
PayloadStream: bytes.NewReader(payloadJSON),
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Type assert to ErrorResponse
|
||||
errorResponse, ok := response.(*protocol.ErrorResponse)
|
||||
require.True(t, ok, "Expected ErrorResponse")
|
||||
assert.Equal(t, protocol.ErrInvalidSolution, errorResponse.Code)
|
||||
assert.Equal(t, "solution verification failed", errorResponse.Message)
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
mockService.AssertNotCalled(t, "GetQuote")
|
||||
}
|
||||
|
||||
func TestWisdomApplication_HandleSolutionRequest_QuoteServiceError(t *testing.T) {
|
||||
mockService := mocks.NewMockWisdomService(t)
|
||||
app := NewWisdomApplication(mockService)
|
||||
|
||||
// Create test solution request
|
||||
testChallenge := challenge.Challenge{
|
||||
Resource: "quotes",
|
||||
Timestamp: 12345,
|
||||
Difficulty: 4,
|
||||
Random: []byte("test"),
|
||||
HMAC: []byte("signature"),
|
||||
}
|
||||
|
||||
solutionPayload := protocol.SolutionRequest{
|
||||
Challenge: testChallenge,
|
||||
Nonce: 12345,
|
||||
}
|
||||
|
||||
payloadJSON, err := json.Marshal(solutionPayload)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Mock successful verification but quote service error
|
||||
mockService.On("VerifySolution", mock.Anything, mock.AnythingOfType("*challenge.Solution")).Return(nil)
|
||||
mockService.On("GetQuote", mock.Anything).Return(nil, errors.New("quote service error"))
|
||||
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.SolutionRequestType,
|
||||
PayloadLength: uint32(len(payloadJSON)),
|
||||
PayloadStream: bytes.NewReader(payloadJSON),
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Type assert to ErrorResponse
|
||||
errorResponse, ok := response.(*protocol.ErrorResponse)
|
||||
require.True(t, ok, "Expected ErrorResponse")
|
||||
assert.Equal(t, protocol.ErrServerError, errorResponse.Code)
|
||||
assert.Equal(t, "Contact administrator", errorResponse.Message)
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
}
|
||||
|
||||
func TestWisdomApplication_HandleMessage_ContextCancellation(t *testing.T) {
|
||||
mockService := mocks.NewMockWisdomService(t)
|
||||
app := NewWisdomApplication(mockService)
|
||||
|
||||
// Create cancelled context
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
// Mock service to respect context cancellation
|
||||
mockService.On("GenerateChallenge", mock.Anything, "quotes").Return(nil, context.Canceled)
|
||||
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.ChallengeRequestType,
|
||||
PayloadLength: 0,
|
||||
PayloadStream: nil,
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Type assert to ErrorResponse
|
||||
errorResponse, ok := response.(*protocol.ErrorResponse)
|
||||
require.True(t, ok, "Expected ErrorResponse")
|
||||
assert.Equal(t, protocol.ErrServerError, errorResponse.Code)
|
||||
|
||||
mockService.AssertExpectations(t)
|
||||
}
|
||||
|
||||
func TestResponseEncoding(t *testing.T) {
|
||||
// Test ChallengeResponse encoding produces valid binary format
|
||||
testChallenge := &challenge.Challenge{
|
||||
Resource: "quotes",
|
||||
Timestamp: 12345,
|
||||
Difficulty: 4,
|
||||
Random: []byte("test"),
|
||||
HMAC: []byte("signature"),
|
||||
}
|
||||
|
||||
challengeResponse := &protocol.ChallengeResponse{Challenge: testChallenge}
|
||||
var buf bytes.Buffer
|
||||
err := challengeResponse.Encode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify binary format
|
||||
data := buf.Bytes()
|
||||
assert.GreaterOrEqual(t, len(data), 5) // At least header size
|
||||
|
||||
// Check message type
|
||||
assert.Equal(t, byte(protocol.ChallengeResponseType), data[0])
|
||||
|
||||
// Check payload contains expected data
|
||||
payload := string(data[5:]) // Skip header
|
||||
assert.Contains(t, payload, "quotes")
|
||||
assert.Contains(t, payload, "12345")
|
||||
}
|
||||
|
|
@ -1,203 +0,0 @@
|
|||
// Code generated by mockery v2.53.5. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
context "context"
|
||||
challenge "hash-of-wisdom/internal/pow/challenge"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
|
||||
quotes "hash-of-wisdom/internal/quotes"
|
||||
)
|
||||
|
||||
// MockWisdomService is an autogenerated mock type for the WisdomService type
|
||||
type MockWisdomService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockWisdomService_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockWisdomService) EXPECT() *MockWisdomService_Expecter {
|
||||
return &MockWisdomService_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// GenerateChallenge provides a mock function with given fields: ctx, resource
|
||||
func (_m *MockWisdomService) GenerateChallenge(ctx context.Context, resource string) (*challenge.Challenge, error) {
|
||||
ret := _m.Called(ctx, resource)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GenerateChallenge")
|
||||
}
|
||||
|
||||
var r0 *challenge.Challenge
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string) (*challenge.Challenge, error)); ok {
|
||||
return rf(ctx, resource)
|
||||
}
|
||||
if rf, ok := ret.Get(0).(func(context.Context, string) *challenge.Challenge); ok {
|
||||
r0 = rf(ctx, resource)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(*challenge.Challenge)
|
||||
}
|
||||
}
|
||||
|
||||
if rf, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = rf(ctx, resource)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockWisdomService_GenerateChallenge_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GenerateChallenge'
|
||||
type MockWisdomService_GenerateChallenge_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GenerateChallenge is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - resource string
|
||||
func (_e *MockWisdomService_Expecter) GenerateChallenge(ctx interface{}, resource interface{}) *MockWisdomService_GenerateChallenge_Call {
|
||||
return &MockWisdomService_GenerateChallenge_Call{Call: _e.mock.On("GenerateChallenge", ctx, resource)}
|
||||
}
|
||||
|
||||
func (_c *MockWisdomService_GenerateChallenge_Call) Run(run func(ctx context.Context, resource string)) *MockWisdomService_GenerateChallenge_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context), args[1].(string))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockWisdomService_GenerateChallenge_Call) Return(_a0 *challenge.Challenge, _a1 error) *MockWisdomService_GenerateChallenge_Call {
|
||||
_c.Call.Return(_a0, _a1)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockWisdomService_GenerateChallenge_Call) RunAndReturn(run func(context.Context, string) (*challenge.Challenge, error)) *MockWisdomService_GenerateChallenge_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetQuote provides a mock function with given fields: ctx
|
||||
func (_m *MockWisdomService) GetQuote(ctx context.Context) (*quotes.Quote, error) {
|
||||
ret := _m.Called(ctx)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetQuote")
|
||||
}
|
||||
|
||||
var r0 *quotes.Quote
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context) (*quotes.Quote, error)); ok {
|
||||
return rf(ctx)
|
||||
}
|
||||
if rf, ok := ret.Get(0).(func(context.Context) *quotes.Quote); ok {
|
||||
r0 = rf(ctx)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(*quotes.Quote)
|
||||
}
|
||||
}
|
||||
|
||||
if rf, ok := ret.Get(1).(func(context.Context) error); ok {
|
||||
r1 = rf(ctx)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockWisdomService_GetQuote_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetQuote'
|
||||
type MockWisdomService_GetQuote_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetQuote is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
func (_e *MockWisdomService_Expecter) GetQuote(ctx interface{}) *MockWisdomService_GetQuote_Call {
|
||||
return &MockWisdomService_GetQuote_Call{Call: _e.mock.On("GetQuote", ctx)}
|
||||
}
|
||||
|
||||
func (_c *MockWisdomService_GetQuote_Call) Run(run func(ctx context.Context)) *MockWisdomService_GetQuote_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockWisdomService_GetQuote_Call) Return(_a0 *quotes.Quote, _a1 error) *MockWisdomService_GetQuote_Call {
|
||||
_c.Call.Return(_a0, _a1)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockWisdomService_GetQuote_Call) RunAndReturn(run func(context.Context) (*quotes.Quote, error)) *MockWisdomService_GetQuote_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// VerifySolution provides a mock function with given fields: ctx, solution
|
||||
func (_m *MockWisdomService) VerifySolution(ctx context.Context, solution *challenge.Solution) error {
|
||||
ret := _m.Called(ctx, solution)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for VerifySolution")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context, *challenge.Solution) error); ok {
|
||||
r0 = rf(ctx, solution)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockWisdomService_VerifySolution_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifySolution'
|
||||
type MockWisdomService_VerifySolution_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// VerifySolution is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - solution *challenge.Solution
|
||||
func (_e *MockWisdomService_Expecter) VerifySolution(ctx interface{}, solution interface{}) *MockWisdomService_VerifySolution_Call {
|
||||
return &MockWisdomService_VerifySolution_Call{Call: _e.mock.On("VerifySolution", ctx, solution)}
|
||||
}
|
||||
|
||||
func (_c *MockWisdomService_VerifySolution_Call) Run(run func(ctx context.Context, solution *challenge.Solution)) *MockWisdomService_VerifySolution_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context), args[1].(*challenge.Solution))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockWisdomService_VerifySolution_Call) Return(_a0 error) *MockWisdomService_VerifySolution_Call {
|
||||
_c.Call.Return(_a0)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockWisdomService_VerifySolution_Call) RunAndReturn(run func(context.Context, *challenge.Solution) error) *MockWisdomService_VerifySolution_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// NewMockWisdomService creates a new instance of MockWisdomService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockWisdomService(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockWisdomService {
|
||||
mock := &MockWisdomService{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() { mock.AssertExpectations(t) })
|
||||
|
||||
return mock
|
||||
}
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/ilyakaznacheev/cleanenv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Server ServerConfig `yaml:"server"`
|
||||
PoW PoWConfig `yaml:"pow"`
|
||||
Quotes QuotesConfig `yaml:"quotes"`
|
||||
Metrics MetricsConfig `yaml:"metrics"`
|
||||
Logging LoggingConfig `yaml:"logging"`
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
Address string `yaml:"address" env:"SERVER_ADDRESS" env-default:":8080"`
|
||||
Timeouts TimeoutConfig `yaml:"timeouts"`
|
||||
}
|
||||
|
||||
type TimeoutConfig struct {
|
||||
Read time.Duration `yaml:"read" env:"SERVER_READ_TIMEOUT" env-default:"5s"`
|
||||
Write time.Duration `yaml:"write" env:"SERVER_WRITE_TIMEOUT" env-default:"5s"`
|
||||
Connection time.Duration `yaml:"connection" env:"SERVER_CONNECTION_TIMEOUT" env-default:"15s"`
|
||||
}
|
||||
|
||||
type PoWConfig struct {
|
||||
Difficulty int `yaml:"difficulty" env:"POW_DIFFICULTY" env-default:"4"`
|
||||
MaxDifficulty int `yaml:"max_difficulty" env:"POW_MAX_DIFFICULTY" env-default:"10"`
|
||||
TTL time.Duration `yaml:"ttl" env:"POW_TTL" env-default:"5m"`
|
||||
HMACSecret string `yaml:"hmac_secret" env:"POW_HMAC_SECRET" env-default:"development-secret-change-in-production"`
|
||||
}
|
||||
|
||||
type QuotesConfig struct {
|
||||
Timeout time.Duration `yaml:"timeout" env:"QUOTES_TIMEOUT" env-default:"10s"`
|
||||
}
|
||||
|
||||
type MetricsConfig struct {
|
||||
Address string `yaml:"address" env:"METRICS_ADDRESS" env-default:":8081"`
|
||||
}
|
||||
|
||||
type LoggingConfig struct {
|
||||
Level string `yaml:"level" env:"LOG_LEVEL" env-default:"info"`
|
||||
Format string `yaml:"format" env:"LOG_FORMAT" env-default:"text"`
|
||||
}
|
||||
|
||||
func Load(configPath string) (*Config, error) {
|
||||
cfg := &Config{}
|
||||
|
||||
if configPath != "" {
|
||||
err := cleanenv.ReadConfig(configPath, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
err := cleanenv.ReadEnv(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c *Config) ToServerConfig() *ServerConfig {
|
||||
return &c.Server
|
||||
}
|
||||
|
||||
func (c *Config) ToPoWConfig() *PoWConfig {
|
||||
return &c.PoW
|
||||
}
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
package sl
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
)
|
||||
|
||||
// Err creates a structured error attribute for slog
|
||||
func Err(err error) slog.Attr {
|
||||
return slog.Attr{
|
||||
Key: "error",
|
||||
Value: slog.StringValue(err.Error()),
|
||||
}
|
||||
}
|
||||
|
||||
// MockHandler is a test handler that discards all log messages
|
||||
type MockHandler struct{}
|
||||
|
||||
func (h *MockHandler) Enabled(context.Context, slog.Level) bool { return false }
|
||||
func (h *MockHandler) Handle(context.Context, slog.Record) error { return nil }
|
||||
func (h *MockHandler) WithAttrs([]slog.Attr) slog.Handler { return h }
|
||||
func (h *MockHandler) WithGroup(string) slog.Handler { return h }
|
||||
|
||||
// NewMockLogger creates a logger that discards all messages for testing
|
||||
func NewMockLogger() *slog.Logger {
|
||||
return slog.New(&MockHandler{})
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
package metrics
|
||||
|
||||
import (
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
)
|
||||
|
||||
var (
|
||||
ActiveConnections = promauto.NewGauge(prometheus.GaugeOpts{
|
||||
Name: "wisdom_active_connections",
|
||||
Help: "Number of currently active TCP connections",
|
||||
})
|
||||
|
||||
RequestsTotal = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "wisdom_requests_total",
|
||||
Help: "Total number of requests processed",
|
||||
})
|
||||
|
||||
RequestErrors = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Name: "wisdom_request_errors_total",
|
||||
Help: "Total number of request errors by type",
|
||||
}, []string{"error_type"})
|
||||
|
||||
RequestDuration = promauto.NewHistogram(prometheus.HistogramOpts{
|
||||
Name: "wisdom_request_duration_seconds",
|
||||
Help: "Time taken to process requests",
|
||||
})
|
||||
|
||||
QuotesServed = promauto.NewCounter(prometheus.CounterOpts{
|
||||
Name: "wisdom_quotes_served_total",
|
||||
Help: "Total number of quotes successfully served to clients",
|
||||
})
|
||||
)
|
||||
|
|
@ -68,8 +68,8 @@ func (c *Challenge) VerifySolution(nonce uint64) bool {
|
|||
|
||||
// hasLeadingZeroBits checks if hash has the required number of leading zero bits
|
||||
func hasLeadingZeroBits(hash []byte, difficulty int) bool {
|
||||
full := difficulty >> 3 // number of whole zero bytes
|
||||
rem := uint(difficulty & 7) // remaining leading zero bits
|
||||
full := difficulty >> 3 // number of whole zero bytes
|
||||
rem := uint(difficulty & 7) // remaining leading zero bits
|
||||
|
||||
for i := range full {
|
||||
if hash[i] != 0 {
|
||||
|
|
|
|||
|
|
@ -1,31 +0,0 @@
|
|||
package protocol
|
||||
|
||||
// MessageType represents the type of protocol message
|
||||
type MessageType byte
|
||||
|
||||
const (
|
||||
ChallengeRequestType MessageType = 0x01
|
||||
SolutionRequestType MessageType = 0x03
|
||||
// Response types (for responses.go)
|
||||
ChallengeResponseType MessageType = 0x02
|
||||
QuoteResponseType MessageType = 0x04
|
||||
ErrorResponseType MessageType = 0x05
|
||||
)
|
||||
|
||||
// Error codes as defined in protocol specification
|
||||
const (
|
||||
ErrMalformedMessage = "MALFORMED_MESSAGE"
|
||||
ErrInvalidChallenge = "INVALID_CHALLENGE"
|
||||
ErrInvalidSolution = "INVALID_SOLUTION"
|
||||
ErrExpiredChallenge = "EXPIRED_CHALLENGE"
|
||||
ErrRateLimited = "RATE_LIMITED"
|
||||
ErrServerError = "SERVER_ERROR"
|
||||
ErrTooManyConnections = "TOO_MANY_CONNECTIONS"
|
||||
ErrDifficultyTooHigh = "DIFFICULTY_TOO_HIGH"
|
||||
)
|
||||
|
||||
// Protocol constants
|
||||
const (
|
||||
MaxPayloadSize = 8 * 1024 // 8KB maximum payload size
|
||||
HeaderSize = 5 // 1 byte type + 4 bytes length
|
||||
)
|
||||
|
|
@ -1,157 +0,0 @@
|
|||
package protocol
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/quotes"
|
||||
)
|
||||
|
||||
func TestSymmetricEncoding_ChallengeRequest(t *testing.T) {
|
||||
// Create a challenge request
|
||||
req := &ChallengeRequest{}
|
||||
|
||||
// Encode it
|
||||
var buf bytes.Buffer
|
||||
err := req.Encode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Decode it back
|
||||
decoder := NewMessageDecoder()
|
||||
msg, err := decoder.Decode(&buf)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ChallengeRequestType, msg.Type)
|
||||
assert.Equal(t, uint32(0), msg.PayloadLength)
|
||||
|
||||
// Decode the request payload
|
||||
decodedReq := &ChallengeRequest{}
|
||||
err = decodedReq.Decode(msg.PayloadStream)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestSymmetricEncoding_SolutionRequest(t *testing.T) {
|
||||
// Create a solution request
|
||||
req := &SolutionRequest{
|
||||
Challenge: challenge.Challenge{
|
||||
Timestamp: 1640995200,
|
||||
Difficulty: 4,
|
||||
Resource: "quotes",
|
||||
Random: []byte("test"),
|
||||
HMAC: []byte("test"),
|
||||
},
|
||||
Nonce: 12345,
|
||||
}
|
||||
|
||||
// Encode it
|
||||
var buf bytes.Buffer
|
||||
err := req.Encode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Decode it back
|
||||
decoder := NewMessageDecoder()
|
||||
msg, err := decoder.Decode(&buf)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, SolutionRequestType, msg.Type)
|
||||
assert.Greater(t, msg.PayloadLength, uint32(0))
|
||||
|
||||
// Decode the request payload
|
||||
decodedReq := &SolutionRequest{}
|
||||
err = decodedReq.Decode(msg.PayloadStream)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, req.Nonce, decodedReq.Nonce)
|
||||
assert.Equal(t, req.Challenge.Timestamp, decodedReq.Challenge.Timestamp)
|
||||
}
|
||||
|
||||
func TestSymmetricEncoding_ChallengeResponse(t *testing.T) {
|
||||
// Create a challenge response
|
||||
resp := &ChallengeResponse{
|
||||
Challenge: &challenge.Challenge{
|
||||
Timestamp: 1640995200,
|
||||
Difficulty: 4,
|
||||
Resource: "quotes",
|
||||
Random: []byte("test"),
|
||||
HMAC: []byte("test"),
|
||||
},
|
||||
}
|
||||
|
||||
// Encode it
|
||||
var buf bytes.Buffer
|
||||
err := resp.Encode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Decode it back
|
||||
decoder := NewMessageDecoder()
|
||||
msg, err := decoder.Decode(&buf)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ChallengeResponseType, msg.Type)
|
||||
assert.Greater(t, msg.PayloadLength, uint32(0))
|
||||
|
||||
// Decode the response payload
|
||||
decodedResp := &ChallengeResponse{}
|
||||
err = decodedResp.Decode(msg.PayloadStream)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, resp.Challenge.Timestamp, decodedResp.Challenge.Timestamp)
|
||||
assert.Equal(t, resp.Challenge.Difficulty, decodedResp.Challenge.Difficulty)
|
||||
}
|
||||
|
||||
func TestSymmetricEncoding_SolutionResponse(t *testing.T) {
|
||||
// Create a solution response
|
||||
resp := &SolutionResponse{
|
||||
Quote: "es.Quote{
|
||||
Text: "Test quote",
|
||||
Author: "Test Author",
|
||||
},
|
||||
}
|
||||
|
||||
// Encode it
|
||||
var buf bytes.Buffer
|
||||
err := resp.Encode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Decode it back
|
||||
decoder := NewMessageDecoder()
|
||||
msg, err := decoder.Decode(&buf)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, QuoteResponseType, msg.Type)
|
||||
assert.Greater(t, msg.PayloadLength, uint32(0))
|
||||
|
||||
// Decode the response payload
|
||||
decodedResp := &SolutionResponse{}
|
||||
err = decodedResp.Decode(msg.PayloadStream)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, resp.Quote.Text, decodedResp.Quote.Text)
|
||||
assert.Equal(t, resp.Quote.Author, decodedResp.Quote.Author)
|
||||
}
|
||||
|
||||
func TestSymmetricEncoding_ErrorResponse(t *testing.T) {
|
||||
// Create an error response
|
||||
resp := &ErrorResponse{
|
||||
Code: "TEST_ERROR",
|
||||
Message: "Test error message",
|
||||
Details: map[string]string{"key": "value"},
|
||||
}
|
||||
|
||||
// Encode it
|
||||
var buf bytes.Buffer
|
||||
err := resp.Encode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Decode it back
|
||||
decoder := NewMessageDecoder()
|
||||
msg, err := decoder.Decode(&buf)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ErrorResponseType, msg.Type)
|
||||
assert.Greater(t, msg.PayloadLength, uint32(0))
|
||||
|
||||
// Decode the response payload
|
||||
decodedResp := &ErrorResponse{}
|
||||
err = decodedResp.Decode(msg.PayloadStream)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, resp.Code, decodedResp.Code)
|
||||
assert.Equal(t, resp.Message, decodedResp.Message)
|
||||
assert.Equal(t, resp.Details, decodedResp.Details)
|
||||
}
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
package protocol
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// encode is a helper function that encodes any message with the given message type
|
||||
func encode(w io.Writer, msgType MessageType, payload interface{}) error {
|
||||
var payloadBytes []byte
|
||||
var err error
|
||||
|
||||
// Only marshal if payload is not nil
|
||||
if payload != nil {
|
||||
payloadBytes, err = json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encode payload: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Write message type (1 byte)
|
||||
if err := binary.Write(w, binary.BigEndian, msgType); err != nil {
|
||||
return fmt.Errorf("failed to write message type: %w", err)
|
||||
}
|
||||
|
||||
// Write payload length (4 bytes, big-endian)
|
||||
if err := binary.Write(w, binary.BigEndian, uint32(len(payloadBytes))); err != nil {
|
||||
return fmt.Errorf("failed to write payload length: %w", err)
|
||||
}
|
||||
|
||||
// Write JSON payload if we have one
|
||||
if len(payloadBytes) > 0 {
|
||||
if _, err := w.Write(payloadBytes); err != nil {
|
||||
return fmt.Errorf("failed to write payload: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
package protocol
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// MessageDecoder handles decoding of protocol message headers
|
||||
type MessageDecoder struct{}
|
||||
|
||||
// NewMessageDecoder creates a new message decoder
|
||||
func NewMessageDecoder() *MessageDecoder {
|
||||
return &MessageDecoder{}
|
||||
}
|
||||
|
||||
// Decode reads the message header and returns a Message with the payload stream
|
||||
func (d *MessageDecoder) Decode(r io.Reader) (*Message, error) {
|
||||
// Read message type (1 byte)
|
||||
var msgType MessageType
|
||||
if err := binary.Read(r, binary.BigEndian, &msgType); err != nil {
|
||||
if err == io.EOF {
|
||||
return nil, err
|
||||
}
|
||||
return nil, fmt.Errorf("failed to read message type: %w", err)
|
||||
}
|
||||
|
||||
// Read payload length (4 bytes, big-endian)
|
||||
var payloadLength uint32
|
||||
if err := binary.Read(r, binary.BigEndian, &payloadLength); err != nil {
|
||||
return nil, fmt.Errorf("failed to read payload length: %w", err)
|
||||
}
|
||||
|
||||
// Validate payload length
|
||||
if payloadLength > MaxPayloadSize {
|
||||
return nil, fmt.Errorf("payload length %d exceeds maximum %d", payloadLength, MaxPayloadSize)
|
||||
}
|
||||
|
||||
// Create limited reader for the payload
|
||||
var payloadStream io.Reader
|
||||
if payloadLength > 0 {
|
||||
payloadStream = io.LimitReader(r, int64(payloadLength))
|
||||
}
|
||||
|
||||
return &Message{
|
||||
Type: msgType,
|
||||
PayloadLength: payloadLength,
|
||||
PayloadStream: payloadStream,
|
||||
}, nil
|
||||
}
|
||||
|
|
@ -1,215 +0,0 @@
|
|||
package protocol
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestMessageDecoder_Decode_Header(t *testing.T) {
|
||||
decoder := NewMessageDecoder()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
data []byte
|
||||
wantType MessageType
|
||||
wantLength uint32
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "challenge request with empty payload",
|
||||
data: []byte{0x01, 0x00, 0x00, 0x00, 0x00},
|
||||
wantType: ChallengeRequestType,
|
||||
wantLength: 0,
|
||||
},
|
||||
{
|
||||
name: "solution request with payload",
|
||||
data: append([]byte{0x03, 0x00, 0x00, 0x00, 0x05}, []byte("hello")...),
|
||||
wantType: SolutionRequestType,
|
||||
wantLength: 5,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
buf := bytes.NewBuffer(tt.data)
|
||||
msg, err := decoder.Decode(buf)
|
||||
|
||||
if tt.wantErr != "" {
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tt.wantErr)
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tt.wantType, msg.Type)
|
||||
assert.Equal(t, tt.wantLength, msg.PayloadLength)
|
||||
|
||||
if tt.wantLength > 0 {
|
||||
assert.NotNil(t, msg.PayloadStream)
|
||||
} else {
|
||||
assert.Nil(t, msg.PayloadStream)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageDecoder_Decode_Errors(t *testing.T) {
|
||||
decoder := NewMessageDecoder()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
data []byte
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "empty data",
|
||||
data: []byte{},
|
||||
wantErr: "EOF",
|
||||
},
|
||||
{
|
||||
name: "incomplete header",
|
||||
data: []byte{0x01, 0x00, 0x00},
|
||||
wantErr: "failed to read payload length",
|
||||
},
|
||||
{
|
||||
name: "payload too large",
|
||||
data: append([]byte{0x01}, encodeBigEndianUint32(MaxPayloadSize+1)...),
|
||||
wantErr: "payload length",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
buf := bytes.NewBuffer(tt.data)
|
||||
_, err := decoder.Decode(buf)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tt.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChallengeRequest_Decode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
stream io.Reader
|
||||
}{
|
||||
{"nil stream", nil},
|
||||
{"non-empty stream", bytes.NewReader([]byte("ignored"))},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := &ChallengeRequest{}
|
||||
err := req.Decode(tt.stream)
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolutionRequest_Decode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
payload []byte
|
||||
wantErr bool
|
||||
wantNonce uint64
|
||||
}{
|
||||
{
|
||||
name: "valid solution request",
|
||||
payload: []byte(`{"challenge":{"timestamp":1640995200,"difficulty":4,"resource":"quotes","random":"cmFuZG9tMTIz","hmac":"aG1hY19zaWduYXR1cmU="},"nonce":12345}`),
|
||||
wantNonce: 12345,
|
||||
},
|
||||
{
|
||||
name: "invalid JSON",
|
||||
payload: []byte(`{invalid json}`),
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "invalid UTF-8",
|
||||
payload: []byte{0xFF, 0xFE, 0xFD},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := &SolutionRequest{}
|
||||
var reader io.Reader
|
||||
if tt.payload != nil {
|
||||
reader = bytes.NewReader(tt.payload)
|
||||
}
|
||||
|
||||
err := req.Decode(reader)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tt.wantNonce, req.Nonce)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("nil stream should error", func(t *testing.T) {
|
||||
req := &SolutionRequest{}
|
||||
err := req.Decode(nil)
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEndToEnd_RequestDecoding(t *testing.T) {
|
||||
decoder := NewMessageDecoder()
|
||||
|
||||
t.Run("challenge request flow", func(t *testing.T) {
|
||||
// Create message data: type=0x01, length=0
|
||||
data := []byte{0x01, 0x00, 0x00, 0x00, 0x00}
|
||||
buf := bytes.NewBuffer(data)
|
||||
|
||||
// Decode header
|
||||
msg, err := decoder.Decode(buf)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ChallengeRequestType, msg.Type)
|
||||
|
||||
// Decode request
|
||||
req := &ChallengeRequest{}
|
||||
err = req.Decode(msg.PayloadStream)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("solution request flow", func(t *testing.T) {
|
||||
payload := `{"challenge":{"timestamp":1640995200,"difficulty":4,"resource":"quotes","random":"cmFuZG9tMTIz","hmac":"aG1hY19zaWduYXR1cmU="},"nonce":12345}`
|
||||
|
||||
// Create message data: type=0x03, length, payload
|
||||
var buf bytes.Buffer
|
||||
buf.WriteByte(0x03) // SolutionRequestType
|
||||
length := uint32(len(payload))
|
||||
buf.Write(encodeBigEndianUint32(length))
|
||||
buf.WriteString(payload)
|
||||
|
||||
// Decode header
|
||||
msg, err := decoder.Decode(&buf)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, SolutionRequestType, msg.Type)
|
||||
assert.Equal(t, length, msg.PayloadLength)
|
||||
|
||||
// Decode request
|
||||
req := &SolutionRequest{}
|
||||
err = req.Decode(msg.PayloadStream)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, uint64(12345), req.Nonce)
|
||||
})
|
||||
}
|
||||
|
||||
// Helper functions for testing
|
||||
|
||||
func encodeBigEndianUint32(val uint32) []byte {
|
||||
return []byte{
|
||||
byte(val >> 24),
|
||||
byte(val >> 16),
|
||||
byte(val >> 8),
|
||||
byte(val),
|
||||
}
|
||||
}
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
package protocol
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
)
|
||||
|
||||
// ChallengeRequest is empty (no payload for challenge requests)
|
||||
type ChallengeRequest struct{}
|
||||
|
||||
// Decode reads a challenge request from the payload stream
|
||||
func (r *ChallengeRequest) Decode(stream io.Reader) error {
|
||||
// Challenge requests have no payload to decode
|
||||
return nil
|
||||
}
|
||||
|
||||
// Encode writes a challenge request to the writer
|
||||
func (r *ChallengeRequest) Encode(w io.Writer) error {
|
||||
return encode(w, ChallengeRequestType, nil)
|
||||
}
|
||||
|
||||
// SolutionRequest contains the client's solution attempt
|
||||
type SolutionRequest struct {
|
||||
Challenge challenge.Challenge `json:"challenge"`
|
||||
Nonce uint64 `json:"nonce"`
|
||||
}
|
||||
|
||||
// Decode reads a solution request from the payload stream
|
||||
func (r *SolutionRequest) Decode(stream io.Reader) error {
|
||||
if stream == nil {
|
||||
// json.NewDecoder panics on nil reader
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
// Parse JSON directly from stream
|
||||
decoder := json.NewDecoder(stream)
|
||||
return decoder.Decode(r)
|
||||
}
|
||||
|
||||
// Encode writes a solution request to the writer
|
||||
func (r *SolutionRequest) Encode(w io.Writer) error {
|
||||
return encode(w, SolutionRequestType, r)
|
||||
}
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
package protocol
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/quotes"
|
||||
)
|
||||
|
||||
// ChallengeResponse represents a challenge response
|
||||
type ChallengeResponse struct {
|
||||
Challenge *challenge.Challenge
|
||||
}
|
||||
|
||||
// Decode reads a challenge response from the payload stream
|
||||
func (r *ChallengeResponse) Decode(stream io.Reader) error {
|
||||
if stream == nil {
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
// Parse JSON directly from stream
|
||||
decoder := json.NewDecoder(stream)
|
||||
return decoder.Decode(&r.Challenge)
|
||||
}
|
||||
|
||||
// SolutionResponse represents a successful solution response (contains quote)
|
||||
type SolutionResponse struct {
|
||||
Quote *quotes.Quote
|
||||
}
|
||||
|
||||
// Decode reads a solution response from the payload stream
|
||||
func (r *SolutionResponse) Decode(stream io.Reader) error {
|
||||
if stream == nil {
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
// Parse JSON directly from stream
|
||||
decoder := json.NewDecoder(stream)
|
||||
return decoder.Decode(&r.Quote)
|
||||
}
|
||||
|
||||
// ErrorResponse represents an error response
|
||||
type ErrorResponse struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RetryAfter int `json:"retry_after,omitempty"`
|
||||
Details map[string]string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// Decode reads an error response from the payload stream
|
||||
func (r *ErrorResponse) Decode(stream io.Reader) error {
|
||||
if stream == nil {
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
// Parse JSON directly from stream
|
||||
decoder := json.NewDecoder(stream)
|
||||
return decoder.Decode(r)
|
||||
}
|
||||
|
||||
// Encode writes the challenge response to the writer
|
||||
func (r *ChallengeResponse) Encode(w io.Writer) error {
|
||||
return encode(w, ChallengeResponseType, r.Challenge)
|
||||
}
|
||||
|
||||
// Encode writes the solution response to the writer
|
||||
func (r *SolutionResponse) Encode(w io.Writer) error {
|
||||
return encode(w, QuoteResponseType, r.Quote)
|
||||
}
|
||||
|
||||
// Encode writes the error response to the writer
|
||||
func (r *ErrorResponse) Encode(w io.Writer) error {
|
||||
return encode(w, ErrorResponseType, r)
|
||||
}
|
||||
|
|
@ -1,194 +0,0 @@
|
|||
package protocol
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestChallengeResponse_BinaryFormat(t *testing.T) {
|
||||
testChallenge := &challenge.Challenge{
|
||||
Timestamp: 1640995200,
|
||||
Difficulty: 4,
|
||||
Resource: "quotes",
|
||||
Random: []byte("test-random"),
|
||||
HMAC: []byte("test-hmac"),
|
||||
}
|
||||
|
||||
response := &ChallengeResponse{Challenge: testChallenge}
|
||||
var buf bytes.Buffer
|
||||
err := response.Encode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify binary format
|
||||
data := buf.Bytes()
|
||||
assert.GreaterOrEqual(t, len(data), 5)
|
||||
assert.Equal(t, byte(ChallengeResponseType), data[0])
|
||||
|
||||
payloadLength := binary.BigEndian.Uint32(data[1:5])
|
||||
assert.Greater(t, payloadLength, uint32(0))
|
||||
assert.Equal(t, len(data)-5, int(payloadLength))
|
||||
|
||||
// Verify payload content
|
||||
payload := string(data[5:])
|
||||
assert.Contains(t, payload, "1640995200")
|
||||
assert.Contains(t, payload, "quotes")
|
||||
}
|
||||
|
||||
func TestSolutionRequest_RoundTrip(t *testing.T) {
|
||||
decoder := NewMessageDecoder()
|
||||
|
||||
payload := `{"challenge":{"timestamp":1640995200,"difficulty":4,"resource":"quotes","random":"dGVzdC1yYW5kb20=","hmac":"dGVzdC1obWFj"},"nonce":12345}`
|
||||
|
||||
var buf bytes.Buffer
|
||||
buf.WriteByte(byte(SolutionRequestType))
|
||||
binary.Write(&buf, binary.BigEndian, uint32(len(payload)))
|
||||
buf.WriteString(payload)
|
||||
|
||||
// Decode header
|
||||
msg, err := decoder.Decode(&buf)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, SolutionRequestType, msg.Type)
|
||||
assert.Equal(t, uint32(len(payload)), msg.PayloadLength)
|
||||
|
||||
// Decode request
|
||||
req := &SolutionRequest{}
|
||||
err = req.Decode(msg.PayloadStream)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, int64(1640995200), req.Challenge.Timestamp)
|
||||
assert.Equal(t, 4, req.Challenge.Difficulty)
|
||||
assert.Equal(t, "quotes", req.Challenge.Resource)
|
||||
assert.Equal(t, uint64(12345), req.Nonce)
|
||||
assert.Equal(t, []byte("test-random"), req.Challenge.Random)
|
||||
assert.Equal(t, []byte("test-hmac"), req.Challenge.HMAC)
|
||||
}
|
||||
|
||||
func TestErrorResponse_BinaryFormat(t *testing.T) {
|
||||
errorResp := &ErrorResponse{
|
||||
Code: "INVALID_SOLUTION",
|
||||
Message: "Test error message",
|
||||
RetryAfter: 30,
|
||||
Details: map[string]string{"reason": "test"},
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
err := errorResp.Encode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
data := buf.Bytes()
|
||||
assert.Equal(t, byte(ErrorResponseType), data[0])
|
||||
|
||||
length := binary.BigEndian.Uint32(data[1:5])
|
||||
assert.Greater(t, length, uint32(0))
|
||||
assert.LessOrEqual(t, length, uint32(MaxPayloadSize))
|
||||
|
||||
payload := string(data[5:])
|
||||
assert.Contains(t, payload, "INVALID_SOLUTION")
|
||||
assert.Contains(t, payload, "Test error message")
|
||||
assert.Contains(t, payload, "30")
|
||||
assert.Contains(t, payload, "test")
|
||||
}
|
||||
|
||||
func TestChallengeRequest_EmptyPayload(t *testing.T) {
|
||||
decoder := NewMessageDecoder()
|
||||
|
||||
data := []byte{0x01, 0x00, 0x00, 0x00, 0x00}
|
||||
buf := bytes.NewBuffer(data)
|
||||
|
||||
msg, err := decoder.Decode(buf)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ChallengeRequestType, msg.Type)
|
||||
assert.Equal(t, uint32(0), msg.PayloadLength)
|
||||
assert.Nil(t, msg.PayloadStream)
|
||||
|
||||
req := &ChallengeRequest{}
|
||||
err = req.Decode(msg.PayloadStream)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestPayloadStream_LimitedRead(t *testing.T) {
|
||||
decoder := NewMessageDecoder()
|
||||
|
||||
payload := `{"challenge":{"timestamp":1640995200,"difficulty":4,"resource":"quotes","random":"dGVzdA==","hmac":"dGVzdA=="},"nonce":999}`
|
||||
extraData := "this should not be read"
|
||||
|
||||
var buf bytes.Buffer
|
||||
buf.WriteByte(byte(SolutionRequestType))
|
||||
binary.Write(&buf, binary.BigEndian, uint32(len(payload)))
|
||||
buf.WriteString(payload)
|
||||
buf.WriteString(extraData)
|
||||
|
||||
msg, err := decoder.Decode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
req := &SolutionRequest{}
|
||||
err = req.Decode(msg.PayloadStream)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, uint64(999), req.Nonce)
|
||||
|
||||
// Verify extra data wasn't consumed
|
||||
remaining := buf.String()
|
||||
assert.Equal(t, extraData, remaining)
|
||||
}
|
||||
|
||||
func TestTrueRoundTrip_ServerClientCommunication(t *testing.T) {
|
||||
// Simulate actual server-client communication
|
||||
|
||||
// 1. SERVER: Create and encode a challenge response
|
||||
originalChallenge := &challenge.Challenge{
|
||||
Timestamp: 1640995200,
|
||||
Difficulty: 4,
|
||||
Resource: "quotes",
|
||||
Random: []byte("server-random-data"),
|
||||
HMAC: []byte("server-hmac-signature"),
|
||||
}
|
||||
|
||||
serverResponse := &ChallengeResponse{Challenge: originalChallenge}
|
||||
var networkBuffer bytes.Buffer
|
||||
|
||||
// Server encodes response to "network"
|
||||
err := serverResponse.Encode(&networkBuffer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 2. NETWORK: Simulate transmission (networkBuffer contains binary data)
|
||||
wireData := networkBuffer.Bytes()
|
||||
assert.Greater(t, len(wireData), 5) // Has header + payload
|
||||
|
||||
// 3. CLIENT: Receives and decodes the binary data
|
||||
// (Client would use a generic decoder, not our server-side MessageDecoder)
|
||||
clientBuf := bytes.NewBuffer(wireData)
|
||||
|
||||
// Client reads header manually
|
||||
var msgType MessageType
|
||||
err = binary.Read(clientBuf, binary.BigEndian, &msgType)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ChallengeResponseType, msgType)
|
||||
|
||||
var payloadLength uint32
|
||||
err = binary.Read(clientBuf, binary.BigEndian, &payloadLength)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Client reads payload
|
||||
payloadBytes := make([]byte, payloadLength)
|
||||
_, err = clientBuf.Read(payloadBytes)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Client deserializes the challenge
|
||||
var receivedChallenge challenge.Challenge
|
||||
err = json.Unmarshal(payloadBytes, &receivedChallenge)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 4. VERIFY: Client received exactly what server sent
|
||||
assert.Equal(t, originalChallenge.Timestamp, receivedChallenge.Timestamp)
|
||||
assert.Equal(t, originalChallenge.Difficulty, receivedChallenge.Difficulty)
|
||||
assert.Equal(t, originalChallenge.Resource, receivedChallenge.Resource)
|
||||
assert.Equal(t, originalChallenge.Random, receivedChallenge.Random)
|
||||
assert.Equal(t, originalChallenge.HMAC, receivedChallenge.HMAC)
|
||||
}
|
||||
|
|
@ -1,177 +0,0 @@
|
|||
package protocol
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/quotes"
|
||||
)
|
||||
|
||||
// TestSpecCompliance_ChallengeResponse verifies challenge response matches PROTOCOL.md format
|
||||
func TestSpecCompliance_ChallengeResponse(t *testing.T) {
|
||||
resp := &ChallengeResponse{
|
||||
Challenge: &challenge.Challenge{
|
||||
Timestamp: 1640995200,
|
||||
Difficulty: 4,
|
||||
Resource: "quotes",
|
||||
Random: []byte{0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6},
|
||||
HMAC: []byte("base64url_encoded_signature"),
|
||||
},
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
err := resp.Encode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Skip header (5 bytes) and get payload
|
||||
header := buf.Bytes()[:5]
|
||||
payload := buf.Bytes()[5:]
|
||||
|
||||
// Verify header format
|
||||
assert.Equal(t, byte(ChallengeResponseType), header[0])
|
||||
assert.Equal(t, uint32(len(payload)), uint32(header[1])<<24|uint32(header[2])<<16|uint32(header[3])<<8|uint32(header[4]))
|
||||
|
||||
// Verify JSON payload matches spec format
|
||||
var decoded map[string]interface{}
|
||||
err = json.Unmarshal(payload, &decoded)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Check required fields from spec
|
||||
assert.Contains(t, decoded, "timestamp")
|
||||
assert.Contains(t, decoded, "difficulty")
|
||||
assert.Contains(t, decoded, "resource")
|
||||
assert.Contains(t, decoded, "random")
|
||||
assert.Contains(t, decoded, "hmac")
|
||||
|
||||
assert.Equal(t, float64(1640995200), decoded["timestamp"])
|
||||
assert.Equal(t, float64(4), decoded["difficulty"])
|
||||
assert.Equal(t, "quotes", decoded["resource"])
|
||||
}
|
||||
|
||||
// TestSpecCompliance_SolutionRequest verifies solution request matches PROTOCOL.md format
|
||||
func TestSpecCompliance_SolutionRequest(t *testing.T) {
|
||||
req := &SolutionRequest{
|
||||
Challenge: challenge.Challenge{
|
||||
Timestamp: 1640995200,
|
||||
Difficulty: 4,
|
||||
Resource: "quotes",
|
||||
Random: []byte{0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6},
|
||||
HMAC: []byte("base64url_encoded_signature"),
|
||||
},
|
||||
Nonce: 12345,
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
err := req.Encode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Skip header and get payload
|
||||
payload := buf.Bytes()[5:]
|
||||
|
||||
// Verify JSON payload matches spec format
|
||||
var decoded map[string]interface{}
|
||||
err = json.Unmarshal(payload, &decoded)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Check required top-level fields
|
||||
assert.Contains(t, decoded, "challenge")
|
||||
assert.Contains(t, decoded, "nonce")
|
||||
assert.Equal(t, float64(12345), decoded["nonce"])
|
||||
|
||||
// Check challenge structure
|
||||
challenge := decoded["challenge"].(map[string]interface{})
|
||||
assert.Contains(t, challenge, "timestamp")
|
||||
assert.Contains(t, challenge, "difficulty")
|
||||
assert.Contains(t, challenge, "resource")
|
||||
assert.Contains(t, challenge, "random")
|
||||
assert.Contains(t, challenge, "hmac")
|
||||
}
|
||||
|
||||
// TestSpecCompliance_QuoteResponse verifies quote response matches PROTOCOL.md format
|
||||
func TestSpecCompliance_QuoteResponse(t *testing.T) {
|
||||
resp := &SolutionResponse{
|
||||
Quote: "es.Quote{
|
||||
Text: "The only way to do great work is to love what you do.",
|
||||
Author: "Steve Jobs",
|
||||
},
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
err := resp.Encode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Skip header and get payload
|
||||
payload := buf.Bytes()[5:]
|
||||
|
||||
// Verify JSON payload matches spec format
|
||||
var decoded map[string]interface{}
|
||||
err = json.Unmarshal(payload, &decoded)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Check required fields from spec
|
||||
assert.Contains(t, decoded, "text")
|
||||
assert.Contains(t, decoded, "author")
|
||||
assert.Equal(t, "The only way to do great work is to love what you do.", decoded["text"])
|
||||
assert.Equal(t, "Steve Jobs", decoded["author"])
|
||||
}
|
||||
|
||||
// TestSpecCompliance_ErrorResponse verifies error response matches PROTOCOL.md format
|
||||
func TestSpecCompliance_ErrorResponse(t *testing.T) {
|
||||
resp := &ErrorResponse{
|
||||
Code: "INVALID_SOLUTION",
|
||||
Message: "The provided PoW solution is incorrect",
|
||||
RetryAfter: 30,
|
||||
Details: map[string]string{"reason": "hash verification failed"},
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
err := resp.Encode(&buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Skip header and get payload
|
||||
payload := buf.Bytes()[5:]
|
||||
|
||||
// Verify JSON payload matches spec format
|
||||
var decoded map[string]interface{}
|
||||
err = json.Unmarshal(payload, &decoded)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Check required fields from spec
|
||||
assert.Contains(t, decoded, "code")
|
||||
assert.Contains(t, decoded, "message")
|
||||
assert.Equal(t, "INVALID_SOLUTION", decoded["code"])
|
||||
assert.Equal(t, "The provided PoW solution is incorrect", decoded["message"])
|
||||
|
||||
// Check optional fields
|
||||
assert.Contains(t, decoded, "retry_after")
|
||||
assert.Contains(t, decoded, "details")
|
||||
assert.Equal(t, float64(30), decoded["retry_after"])
|
||||
}
|
||||
|
||||
// TestSpecCompliance_MessageSizeLimits verifies 8KB payload limit
|
||||
func TestSpecCompliance_MessageSizeLimits(t *testing.T) {
|
||||
decoder := NewMessageDecoder()
|
||||
|
||||
// Create a message that exceeds 8KB payload limit
|
||||
largePayload := make([]byte, MaxPayloadSize+1)
|
||||
for i := range largePayload {
|
||||
largePayload[i] = 'A'
|
||||
}
|
||||
|
||||
// Create message with oversized payload
|
||||
var buf bytes.Buffer
|
||||
buf.WriteByte(byte(ChallengeRequestType))
|
||||
buf.Write([]byte{0x00, 0x00, 0x20, 0x01}) // 8193 bytes (8KB + 1)
|
||||
buf.Write(largePayload)
|
||||
|
||||
// Should reject oversized payload
|
||||
_, err := decoder.Decode(&buf)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "payload length")
|
||||
assert.Contains(t, err.Error(), "exceeds maximum")
|
||||
}
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
package protocol
|
||||
|
||||
import "io"
|
||||
|
||||
// Message represents a protocol message with type and payload stream
|
||||
type Message struct {
|
||||
Type MessageType
|
||||
PayloadLength uint32
|
||||
PayloadStream io.Reader
|
||||
}
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
package quotes
|
||||
|
||||
type Quote struct {
|
||||
Text string `json:"text"`
|
||||
Author string `json:"author"`
|
||||
}
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
package quotes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
type HTTPService struct {
|
||||
client *resty.Client
|
||||
}
|
||||
|
||||
func NewHTTPService() *HTTPService {
|
||||
return &HTTPService{
|
||||
client: resty.New(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *HTTPService) GetRandomQuote(ctx context.Context) (*Quote, error) {
|
||||
var response []struct {
|
||||
Q string `json:"q"`
|
||||
A string `json:"a"`
|
||||
}
|
||||
|
||||
resp, err := s.client.R().
|
||||
SetContext(ctx).
|
||||
SetResult(&response).
|
||||
Get("https://zenquotes.io/api/random")
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to fetch quote: %w", err)
|
||||
}
|
||||
|
||||
if resp.IsError() {
|
||||
return nil, fmt.Errorf("API error: %s", resp.Status())
|
||||
}
|
||||
|
||||
if len(response) == 0 {
|
||||
return nil, fmt.Errorf("no quotes returned from API")
|
||||
}
|
||||
|
||||
return &Quote{
|
||||
Text: response[0].Q,
|
||||
Author: response[0].A,
|
||||
}, nil
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
package server
|
||||
|
||||
import "time"
|
||||
|
||||
// Config holds configuration for the TCP server
|
||||
type Config struct {
|
||||
Address string
|
||||
Timeouts TimeoutConfig
|
||||
}
|
||||
|
||||
// TimeoutConfig holds timeout configuration
|
||||
type TimeoutConfig struct {
|
||||
// Read timeout protects against slowloris attacks (clients sending data slowly)
|
||||
Read time.Duration
|
||||
// Write timeout protects against slow readers (clients reading responses slowly)
|
||||
Write time.Duration
|
||||
// Connection timeout is the maximum total connection lifetime
|
||||
Connection time.Duration
|
||||
}
|
||||
|
|
@ -1,234 +0,0 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"hash-of-wisdom/internal/application"
|
||||
"hash-of-wisdom/internal/lib/sl"
|
||||
"hash-of-wisdom/internal/metrics"
|
||||
"hash-of-wisdom/internal/protocol"
|
||||
"hash-of-wisdom/internal/service"
|
||||
)
|
||||
|
||||
// TCPServer handles TCP connections for the Word of Wisdom protocol
|
||||
type TCPServer struct {
|
||||
config *Config
|
||||
wisdomApplication *application.WisdomApplication
|
||||
decoder *protocol.MessageDecoder
|
||||
listener net.Listener
|
||||
logger *slog.Logger
|
||||
wg sync.WaitGroup
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// Option is a functional option for configuring TCPServer
|
||||
type option func(*TCPServer)
|
||||
|
||||
// WithLogger sets a custom logger
|
||||
func WithLogger(logger *slog.Logger) option {
|
||||
return func(s *TCPServer) {
|
||||
s.logger = logger
|
||||
}
|
||||
}
|
||||
|
||||
// NewTCPServer creates a new TCP server with required configuration
|
||||
func NewTCPServer(wisdomService *service.WisdomService, config *Config, opts ...option) *TCPServer {
|
||||
server := &TCPServer{
|
||||
config: config,
|
||||
wisdomApplication: application.NewWisdomApplication(wisdomService),
|
||||
decoder: protocol.NewMessageDecoder(),
|
||||
logger: slog.Default(),
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(server)
|
||||
}
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
// Start starts the TCP server
|
||||
func (s *TCPServer) Start(ctx context.Context) error {
|
||||
listener, err := net.Listen("tcp", s.config.Address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to listen on %s: %w", s.config.Address, err)
|
||||
}
|
||||
|
||||
s.listener = listener
|
||||
s.logger.Info("tcp server started", "address", s.config.Address)
|
||||
|
||||
// Create cancellable context for server lifecycle
|
||||
serverCtx, cancel := context.WithCancel(ctx)
|
||||
s.cancel = cancel
|
||||
|
||||
go s.acceptLoop(serverCtx)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop gracefully stops the server
|
||||
func (s *TCPServer) Stop() error {
|
||||
s.logger.Info("stopping tcp server")
|
||||
|
||||
// Cancel server context to stop accept loop and active connections
|
||||
if s.cancel != nil {
|
||||
s.cancel()
|
||||
}
|
||||
|
||||
if s.listener != nil {
|
||||
s.listener.Close()
|
||||
}
|
||||
|
||||
s.wg.Wait()
|
||||
s.logger.Info("tcp server stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Address returns the server's listening address
|
||||
func (s *TCPServer) Address() string {
|
||||
if s.listener != nil {
|
||||
return s.listener.Addr().String()
|
||||
}
|
||||
return s.config.Address
|
||||
}
|
||||
|
||||
// acceptLoop accepts and handles incoming connections
|
||||
func (s *TCPServer) acceptLoop(ctx context.Context) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
rawConn, err := s.listener.Accept()
|
||||
if err != nil {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
s.logger.Error("accept error", sl.Err(err))
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
s.wg.Add(1)
|
||||
go func() {
|
||||
defer s.wg.Done()
|
||||
s.handleConnection(ctx, rawConn)
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// handleConnection handles a single client connection
|
||||
func (s *TCPServer) handleConnection(ctx context.Context, rawConn net.Conn) {
|
||||
defer rawConn.Close()
|
||||
|
||||
// Track active connections
|
||||
metrics.ActiveConnections.Inc()
|
||||
defer metrics.ActiveConnections.Dec()
|
||||
|
||||
connLogger := s.logger.With("remote_addr", rawConn.RemoteAddr().String())
|
||||
connLogger.Info("connection accepted")
|
||||
|
||||
// Create connection-scoped context for overall timeout
|
||||
connCtx, cancel := context.WithTimeout(ctx, s.config.Timeouts.Connection)
|
||||
defer cancel()
|
||||
|
||||
if err := s.processConnection(connCtx, rawConn, connLogger); err != nil {
|
||||
connLogger.Error("connection error", sl.Err(err))
|
||||
} else {
|
||||
connLogger.Debug("connection completed successfully")
|
||||
}
|
||||
}
|
||||
|
||||
// deadlineConn wraps a connection to automatically set deadlines on each read/write
|
||||
type deadlineConn struct {
|
||||
net.Conn
|
||||
rto, wto time.Duration
|
||||
}
|
||||
|
||||
func (d *deadlineConn) Read(p []byte) (int, error) {
|
||||
_ = d.SetReadDeadline(time.Now().Add(d.rto))
|
||||
return d.Conn.Read(p)
|
||||
}
|
||||
|
||||
func (d *deadlineConn) Write(p []byte) (int, error) {
|
||||
_ = d.SetWriteDeadline(time.Now().Add(d.wto))
|
||||
return d.Conn.Write(p)
|
||||
}
|
||||
|
||||
// processConnection handles the protocol message exchange
|
||||
func (s *TCPServer) processConnection(ctx context.Context, conn net.Conn, logger *slog.Logger) error {
|
||||
// Set overall connection deadline
|
||||
globalDL := time.Now().Add(s.config.Timeouts.Connection)
|
||||
if err := conn.SetDeadline(globalDL); err != nil {
|
||||
return fmt.Errorf("failed to set connection deadline: %w", err)
|
||||
}
|
||||
|
||||
// Create deadline wrapper for automatic timeout handling
|
||||
dc := &deadlineConn{
|
||||
Conn: conn,
|
||||
rto: s.config.Timeouts.Read,
|
||||
wto: s.config.Timeouts.Write,
|
||||
}
|
||||
|
||||
// Use LimitReader to prevent reading more than the protocol-defined maximum message size
|
||||
// This protects against malicious clients that lie about payload length in headers
|
||||
limitedReader := io.LimitReader(dc, int64(protocol.MaxPayloadSize)+protocol.HeaderSize)
|
||||
|
||||
// Read incoming message through limited reader
|
||||
logger.Debug("reading message from client")
|
||||
msg, err := s.decoder.Decode(limitedReader)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
logger.Debug("client closed connection gracefully")
|
||||
return nil
|
||||
}
|
||||
metrics.RequestErrors.WithLabelValues("decode_error").Inc()
|
||||
logger.Error("failed to decode message", sl.Err(err))
|
||||
return fmt.Errorf("decode error: %w", err)
|
||||
}
|
||||
|
||||
logger.Debug("message decoded", "type", msg.Type, "payload_length", msg.PayloadLength)
|
||||
|
||||
// Track all requests
|
||||
metrics.RequestsTotal.Inc()
|
||||
|
||||
// Process message through application layer with timing
|
||||
start := time.Now()
|
||||
response, err := s.wisdomApplication.HandleMessage(ctx, msg)
|
||||
duration := time.Since(start)
|
||||
metrics.RequestDuration.Observe(duration.Seconds())
|
||||
|
||||
if err != nil {
|
||||
metrics.RequestErrors.WithLabelValues("internal_error").Inc()
|
||||
logger.Error("application error", sl.Err(err))
|
||||
return fmt.Errorf("application error: %w", err)
|
||||
}
|
||||
|
||||
// Check if response is an error response
|
||||
if errorResp, isError := response.(*protocol.ErrorResponse); isError {
|
||||
metrics.RequestErrors.WithLabelValues(string(errorResp.Code)).Inc()
|
||||
} else {
|
||||
// Track quotes served for successful solution requests
|
||||
if msg.Type == protocol.SolutionRequestType {
|
||||
metrics.QuotesServed.Inc()
|
||||
}
|
||||
}
|
||||
|
||||
logger.Debug("sending response to client")
|
||||
// Send response using the response's own Encode method
|
||||
if err := response.Encode(dc); err != nil {
|
||||
logger.Error("failed to encode response", sl.Err(err))
|
||||
return fmt.Errorf("encode error: %w", err)
|
||||
}
|
||||
|
||||
logger.Debug("response sent successfully")
|
||||
return nil
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
package service
|
||||
|
||||
import "hash-of-wisdom/internal/pow/challenge"
|
||||
|
||||
// generatorAdapter adapts the real challenge.Generator to our interface
|
||||
type generatorAdapter struct {
|
||||
generator *challenge.Generator
|
||||
}
|
||||
|
||||
func NewGeneratorAdapter(generator *challenge.Generator) ChallengeGenerator {
|
||||
return &generatorAdapter{generator: generator}
|
||||
}
|
||||
|
||||
func (a *generatorAdapter) GenerateChallenge() (*challenge.Challenge, error) {
|
||||
return a.generator.GenerateChallenge()
|
||||
}
|
||||
|
|
@ -1,93 +0,0 @@
|
|||
// Code generated by mockery v2.53.5. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
challenge "hash-of-wisdom/internal/pow/challenge"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// MockChallengeGenerator is an autogenerated mock type for the ChallengeGenerator type
|
||||
type MockChallengeGenerator struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockChallengeGenerator_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockChallengeGenerator) EXPECT() *MockChallengeGenerator_Expecter {
|
||||
return &MockChallengeGenerator_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// GenerateChallenge provides a mock function with no fields
|
||||
func (_m *MockChallengeGenerator) GenerateChallenge() (*challenge.Challenge, error) {
|
||||
ret := _m.Called()
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GenerateChallenge")
|
||||
}
|
||||
|
||||
var r0 *challenge.Challenge
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(0).(func() (*challenge.Challenge, error)); ok {
|
||||
return rf()
|
||||
}
|
||||
if rf, ok := ret.Get(0).(func() *challenge.Challenge); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(*challenge.Challenge)
|
||||
}
|
||||
}
|
||||
|
||||
if rf, ok := ret.Get(1).(func() error); ok {
|
||||
r1 = rf()
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockChallengeGenerator_GenerateChallenge_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GenerateChallenge'
|
||||
type MockChallengeGenerator_GenerateChallenge_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GenerateChallenge is a helper method to define mock.On call
|
||||
func (_e *MockChallengeGenerator_Expecter) GenerateChallenge() *MockChallengeGenerator_GenerateChallenge_Call {
|
||||
return &MockChallengeGenerator_GenerateChallenge_Call{Call: _e.mock.On("GenerateChallenge")}
|
||||
}
|
||||
|
||||
func (_c *MockChallengeGenerator_GenerateChallenge_Call) Run(run func()) *MockChallengeGenerator_GenerateChallenge_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run()
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChallengeGenerator_GenerateChallenge_Call) Return(_a0 *challenge.Challenge, _a1 error) *MockChallengeGenerator_GenerateChallenge_Call {
|
||||
_c.Call.Return(_a0, _a1)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChallengeGenerator_GenerateChallenge_Call) RunAndReturn(run func() (*challenge.Challenge, error)) *MockChallengeGenerator_GenerateChallenge_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// NewMockChallengeGenerator creates a new instance of MockChallengeGenerator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockChallengeGenerator(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockChallengeGenerator {
|
||||
mock := &MockChallengeGenerator{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() { mock.AssertExpectations(t) })
|
||||
|
||||
return mock
|
||||
}
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
// Code generated by mockery v2.53.5. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
challenge "hash-of-wisdom/internal/pow/challenge"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// MockChallengeVerifier is an autogenerated mock type for the ChallengeVerifier type
|
||||
type MockChallengeVerifier struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockChallengeVerifier_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockChallengeVerifier) EXPECT() *MockChallengeVerifier_Expecter {
|
||||
return &MockChallengeVerifier_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// VerifyChallenge provides a mock function with given fields: ch
|
||||
func (_m *MockChallengeVerifier) VerifyChallenge(ch *challenge.Challenge) error {
|
||||
ret := _m.Called(ch)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for VerifyChallenge")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(*challenge.Challenge) error); ok {
|
||||
r0 = rf(ch)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockChallengeVerifier_VerifyChallenge_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyChallenge'
|
||||
type MockChallengeVerifier_VerifyChallenge_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// VerifyChallenge is a helper method to define mock.On call
|
||||
// - ch *challenge.Challenge
|
||||
func (_e *MockChallengeVerifier_Expecter) VerifyChallenge(ch interface{}) *MockChallengeVerifier_VerifyChallenge_Call {
|
||||
return &MockChallengeVerifier_VerifyChallenge_Call{Call: _e.mock.On("VerifyChallenge", ch)}
|
||||
}
|
||||
|
||||
func (_c *MockChallengeVerifier_VerifyChallenge_Call) Run(run func(ch *challenge.Challenge)) *MockChallengeVerifier_VerifyChallenge_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(*challenge.Challenge))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChallengeVerifier_VerifyChallenge_Call) Return(_a0 error) *MockChallengeVerifier_VerifyChallenge_Call {
|
||||
_c.Call.Return(_a0)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChallengeVerifier_VerifyChallenge_Call) RunAndReturn(run func(*challenge.Challenge) error) *MockChallengeVerifier_VerifyChallenge_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// NewMockChallengeVerifier creates a new instance of MockChallengeVerifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockChallengeVerifier(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockChallengeVerifier {
|
||||
mock := &MockChallengeVerifier{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() { mock.AssertExpectations(t) })
|
||||
|
||||
return mock
|
||||
}
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
// Code generated by mockery v2.53.5. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
context "context"
|
||||
quotes "hash-of-wisdom/internal/quotes"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// MockQuoteService is an autogenerated mock type for the QuoteService type
|
||||
type MockQuoteService struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockQuoteService_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockQuoteService) EXPECT() *MockQuoteService_Expecter {
|
||||
return &MockQuoteService_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// GetRandomQuote provides a mock function with given fields: ctx
|
||||
func (_m *MockQuoteService) GetRandomQuote(ctx context.Context) (*quotes.Quote, error) {
|
||||
ret := _m.Called(ctx)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetRandomQuote")
|
||||
}
|
||||
|
||||
var r0 *quotes.Quote
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(0).(func(context.Context) (*quotes.Quote, error)); ok {
|
||||
return rf(ctx)
|
||||
}
|
||||
if rf, ok := ret.Get(0).(func(context.Context) *quotes.Quote); ok {
|
||||
r0 = rf(ctx)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(*quotes.Quote)
|
||||
}
|
||||
}
|
||||
|
||||
if rf, ok := ret.Get(1).(func(context.Context) error); ok {
|
||||
r1 = rf(ctx)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockQuoteService_GetRandomQuote_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRandomQuote'
|
||||
type MockQuoteService_GetRandomQuote_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetRandomQuote is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
func (_e *MockQuoteService_Expecter) GetRandomQuote(ctx interface{}) *MockQuoteService_GetRandomQuote_Call {
|
||||
return &MockQuoteService_GetRandomQuote_Call{Call: _e.mock.On("GetRandomQuote", ctx)}
|
||||
}
|
||||
|
||||
func (_c *MockQuoteService_GetRandomQuote_Call) Run(run func(ctx context.Context)) *MockQuoteService_GetRandomQuote_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run(args[0].(context.Context))
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockQuoteService_GetRandomQuote_Call) Return(_a0 *quotes.Quote, _a1 error) *MockQuoteService_GetRandomQuote_Call {
|
||||
_c.Call.Return(_a0, _a1)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockQuoteService_GetRandomQuote_Call) RunAndReturn(run func(context.Context) (*quotes.Quote, error)) *MockQuoteService_GetRandomQuote_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// NewMockQuoteService creates a new instance of MockQuoteService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockQuoteService(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockQuoteService {
|
||||
mock := &MockQuoteService{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() { mock.AssertExpectations(t) })
|
||||
|
||||
return mock
|
||||
}
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/quotes"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrResourceRequired = errors.New("resource is required")
|
||||
ErrUnsupportedResource = errors.New("unsupported resource")
|
||||
ErrSolutionRequired = errors.New("solution is required")
|
||||
ErrInvalidChallenge = errors.New("invalid challenge")
|
||||
ErrInvalidSolution = errors.New("invalid proof of work solution")
|
||||
)
|
||||
|
||||
type ChallengeGenerator interface {
|
||||
GenerateChallenge() (*challenge.Challenge, error)
|
||||
}
|
||||
|
||||
type ChallengeVerifier interface {
|
||||
VerifyChallenge(ch *challenge.Challenge) error
|
||||
}
|
||||
|
||||
type QuoteService interface {
|
||||
GetRandomQuote(ctx context.Context) (*quotes.Quote, error)
|
||||
}
|
||||
|
||||
type WisdomService struct {
|
||||
challengeGenerator ChallengeGenerator
|
||||
challengeVerifier ChallengeVerifier
|
||||
quoteService QuoteService
|
||||
}
|
||||
|
||||
func NewWisdomService(
|
||||
generator ChallengeGenerator,
|
||||
verifier ChallengeVerifier,
|
||||
quoteService QuoteService,
|
||||
) *WisdomService {
|
||||
return &WisdomService{
|
||||
challengeGenerator: generator,
|
||||
challengeVerifier: verifier,
|
||||
quoteService: quoteService,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *WisdomService) GenerateChallenge(ctx context.Context, resource string) (*challenge.Challenge, error) {
|
||||
if resource == "" {
|
||||
return nil, ErrResourceRequired
|
||||
}
|
||||
|
||||
if resource != "quotes" {
|
||||
return nil, ErrUnsupportedResource
|
||||
}
|
||||
|
||||
ch, err := s.challengeGenerator.GenerateChallenge()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate challenge: %w", err)
|
||||
}
|
||||
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (s *WisdomService) VerifySolution(ctx context.Context, solution *challenge.Solution) error {
|
||||
if solution == nil {
|
||||
return ErrSolutionRequired
|
||||
}
|
||||
|
||||
// Verify challenge authenticity and expiration
|
||||
if err := s.challengeVerifier.VerifyChallenge(&solution.Challenge); err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrInvalidChallenge, err)
|
||||
}
|
||||
|
||||
// Verify PoW solution
|
||||
if !solution.Verify() {
|
||||
return ErrInvalidSolution
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *WisdomService) GetQuote(ctx context.Context) (*quotes.Quote, error) {
|
||||
return s.quoteService.GetRandomQuote(ctx)
|
||||
}
|
||||
|
|
@ -1,186 +0,0 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/quotes"
|
||||
"hash-of-wisdom/internal/service/mocks"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
func TestWisdomService_GenerateChallenge(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
resource string
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "valid resource",
|
||||
resource: "quotes",
|
||||
wantErr: nil,
|
||||
},
|
||||
{
|
||||
name: "empty resource",
|
||||
resource: "",
|
||||
wantErr: ErrResourceRequired,
|
||||
},
|
||||
{
|
||||
name: "unsupported resource",
|
||||
resource: "invalid",
|
||||
wantErr: ErrUnsupportedResource,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockGen := mocks.NewMockChallengeGenerator(t)
|
||||
mockVer := mocks.NewMockChallengeVerifier(t)
|
||||
mockQuote := mocks.NewMockQuoteService(t)
|
||||
|
||||
service := NewWisdomService(mockGen, mockVer, mockQuote)
|
||||
|
||||
if tt.wantErr == nil {
|
||||
expectedChallenge := &challenge.Challenge{
|
||||
Timestamp: time.Now().Unix(),
|
||||
Difficulty: 4,
|
||||
Resource: "quotes",
|
||||
Random: []byte{0x01, 0x02, 0x03},
|
||||
}
|
||||
mockGen.EXPECT().GenerateChallenge().Return(expectedChallenge, nil).Once()
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ch, err := service.GenerateChallenge(ctx, tt.resource)
|
||||
|
||||
if tt.wantErr != nil {
|
||||
assert.ErrorIs(t, err, tt.wantErr)
|
||||
assert.Nil(t, ch)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, ch)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWisdomService_VerifySolution(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
solution *challenge.Solution
|
||||
wantErr error
|
||||
setupMocks func(*mocks.MockChallengeVerifier)
|
||||
}{
|
||||
{
|
||||
name: "nil solution",
|
||||
solution: nil,
|
||||
wantErr: ErrSolutionRequired,
|
||||
setupMocks: func(mv *mocks.MockChallengeVerifier) {},
|
||||
},
|
||||
{
|
||||
name: "invalid challenge",
|
||||
solution: &challenge.Solution{
|
||||
Challenge: challenge.Challenge{},
|
||||
Nonce: 123,
|
||||
},
|
||||
wantErr: ErrInvalidChallenge,
|
||||
setupMocks: func(mv *mocks.MockChallengeVerifier) {
|
||||
mv.EXPECT().VerifyChallenge(mock.Anything).Return(challenge.ErrInvalidHMAC).Once()
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "invalid solution",
|
||||
solution: createInvalidSolution(t),
|
||||
wantErr: ErrInvalidSolution,
|
||||
setupMocks: func(mv *mocks.MockChallengeVerifier) {
|
||||
mv.EXPECT().VerifyChallenge(mock.Anything).Return(nil).Once()
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "valid solution",
|
||||
solution: createValidSolution(t),
|
||||
wantErr: nil,
|
||||
setupMocks: func(mv *mocks.MockChallengeVerifier) {
|
||||
mv.EXPECT().VerifyChallenge(mock.Anything).Return(nil).Once()
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mockGen := mocks.NewMockChallengeGenerator(t)
|
||||
mockVer := mocks.NewMockChallengeVerifier(t)
|
||||
mockQuote := mocks.NewMockQuoteService(t)
|
||||
|
||||
tt.setupMocks(mockVer)
|
||||
|
||||
service := NewWisdomService(mockGen, mockVer, mockQuote)
|
||||
|
||||
ctx := context.Background()
|
||||
err := service.VerifySolution(ctx, tt.solution)
|
||||
|
||||
if tt.wantErr != nil {
|
||||
assert.ErrorIs(t, err, tt.wantErr)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWisdomService_GetQuote(t *testing.T) {
|
||||
mockGen := mocks.NewMockChallengeGenerator(t)
|
||||
mockVer := mocks.NewMockChallengeVerifier(t)
|
||||
mockQuote := mocks.NewMockQuoteService(t)
|
||||
|
||||
expectedQuote := "es.Quote{
|
||||
Text: "Test quote",
|
||||
Author: "Test author",
|
||||
}
|
||||
|
||||
mockQuote.EXPECT().GetRandomQuote(mock.Anything).Return(expectedQuote, nil).Once()
|
||||
|
||||
service := NewWisdomService(mockGen, mockVer, mockQuote)
|
||||
|
||||
ctx := context.Background()
|
||||
quote, err := service.GetQuote(ctx)
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expectedQuote, quote)
|
||||
}
|
||||
|
||||
func createValidSolution(t *testing.T) *challenge.Solution {
|
||||
config := challenge.TestConfig()
|
||||
ch := &challenge.Challenge{
|
||||
Timestamp: time.Now().Unix(),
|
||||
Difficulty: 0, // Difficulty 0 means any nonce works
|
||||
Resource: "quotes",
|
||||
Random: []byte{0x01, 0x02, 0x03},
|
||||
}
|
||||
ch.Sign(config.HMACSecret)
|
||||
|
||||
return &challenge.Solution{
|
||||
Challenge: *ch,
|
||||
Nonce: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func createInvalidSolution(t *testing.T) *challenge.Solution {
|
||||
config := challenge.TestConfig()
|
||||
ch := &challenge.Challenge{
|
||||
Timestamp: time.Now().Unix(),
|
||||
Difficulty: 20, // High difficulty, nonce 999 won't work
|
||||
Resource: "quotes",
|
||||
Random: []byte{0x01, 0x02, 0x03},
|
||||
}
|
||||
ch.Sign(config.HMACSecret)
|
||||
|
||||
return &challenge.Solution{
|
||||
Challenge: *ch,
|
||||
Nonce: 999, // Wrong nonce for difficulty 20
|
||||
}
|
||||
}
|
||||
|
|
@ -1,370 +0,0 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/pow/solver"
|
||||
"hash-of-wisdom/internal/quotes"
|
||||
"hash-of-wisdom/internal/service/mocks"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestWisdomService_FullWorkflowTests(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
resource string
|
||||
difficulty int
|
||||
setupQuote func(*mocks.MockQuoteService)
|
||||
wantErr bool
|
||||
expectQuote bool
|
||||
}{
|
||||
{
|
||||
name: "successful flow with difficulty 1",
|
||||
resource: "quotes",
|
||||
difficulty: 1,
|
||||
setupQuote: func(m *mocks.MockQuoteService) {
|
||||
m.EXPECT().GetRandomQuote(context.Background()).Return("es.Quote{
|
||||
Text: "Success quote",
|
||||
Author: "Test Author",
|
||||
}, nil).Once()
|
||||
},
|
||||
wantErr: false,
|
||||
expectQuote: true,
|
||||
},
|
||||
{
|
||||
name: "successful flow with difficulty 2",
|
||||
resource: "quotes",
|
||||
difficulty: 2,
|
||||
setupQuote: func(m *mocks.MockQuoteService) {
|
||||
m.EXPECT().GetRandomQuote(context.Background()).Return("es.Quote{
|
||||
Text: "Another quote",
|
||||
Author: "Another Author",
|
||||
}, nil).Once()
|
||||
},
|
||||
wantErr: false,
|
||||
expectQuote: true,
|
||||
},
|
||||
{
|
||||
name: "successful flow with difficulty 3",
|
||||
resource: "quotes",
|
||||
difficulty: 3,
|
||||
setupQuote: func(m *mocks.MockQuoteService) {
|
||||
m.EXPECT().GetRandomQuote(context.Background()).Return("es.Quote{
|
||||
Text: "Hard quote",
|
||||
Author: "Hard Author",
|
||||
}, nil).Once()
|
||||
},
|
||||
wantErr: false,
|
||||
expectQuote: true,
|
||||
},
|
||||
{
|
||||
name: "invalid resource",
|
||||
resource: "invalid",
|
||||
difficulty: 1,
|
||||
setupQuote: func(m *mocks.MockQuoteService) {
|
||||
// No expectations - should not reach quote service
|
||||
},
|
||||
wantErr: true,
|
||||
expectQuote: false,
|
||||
},
|
||||
{
|
||||
name: "empty resource",
|
||||
resource: "",
|
||||
difficulty: 1,
|
||||
setupQuote: func(m *mocks.MockQuoteService) {
|
||||
// No expectations - should not reach quote service
|
||||
},
|
||||
wantErr: true,
|
||||
expectQuote: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Create real PoW components
|
||||
config, err := challenge.NewConfig(
|
||||
challenge.WithDefaultDifficulty(tt.difficulty),
|
||||
challenge.WithMinDifficulty(1),
|
||||
challenge.WithMaxDifficulty(10),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
generator := challenge.NewGenerator(config)
|
||||
verifier := challenge.NewVerifier(config)
|
||||
powSolver := solver.NewSolver(solver.WithWorkers(2))
|
||||
|
||||
// Mock quote service
|
||||
mockQuote := mocks.NewMockQuoteService(t)
|
||||
tt.setupQuote(mockQuote)
|
||||
|
||||
// Create service
|
||||
service := NewWisdomService(NewGeneratorAdapter(generator), verifier, mockQuote)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Step 1: Generate challenge
|
||||
ch, err := service.GenerateChallenge(ctx, tt.resource)
|
||||
if tt.wantErr && (tt.resource == "" || tt.resource != "quotes") {
|
||||
assert.Error(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, ch)
|
||||
|
||||
// Challenge generated successfully (HMAC ensures integrity)
|
||||
|
||||
// Step 2: Solve the challenge
|
||||
solveCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
solution, err := powSolver.Solve(solveCtx, ch)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, solution)
|
||||
|
||||
// Step 3: Verify solution through service
|
||||
err = service.VerifySolution(ctx, solution)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Step 4: Get quote
|
||||
if tt.expectQuote {
|
||||
quote, err := service.GetQuote(ctx)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, quote)
|
||||
assert.NotEmpty(t, quote.Text)
|
||||
assert.NotEmpty(t, quote.Author)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWisdomService_FullWorkflow_MultipleRounds(t *testing.T) {
|
||||
// Test multiple consecutive challenge-solve-quote cycles
|
||||
config, err := challenge.NewConfig(
|
||||
challenge.WithDefaultDifficulty(2),
|
||||
challenge.WithMinDifficulty(1),
|
||||
challenge.WithMaxDifficulty(5),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
generator := challenge.NewGenerator(config)
|
||||
verifier := challenge.NewVerifier(config)
|
||||
powSolver := solver.NewSolver(solver.WithWorkers(1))
|
||||
mockQuote := mocks.NewMockQuoteService(t)
|
||||
|
||||
// Setup expectations for 3 rounds
|
||||
quotes := []*quotes.Quote{
|
||||
{Text: "First quote", Author: "Author 1"},
|
||||
{Text: "Second quote", Author: "Author 2"},
|
||||
{Text: "Third quote", Author: "Author 3"},
|
||||
}
|
||||
|
||||
for _, quote := range quotes {
|
||||
mockQuote.EXPECT().GetRandomQuote(context.Background()).Return(quote, nil).Once()
|
||||
}
|
||||
|
||||
service := NewWisdomService(NewGeneratorAdapter(generator), verifier, mockQuote)
|
||||
ctx := context.Background()
|
||||
|
||||
// Run 3 complete cycles
|
||||
for i, expectedQuote := range quotes {
|
||||
t.Run(fmt.Sprintf("round_%d", i+1), func(t *testing.T) {
|
||||
// Generate challenge
|
||||
ch, err := service.GenerateChallenge(ctx, "quotes")
|
||||
require.NoError(t, err)
|
||||
|
||||
// Solve challenge
|
||||
solveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
solution, err := powSolver.Solve(solveCtx, ch)
|
||||
cancel()
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify solution
|
||||
err = service.VerifySolution(ctx, solution)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Get quote
|
||||
quote, err := service.GetQuote(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, expectedQuote.Text, quote.Text)
|
||||
assert.Equal(t, expectedQuote.Author, quote.Author)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWisdomService_InvalidSolutions(t *testing.T) {
|
||||
config, err := challenge.NewConfig(
|
||||
challenge.WithDefaultDifficulty(3),
|
||||
challenge.WithMinDifficulty(1),
|
||||
challenge.WithMaxDifficulty(10),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
generator := challenge.NewGenerator(config)
|
||||
verifier := challenge.NewVerifier(config)
|
||||
powSolver := solver.NewSolver(solver.WithWorkers(1))
|
||||
mockQuote := mocks.NewMockQuoteService(t)
|
||||
|
||||
service := NewWisdomService(NewGeneratorAdapter(generator), verifier, mockQuote)
|
||||
ctx := context.Background()
|
||||
|
||||
// Generate a valid challenge
|
||||
ch, err := service.GenerateChallenge(ctx, "quotes")
|
||||
require.NoError(t, err)
|
||||
|
||||
// Solve it properly
|
||||
solveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
validSolution, err := powSolver.Solve(solveCtx, ch)
|
||||
cancel()
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
solution *challenge.Solution
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "nil solution",
|
||||
solution: nil,
|
||||
wantErr: ErrSolutionRequired,
|
||||
},
|
||||
{
|
||||
name: "tampered challenge",
|
||||
solution: &challenge.Solution{
|
||||
Challenge: challenge.Challenge{
|
||||
Timestamp: ch.Timestamp,
|
||||
Difficulty: ch.Difficulty + 1, // Tampered
|
||||
Resource: ch.Resource,
|
||||
Random: ch.Random,
|
||||
HMAC: ch.HMAC, // Original HMAC won't match tampered data
|
||||
},
|
||||
Nonce: validSolution.Nonce,
|
||||
},
|
||||
wantErr: ErrInvalidChallenge,
|
||||
},
|
||||
{
|
||||
name: "wrong nonce",
|
||||
solution: &challenge.Solution{
|
||||
Challenge: *ch,
|
||||
Nonce: validSolution.Nonce + 1, // Wrong nonce
|
||||
},
|
||||
wantErr: ErrInvalidSolution,
|
||||
},
|
||||
{
|
||||
name: "expired challenge",
|
||||
solution: func() *challenge.Solution {
|
||||
expiredCh := &challenge.Challenge{
|
||||
Timestamp: time.Now().Add(-10 * time.Minute).Unix(), // Expired
|
||||
Difficulty: ch.Difficulty,
|
||||
Resource: ch.Resource,
|
||||
Random: ch.Random,
|
||||
}
|
||||
expiredCh.Sign(config.HMACSecret)
|
||||
return &challenge.Solution{
|
||||
Challenge: *expiredCh,
|
||||
Nonce: 0, // Difficulty doesn't matter since it will fail on expiry
|
||||
}
|
||||
}(),
|
||||
wantErr: ErrInvalidChallenge,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := service.VerifySolution(ctx, tt.solution)
|
||||
assert.ErrorIs(t, err, tt.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWisdomService_UnsuccessfulFlows(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
difficulty int
|
||||
createSolution func(*challenge.Challenge, *challenge.Solution) *challenge.Solution
|
||||
}{
|
||||
{
|
||||
name: "tampered solution",
|
||||
difficulty: 2,
|
||||
createSolution: func(ch *challenge.Challenge, validSolution *challenge.Solution) *challenge.Solution {
|
||||
return &challenge.Solution{
|
||||
Challenge: challenge.Challenge{
|
||||
Timestamp: ch.Timestamp,
|
||||
Difficulty: ch.Difficulty + 1, // Tampered
|
||||
Resource: ch.Resource,
|
||||
Random: ch.Random,
|
||||
HMAC: ch.HMAC, // Original HMAC won't match tampered data
|
||||
},
|
||||
Nonce: validSolution.Nonce,
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "wrong nonce",
|
||||
difficulty: 3,
|
||||
createSolution: func(ch *challenge.Challenge, validSolution *challenge.Solution) *challenge.Solution {
|
||||
return &challenge.Solution{
|
||||
Challenge: *ch,
|
||||
Nonce: 999999, // Wrong nonce
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Create real PoW components
|
||||
config, err := challenge.NewConfig(
|
||||
challenge.WithDefaultDifficulty(tt.difficulty),
|
||||
challenge.WithMinDifficulty(1),
|
||||
challenge.WithMaxDifficulty(10),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
generator := challenge.NewGenerator(config)
|
||||
verifier := challenge.NewVerifier(config)
|
||||
powSolver := solver.NewSolver(solver.WithWorkers(2))
|
||||
|
||||
// Mock quote service - should not be called
|
||||
mockQuote := mocks.NewMockQuoteService(t)
|
||||
// No expectations - service should not reach quote fetching
|
||||
|
||||
// Create service
|
||||
service := NewWisdomService(NewGeneratorAdapter(generator), verifier, mockQuote)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Step 1: Generate challenge
|
||||
ch, err := service.GenerateChallenge(ctx, "quotes")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, ch)
|
||||
|
||||
// Step 2: Get a valid solution first (for tampering tests)
|
||||
solveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
validSolution, err := powSolver.Solve(solveCtx, ch)
|
||||
cancel()
|
||||
require.NoError(t, err)
|
||||
|
||||
// Step 3: Create invalid solution
|
||||
invalidSolution := tt.createSolution(ch, validSolution)
|
||||
|
||||
// Step 4: Verify solution should fail
|
||||
err = service.VerifySolution(ctx, invalidSolution)
|
||||
require.Error(t, err)
|
||||
|
||||
// Verify error type based on test case
|
||||
if tt.name == "tampered solution" {
|
||||
require.ErrorIs(t, err, ErrInvalidChallenge)
|
||||
} else if tt.name == "wrong nonce" {
|
||||
require.ErrorIs(t, err, ErrInvalidSolution)
|
||||
}
|
||||
|
||||
// Quote service should never be called in unsuccessful flows
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1,56 +0,0 @@
|
|||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hash-of-wisdom/internal/lib/sl"
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/quotes"
|
||||
"hash-of-wisdom/internal/server"
|
||||
"hash-of-wisdom/internal/service"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// testQuoteService provides static quotes for testing
|
||||
type testQuoteService struct{}
|
||||
|
||||
func (s *testQuoteService) GetRandomQuote(ctx context.Context) (*quotes.Quote, error) {
|
||||
return "es.Quote{
|
||||
Text: "Test quote for integration testing",
|
||||
Author: "Test Author",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func setupTestServerWithConfig(t *testing.T, serverConfig *server.Config) *server.TCPServer {
|
||||
// Create test components
|
||||
challengeConfig := challenge.TestConfig()
|
||||
generator := challenge.NewGenerator(challengeConfig)
|
||||
verifier := challenge.NewVerifier(challengeConfig)
|
||||
|
||||
// Create a simple test quote service
|
||||
quoteService := &testQuoteService{}
|
||||
|
||||
// Wire up service
|
||||
genAdapter := service.NewGeneratorAdapter(generator)
|
||||
wisdomService := service.NewWisdomService(genAdapter, verifier, quoteService)
|
||||
|
||||
// Create server with custom config using functional options
|
||||
logger := sl.NewMockLogger()
|
||||
srv := server.NewTCPServer(wisdomService, serverConfig,
|
||||
server.WithLogger(logger))
|
||||
|
||||
// Start server
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
|
||||
err := srv.Start(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Give server time to start
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
return srv
|
||||
}
|
||||
|
|
@ -1,114 +0,0 @@
|
|||
package integration
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hash-of-wisdom/internal/server"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSlowlorisProtection_SlowReader(t *testing.T) {
|
||||
// Setup server with very short read timeout for testing
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 100 * time.Millisecond,
|
||||
Write: 5 * time.Second,
|
||||
Connection: 15 * time.Second,
|
||||
},
|
||||
}
|
||||
|
||||
srv := setupTestServerWithConfig(t, serverConfig)
|
||||
defer srv.Stop()
|
||||
|
||||
// Connect to server
|
||||
conn, err := net.Dial("tcp", srv.Address())
|
||||
require.NoError(t, err)
|
||||
defer conn.Close()
|
||||
|
||||
// Send partial message header very slowly (slowloris attack)
|
||||
_, err = conn.Write([]byte{0x01}) // Challenge request type
|
||||
require.NoError(t, err)
|
||||
|
||||
// Wait longer than read timeout before sending length
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
|
||||
// Try to send more data - connection should be timed out
|
||||
_, err = conn.Write([]byte{0x00, 0x00, 0x00, 0x00}) // Payload length
|
||||
|
||||
// Verify connection is closed by trying to read
|
||||
buffer := make([]byte, 1024)
|
||||
conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
|
||||
_, err = conn.Read(buffer)
|
||||
assert.Error(t, err, "Connection should be closed due to slow reading")
|
||||
}
|
||||
|
||||
func TestSlowlorisProtection_SlowConnectionTimeout(t *testing.T) {
|
||||
// Setup server with very short connection timeout for testing
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 5 * time.Second,
|
||||
Write: 5 * time.Second,
|
||||
Connection: 200 * time.Millisecond,
|
||||
},
|
||||
}
|
||||
|
||||
srv := setupTestServerWithConfig(t, serverConfig)
|
||||
defer srv.Stop()
|
||||
|
||||
// Connect to server but do nothing
|
||||
conn, err := net.Dial("tcp", srv.Address())
|
||||
require.NoError(t, err)
|
||||
defer conn.Close()
|
||||
|
||||
// Wait longer than connection timeout
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
|
||||
// Try to read - connection should be closed
|
||||
buffer := make([]byte, 1024)
|
||||
conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
|
||||
_, err = conn.Read(buffer)
|
||||
assert.Error(t, err, "Connection should be closed due to connection timeout")
|
||||
}
|
||||
|
||||
func TestSlowlorisProtection_MultipleSlowClients(t *testing.T) {
|
||||
// Setup server with short timeouts
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 1 * time.Second,
|
||||
Write: 1 * time.Second,
|
||||
Connection: 2 * time.Second,
|
||||
},
|
||||
}
|
||||
|
||||
srv := setupTestServerWithConfig(t, serverConfig)
|
||||
defer srv.Stop()
|
||||
|
||||
// Create multiple slow connections
|
||||
var connections []net.Conn
|
||||
for i := 0; i < 5; i++ {
|
||||
conn, err := net.Dial("tcp", srv.Address())
|
||||
require.NoError(t, err)
|
||||
connections = append(connections, conn)
|
||||
// Send partial data on each connection
|
||||
conn.Write([]byte{0x01}) // Challenge request type only
|
||||
}
|
||||
|
||||
// Wait for timeouts to kick in
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
|
||||
// All connections should be closed
|
||||
buffer := make([]byte, 1024)
|
||||
for i, conn := range connections {
|
||||
conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
|
||||
_, err := conn.Read(buffer)
|
||||
assert.Error(t, err, "Connection %d should be closed", i)
|
||||
conn.Close()
|
||||
}
|
||||
}
|
||||
|
|
@ -1,161 +0,0 @@
|
|||
package integration
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hash-of-wisdom/internal/protocol"
|
||||
"hash-of-wisdom/internal/server"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestTCPServer_TimeoutProtection_SlowReader(t *testing.T) {
|
||||
// Setup server with very short read timeout for testing
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 500 * time.Millisecond,
|
||||
Write: 5 * time.Second,
|
||||
Connection: 15 * time.Second,
|
||||
},
|
||||
}
|
||||
srv := setupTestServerWithConfig(t, serverConfig)
|
||||
defer srv.Stop()
|
||||
|
||||
// Connect to server
|
||||
conn, err := net.Dial("tcp", srv.Address())
|
||||
require.NoError(t, err)
|
||||
defer conn.Close()
|
||||
|
||||
// Send partial message header (just type byte)
|
||||
_, err = conn.Write([]byte{0x01}) // Challenge request type
|
||||
require.NoError(t, err)
|
||||
|
||||
// Wait longer than read timeout before sending length
|
||||
time.Sleep(700 * time.Millisecond)
|
||||
|
||||
// Try to send more data - connection should be timed out
|
||||
_, err = conn.Write([]byte{0x00, 0x00, 0x00, 0x00}) // Payload length
|
||||
|
||||
// Verify connection is closed by reading
|
||||
buffer := make([]byte, 1024)
|
||||
conn.SetReadDeadline(time.Now().Add(1 * time.Second))
|
||||
_, err = conn.Read(buffer)
|
||||
assert.Error(t, err, "Connection should be closed due to slow reading")
|
||||
}
|
||||
|
||||
func TestTCPServer_TimeoutProtection_ConnectionTimeout(t *testing.T) {
|
||||
// Setup server with very short connection timeout
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 5 * time.Second,
|
||||
Write: 5 * time.Second,
|
||||
Connection: 1 * time.Second,
|
||||
},
|
||||
}
|
||||
srv := setupTestServerWithConfig(t, serverConfig)
|
||||
defer srv.Stop()
|
||||
|
||||
// Connect to server
|
||||
conn, err := net.Dial("tcp", srv.Address())
|
||||
require.NoError(t, err)
|
||||
defer conn.Close()
|
||||
|
||||
// Wait longer than connection timeout
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
|
||||
// Try to read from connection - should get EOF or connection reset
|
||||
buffer := make([]byte, 1024)
|
||||
conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
|
||||
_, err = conn.Read(buffer)
|
||||
assert.Error(t, err, "Connection should be closed due to timeout")
|
||||
}
|
||||
|
||||
func TestTCPServer_NormalOperation_WithinTimeouts(t *testing.T) {
|
||||
srv := setupTestServer(t)
|
||||
defer srv.Stop()
|
||||
|
||||
// Connect and complete normal flow quickly
|
||||
conn, err := net.Dial("tcp", srv.Address())
|
||||
require.NoError(t, err)
|
||||
defer conn.Close()
|
||||
|
||||
// Request challenge using new protocol API
|
||||
challengeReq := &protocol.ChallengeRequest{}
|
||||
err = challengeReq.Encode(conn)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Should receive challenge response without timeout
|
||||
decoder := protocol.NewMessageDecoder()
|
||||
msg, err := decoder.Decode(conn)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, protocol.ChallengeResponseType, msg.Type)
|
||||
assert.Greater(t, msg.PayloadLength, uint32(0), "Challenge payload should not be empty")
|
||||
}
|
||||
|
||||
func TestTCPServer_MultipleConnections_IndependentTimeouts(t *testing.T) {
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 1 * time.Second,
|
||||
Write: 5 * time.Second,
|
||||
Connection: 3 * time.Second,
|
||||
},
|
||||
}
|
||||
srv := setupTestServerWithConfig(t, serverConfig)
|
||||
defer srv.Stop()
|
||||
|
||||
// Start two connections
|
||||
conn1, err := net.Dial("tcp", srv.Address())
|
||||
require.NoError(t, err)
|
||||
defer conn1.Close()
|
||||
|
||||
conn2, err := net.Dial("tcp", srv.Address())
|
||||
require.NoError(t, err)
|
||||
defer conn2.Close()
|
||||
|
||||
// Conn1: Send complete request quickly
|
||||
go func() {
|
||||
req := &protocol.ChallengeRequest{}
|
||||
req.Encode(conn1)
|
||||
}()
|
||||
|
||||
// Conn2: Send partial request and stall
|
||||
conn2.Write([]byte{0x01}) // Just message type
|
||||
|
||||
// Wait for read timeout
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
|
||||
// Conn1 should still work, Conn2 should be closed
|
||||
buffer := make([]byte, 1024)
|
||||
|
||||
// Conn1 should receive response
|
||||
conn1.SetReadDeadline(time.Now().Add(1 * time.Second))
|
||||
n, err := conn1.Read(buffer)
|
||||
assert.NoError(t, err)
|
||||
assert.Greater(t, n, 0, "Conn1 should receive response")
|
||||
|
||||
// Conn2 should be closed
|
||||
conn2.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
|
||||
_, err = conn2.Read(buffer)
|
||||
assert.Error(t, err, "Conn2 should be closed due to timeout")
|
||||
}
|
||||
|
||||
// Helper function to create test server with default config
|
||||
func setupTestServer(t *testing.T) *server.TCPServer {
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 5 * time.Second,
|
||||
Write: 5 * time.Second,
|
||||
Connection: 15 * time.Second,
|
||||
},
|
||||
}
|
||||
return setupTestServerWithConfig(t, serverConfig)
|
||||
}
|
||||
|
||||
// Helper function to create test server with custom config
|
||||
Loading…
Reference in a new issue