Compare commits
4 commits
phase-9-do
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dfbf23a27c | ||
|
|
89b5fb9cf1 | ||
|
|
c9fb9f91c1 | ||
|
|
78beb401fe |
59
README.md
59
README.md
|
|
@ -11,17 +11,41 @@ The Hash of Wisdom server requires clients to solve computational puzzles (proof
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
- Go 1.24.3+
|
- Go 1.24.3+
|
||||||
- Docker (optional)
|
- Docker (optional)
|
||||||
|
- [Task](https://taskfile.dev/) (optional, but recommended)
|
||||||
|
|
||||||
### Building
|
### Building
|
||||||
```bash
|
```bash
|
||||||
# Build server
|
# Build server
|
||||||
go build -o hash-of-wisdom ./cmd/server
|
go build -o hash-of-wisdom ./cmd/server
|
||||||
|
|
||||||
# Build client
|
# Build client
|
||||||
go build -o client ./cmd/client
|
go build -o client ./cmd/client
|
||||||
```
|
```
|
||||||
|
|
||||||
### Running
|
### 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
|
```bash
|
||||||
# Start server (uses config.yaml by default)
|
# Start server (uses config.yaml by default)
|
||||||
./hash-of-wisdom
|
./hash-of-wisdom
|
||||||
|
|
@ -31,6 +55,9 @@ go build -o client ./cmd/client
|
||||||
|
|
||||||
# Connect with client
|
# Connect with client
|
||||||
./client -addr localhost:8080
|
./client -addr localhost:8080
|
||||||
|
|
||||||
|
# Run tests
|
||||||
|
go test ./...
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using Docker
|
### Using Docker
|
||||||
|
|
@ -50,38 +77,10 @@ docker run -p 8080:8080 -p 8081:8081 hash-of-wisdom
|
||||||
|
|
||||||
### Protocol & Implementation
|
### Protocol & Implementation
|
||||||
- [Protocol Specification](docs/PROTOCOL.md) - Binary protocol definition
|
- [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
|
- [Implementation Plan](docs/IMPLEMENTATION.md) - Development phases and progress
|
||||||
- [Package Structure](docs/PACKAGES.md) - Code organization and package responsibilities
|
- [Package Structure](docs/PACKAGES.md) - Code organization and package responsibilities
|
||||||
- [Architecture Choices](docs/ARCHITECTURE.md) - Design decisions and patterns
|
- [Architecture Choices](docs/ARCHITECTURE.md) - Design decisions and patterns
|
||||||
|
|
||||||
### Production Readiness
|
### Production Readiness
|
||||||
- [Production Readiness Guide](docs/PRODUCTION_READINESS.md) - Requirements for production deployment
|
- [Production Readiness Guide](docs/PRODUCTION_READINESS.md) - Requirements for production deployment
|
||||||
|
|
||||||
## Algorithm Choice
|
|
||||||
|
|
||||||
The server uses **SHA-256 based proof-of-work** with leading zero bits difficulty:
|
|
||||||
- **Why SHA-256**: Cryptographically secure, well-tested, hardware-optimized
|
|
||||||
- **Leading Zero Bits**: Simple difficulty scaling, easy verification
|
|
||||||
- **HMAC Authentication**: Prevents challenge tampering and replay attacks
|
|
||||||
- **Configurable Difficulty**: Adaptive to different threat levels (4-30 bits)
|
|
||||||
|
|
||||||
This approach provides strong DDoS protection while remaining computationally reasonable for legitimate clients.
|
|
||||||
|
|
||||||
## Current Status
|
|
||||||
|
|
||||||
✅ **Complete**: Core functionality, TCP server, client, metrics, containerization
|
|
||||||
🔄 **In Progress**: Documentation (Phase 9)
|
|
||||||
📋 **Planned**: See [Production Readiness Guide](docs/PRODUCTION_READINESS.md) for production deployment requirements
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Run all tests
|
|
||||||
go test ./...
|
|
||||||
|
|
||||||
# Run integration tests
|
|
||||||
go test ./test/integration/...
|
|
||||||
|
|
||||||
# Benchmarks
|
|
||||||
go test -bench=. ./internal/pow/...
|
|
||||||
```
|
|
||||||
|
|
|
||||||
38
Taskfile.yml
38
Taskfile.yml
|
|
@ -93,3 +93,41 @@ tasks:
|
||||||
desc: Alias for cpu-burner
|
desc: Alias for cpu-burner
|
||||||
cmds:
|
cmds:
|
||||||
- task: cpu-burner
|
- 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/...
|
||||||
|
|
|
||||||
|
|
@ -55,7 +55,7 @@ func main() {
|
||||||
|
|
||||||
// Create server configuration
|
// Create server configuration
|
||||||
serverConfig := &server.Config{
|
serverConfig := &server.Config{
|
||||||
Address: cfg.Server.Address,
|
Address: cfg.Server.Address,
|
||||||
Timeouts: server.TimeoutConfig{
|
Timeouts: server.TimeoutConfig{
|
||||||
Read: cfg.Server.Timeouts.Read,
|
Read: cfg.Server.Timeouts.Read,
|
||||||
Write: cfg.Server.Timeouts.Write,
|
Write: cfg.Server.Timeouts.Write,
|
||||||
|
|
|
||||||
|
|
@ -32,9 +32,9 @@ func TestWisdomApplication_HandleMessage_UnsupportedType(t *testing.T) {
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
msg := &protocol.Message{
|
msg := &protocol.Message{
|
||||||
Type: protocol.MessageType(0xFF), // Invalid type
|
Type: protocol.MessageType(0xFF), // Invalid type
|
||||||
PayloadLength: 0,
|
PayloadLength: 0,
|
||||||
PayloadStream: nil,
|
PayloadStream: nil,
|
||||||
}
|
}
|
||||||
|
|
||||||
response, err := app.HandleMessage(ctx, msg)
|
response, err := app.HandleMessage(ctx, msg)
|
||||||
|
|
@ -64,9 +64,9 @@ func TestWisdomApplication_HandleChallengeRequest_Success(t *testing.T) {
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
msg := &protocol.Message{
|
msg := &protocol.Message{
|
||||||
Type: protocol.ChallengeRequestType,
|
Type: protocol.ChallengeRequestType,
|
||||||
PayloadLength: 0,
|
PayloadLength: 0,
|
||||||
PayloadStream: nil,
|
PayloadStream: nil,
|
||||||
}
|
}
|
||||||
|
|
||||||
response, err := app.HandleMessage(ctx, msg)
|
response, err := app.HandleMessage(ctx, msg)
|
||||||
|
|
@ -89,9 +89,9 @@ func TestWisdomApplication_HandleChallengeRequest_ServiceError(t *testing.T) {
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
msg := &protocol.Message{
|
msg := &protocol.Message{
|
||||||
Type: protocol.ChallengeRequestType,
|
Type: protocol.ChallengeRequestType,
|
||||||
PayloadLength: 0,
|
PayloadLength: 0,
|
||||||
PayloadStream: nil,
|
PayloadStream: nil,
|
||||||
}
|
}
|
||||||
|
|
||||||
response, err := app.HandleMessage(ctx, msg)
|
response, err := app.HandleMessage(ctx, msg)
|
||||||
|
|
@ -138,9 +138,9 @@ func TestWisdomApplication_HandleSolutionRequest_Success(t *testing.T) {
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
msg := &protocol.Message{
|
msg := &protocol.Message{
|
||||||
Type: protocol.SolutionRequestType,
|
Type: protocol.SolutionRequestType,
|
||||||
PayloadLength: uint32(len(payloadJSON)),
|
PayloadLength: uint32(len(payloadJSON)),
|
||||||
PayloadStream: bytes.NewReader(payloadJSON),
|
PayloadStream: bytes.NewReader(payloadJSON),
|
||||||
}
|
}
|
||||||
|
|
||||||
response, err := app.HandleMessage(ctx, msg)
|
response, err := app.HandleMessage(ctx, msg)
|
||||||
|
|
@ -161,9 +161,9 @@ func TestWisdomApplication_HandleSolutionRequest_InvalidJSON(t *testing.T) {
|
||||||
invalidJSON := []byte("invalid json")
|
invalidJSON := []byte("invalid json")
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
msg := &protocol.Message{
|
msg := &protocol.Message{
|
||||||
Type: protocol.SolutionRequestType,
|
Type: protocol.SolutionRequestType,
|
||||||
PayloadLength: uint32(len(invalidJSON)),
|
PayloadLength: uint32(len(invalidJSON)),
|
||||||
PayloadStream: bytes.NewReader(invalidJSON),
|
PayloadStream: bytes.NewReader(invalidJSON),
|
||||||
}
|
}
|
||||||
|
|
||||||
response, err := app.HandleMessage(ctx, msg)
|
response, err := app.HandleMessage(ctx, msg)
|
||||||
|
|
@ -205,9 +205,9 @@ func TestWisdomApplication_HandleSolutionRequest_VerificationFailed(t *testing.T
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
msg := &protocol.Message{
|
msg := &protocol.Message{
|
||||||
Type: protocol.SolutionRequestType,
|
Type: protocol.SolutionRequestType,
|
||||||
PayloadLength: uint32(len(payloadJSON)),
|
PayloadLength: uint32(len(payloadJSON)),
|
||||||
PayloadStream: bytes.NewReader(payloadJSON),
|
PayloadStream: bytes.NewReader(payloadJSON),
|
||||||
}
|
}
|
||||||
|
|
||||||
response, err := app.HandleMessage(ctx, msg)
|
response, err := app.HandleMessage(ctx, msg)
|
||||||
|
|
@ -250,9 +250,9 @@ func TestWisdomApplication_HandleSolutionRequest_QuoteServiceError(t *testing.T)
|
||||||
|
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
msg := &protocol.Message{
|
msg := &protocol.Message{
|
||||||
Type: protocol.SolutionRequestType,
|
Type: protocol.SolutionRequestType,
|
||||||
PayloadLength: uint32(len(payloadJSON)),
|
PayloadLength: uint32(len(payloadJSON)),
|
||||||
PayloadStream: bytes.NewReader(payloadJSON),
|
PayloadStream: bytes.NewReader(payloadJSON),
|
||||||
}
|
}
|
||||||
|
|
||||||
response, err := app.HandleMessage(ctx, msg)
|
response, err := app.HandleMessage(ctx, msg)
|
||||||
|
|
@ -279,9 +279,9 @@ func TestWisdomApplication_HandleMessage_ContextCancellation(t *testing.T) {
|
||||||
mockService.On("GenerateChallenge", mock.Anything, "quotes").Return(nil, context.Canceled)
|
mockService.On("GenerateChallenge", mock.Anything, "quotes").Return(nil, context.Canceled)
|
||||||
|
|
||||||
msg := &protocol.Message{
|
msg := &protocol.Message{
|
||||||
Type: protocol.ChallengeRequestType,
|
Type: protocol.ChallengeRequestType,
|
||||||
PayloadLength: 0,
|
PayloadLength: 0,
|
||||||
PayloadStream: nil,
|
PayloadStream: nil,
|
||||||
}
|
}
|
||||||
|
|
||||||
response, err := app.HandleMessage(ctx, msg)
|
response, err := app.HandleMessage(ctx, msg)
|
||||||
|
|
|
||||||
|
|
@ -7,16 +7,16 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Server ServerConfig `yaml:"server"`
|
Server ServerConfig `yaml:"server"`
|
||||||
PoW PoWConfig `yaml:"pow"`
|
PoW PoWConfig `yaml:"pow"`
|
||||||
Quotes QuotesConfig `yaml:"quotes"`
|
Quotes QuotesConfig `yaml:"quotes"`
|
||||||
Metrics MetricsConfig `yaml:"metrics"`
|
Metrics MetricsConfig `yaml:"metrics"`
|
||||||
Logging LoggingConfig `yaml:"logging"`
|
Logging LoggingConfig `yaml:"logging"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ServerConfig struct {
|
type ServerConfig struct {
|
||||||
Address string `yaml:"address" env:"SERVER_ADDRESS" env-default:":8080"`
|
Address string `yaml:"address" env:"SERVER_ADDRESS" env-default:":8080"`
|
||||||
Timeouts TimeoutConfig `yaml:"timeouts"`
|
Timeouts TimeoutConfig `yaml:"timeouts"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type TimeoutConfig struct {
|
type TimeoutConfig struct {
|
||||||
|
|
@ -26,10 +26,10 @@ type TimeoutConfig struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
type PoWConfig struct {
|
type PoWConfig struct {
|
||||||
Difficulty int `yaml:"difficulty" env:"POW_DIFFICULTY" env-default:"4"`
|
Difficulty int `yaml:"difficulty" env:"POW_DIFFICULTY" env-default:"4"`
|
||||||
MaxDifficulty int `yaml:"max_difficulty" env:"POW_MAX_DIFFICULTY" env-default:"10"`
|
MaxDifficulty int `yaml:"max_difficulty" env:"POW_MAX_DIFFICULTY" env-default:"10"`
|
||||||
TTL time.Duration `yaml:"ttl" env:"POW_TTL" env-default:"5m"`
|
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"`
|
HMACSecret string `yaml:"hmac_secret" env:"POW_HMAC_SECRET" env-default:"development-secret-change-in-production"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type QuotesConfig struct {
|
type QuotesConfig struct {
|
||||||
|
|
|
||||||
|
|
@ -68,8 +68,8 @@ func (c *Challenge) VerifySolution(nonce uint64) bool {
|
||||||
|
|
||||||
// hasLeadingZeroBits checks if hash has the required number of leading zero bits
|
// hasLeadingZeroBits checks if hash has the required number of leading zero bits
|
||||||
func hasLeadingZeroBits(hash []byte, difficulty int) bool {
|
func hasLeadingZeroBits(hash []byte, difficulty int) bool {
|
||||||
full := difficulty >> 3 // number of whole zero bytes
|
full := difficulty >> 3 // number of whole zero bytes
|
||||||
rem := uint(difficulty & 7) // remaining leading zero bits
|
rem := uint(difficulty & 7) // remaining leading zero bits
|
||||||
|
|
||||||
for i := range full {
|
for i := range full {
|
||||||
if hash[i] != 0 {
|
if hash[i] != 0 {
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@ package protocol
|
||||||
type MessageType byte
|
type MessageType byte
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ChallengeRequestType MessageType = 0x01
|
ChallengeRequestType MessageType = 0x01
|
||||||
SolutionRequestType MessageType = 0x03
|
SolutionRequestType MessageType = 0x03
|
||||||
// Response types (for responses.go)
|
// Response types (for responses.go)
|
||||||
ChallengeResponseType MessageType = 0x02
|
ChallengeResponseType MessageType = 0x02
|
||||||
QuoteResponseType MessageType = 0x04
|
QuoteResponseType MessageType = 0x04
|
||||||
|
|
@ -14,14 +14,14 @@ const (
|
||||||
|
|
||||||
// Error codes as defined in protocol specification
|
// Error codes as defined in protocol specification
|
||||||
const (
|
const (
|
||||||
ErrMalformedMessage = "MALFORMED_MESSAGE"
|
ErrMalformedMessage = "MALFORMED_MESSAGE"
|
||||||
ErrInvalidChallenge = "INVALID_CHALLENGE"
|
ErrInvalidChallenge = "INVALID_CHALLENGE"
|
||||||
ErrInvalidSolution = "INVALID_SOLUTION"
|
ErrInvalidSolution = "INVALID_SOLUTION"
|
||||||
ErrExpiredChallenge = "EXPIRED_CHALLENGE"
|
ErrExpiredChallenge = "EXPIRED_CHALLENGE"
|
||||||
ErrRateLimited = "RATE_LIMITED"
|
ErrRateLimited = "RATE_LIMITED"
|
||||||
ErrServerError = "SERVER_ERROR"
|
ErrServerError = "SERVER_ERROR"
|
||||||
ErrTooManyConnections = "TOO_MANY_CONNECTIONS"
|
ErrTooManyConnections = "TOO_MANY_CONNECTIONS"
|
||||||
ErrDifficultyTooHigh = "DIFFICULTY_TOO_HIGH"
|
ErrDifficultyTooHigh = "DIFFICULTY_TOO_HIGH"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Protocol constants
|
// Protocol constants
|
||||||
|
|
|
||||||
|
|
@ -43,8 +43,8 @@ func (d *MessageDecoder) Decode(r io.Reader) (*Message, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Message{
|
return &Message{
|
||||||
Type: msgType,
|
Type: msgType,
|
||||||
PayloadLength: payloadLength,
|
PayloadLength: payloadLength,
|
||||||
PayloadStream: payloadStream,
|
PayloadStream: payloadStream,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,11 +13,11 @@ func TestMessageDecoder_Decode_Header(t *testing.T) {
|
||||||
decoder := NewMessageDecoder()
|
decoder := NewMessageDecoder()
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
data []byte
|
data []byte
|
||||||
wantType MessageType
|
wantType MessageType
|
||||||
wantLength uint32
|
wantLength uint32
|
||||||
wantErr string
|
wantErr string
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "challenge request with empty payload",
|
name: "challenge request with empty payload",
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,6 @@ import (
|
||||||
"hash-of-wisdom/internal/pow/challenge"
|
"hash-of-wisdom/internal/pow/challenge"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
// ChallengeRequest is empty (no payload for challenge requests)
|
// ChallengeRequest is empty (no payload for challenge requests)
|
||||||
type ChallengeRequest struct{}
|
type ChallengeRequest struct{}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,6 @@ import (
|
||||||
"hash-of-wisdom/internal/quotes"
|
"hash-of-wisdom/internal/quotes"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
// ChallengeResponse represents a challenge response
|
// ChallengeResponse represents a challenge response
|
||||||
type ChallengeResponse struct {
|
type ChallengeResponse struct {
|
||||||
Challenge *challenge.Challenge
|
Challenge *challenge.Challenge
|
||||||
|
|
|
||||||
|
|
@ -113,7 +113,6 @@ func TestChallengeRequest_EmptyPayload(t *testing.T) {
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func TestPayloadStream_LimitedRead(t *testing.T) {
|
func TestPayloadStream_LimitedRead(t *testing.T) {
|
||||||
decoder := NewMessageDecoder()
|
decoder := NewMessageDecoder()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import "io"
|
||||||
|
|
||||||
// Message represents a protocol message with type and payload stream
|
// Message represents a protocol message with type and payload stream
|
||||||
type Message struct {
|
type Message struct {
|
||||||
Type MessageType
|
Type MessageType
|
||||||
PayloadLength uint32
|
PayloadLength uint32
|
||||||
PayloadStream io.Reader
|
PayloadStream io.Reader
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -30,7 +30,6 @@ type TCPServer struct {
|
||||||
// Option is a functional option for configuring TCPServer
|
// Option is a functional option for configuring TCPServer
|
||||||
type option func(*TCPServer)
|
type option func(*TCPServer)
|
||||||
|
|
||||||
|
|
||||||
// WithLogger sets a custom logger
|
// WithLogger sets a custom logger
|
||||||
func WithLogger(logger *slog.Logger) option {
|
func WithLogger(logger *slog.Logger) option {
|
||||||
return func(s *TCPServer) {
|
return func(s *TCPServer) {
|
||||||
|
|
@ -54,7 +53,6 @@ func NewTCPServer(wisdomService *service.WisdomService, config *Config, opts ...
|
||||||
return server
|
return server
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Start starts the TCP server
|
// Start starts the TCP server
|
||||||
func (s *TCPServer) Start(ctx context.Context) error {
|
func (s *TCPServer) Start(ctx context.Context) error {
|
||||||
listener, err := net.Listen("tcp", s.config.Address)
|
listener, err := net.Listen("tcp", s.config.Address)
|
||||||
|
|
|
||||||
|
|
@ -9,11 +9,11 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrResourceRequired = errors.New("resource is required")
|
ErrResourceRequired = errors.New("resource is required")
|
||||||
ErrUnsupportedResource = errors.New("unsupported resource")
|
ErrUnsupportedResource = errors.New("unsupported resource")
|
||||||
ErrSolutionRequired = errors.New("solution is required")
|
ErrSolutionRequired = errors.New("solution is required")
|
||||||
ErrInvalidChallenge = errors.New("invalid challenge")
|
ErrInvalidChallenge = errors.New("invalid challenge")
|
||||||
ErrInvalidSolution = errors.New("invalid proof of work solution")
|
ErrInvalidSolution = errors.New("invalid proof of work solution")
|
||||||
)
|
)
|
||||||
|
|
||||||
type ChallengeGenerator interface {
|
type ChallengeGenerator interface {
|
||||||
|
|
|
||||||
|
|
@ -70,15 +70,15 @@ func TestWisdomService_GenerateChallenge(t *testing.T) {
|
||||||
|
|
||||||
func TestWisdomService_VerifySolution(t *testing.T) {
|
func TestWisdomService_VerifySolution(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
solution *challenge.Solution
|
solution *challenge.Solution
|
||||||
wantErr error
|
wantErr error
|
||||||
setupMocks func(*mocks.MockChallengeVerifier)
|
setupMocks func(*mocks.MockChallengeVerifier)
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "nil solution",
|
name: "nil solution",
|
||||||
solution: nil,
|
solution: nil,
|
||||||
wantErr: ErrSolutionRequired,
|
wantErr: ErrSolutionRequired,
|
||||||
setupMocks: func(mv *mocks.MockChallengeVerifier) {},
|
setupMocks: func(mv *mocks.MockChallengeVerifier) {},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
@ -93,17 +93,17 @@ func TestWisdomService_VerifySolution(t *testing.T) {
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "invalid solution",
|
name: "invalid solution",
|
||||||
solution: createInvalidSolution(t),
|
solution: createInvalidSolution(t),
|
||||||
wantErr: ErrInvalidSolution,
|
wantErr: ErrInvalidSolution,
|
||||||
setupMocks: func(mv *mocks.MockChallengeVerifier) {
|
setupMocks: func(mv *mocks.MockChallengeVerifier) {
|
||||||
mv.EXPECT().VerifyChallenge(mock.Anything).Return(nil).Once()
|
mv.EXPECT().VerifyChallenge(mock.Anything).Return(nil).Once()
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "valid solution",
|
name: "valid solution",
|
||||||
solution: createValidSolution(t),
|
solution: createValidSolution(t),
|
||||||
wantErr: nil,
|
wantErr: nil,
|
||||||
setupMocks: func(mv *mocks.MockChallengeVerifier) {
|
setupMocks: func(mv *mocks.MockChallengeVerifier) {
|
||||||
mv.EXPECT().VerifyChallenge(mock.Anything).Return(nil).Once()
|
mv.EXPECT().VerifyChallenge(mock.Anything).Return(nil).Once()
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -284,8 +284,8 @@ func TestWisdomService_InvalidSolutions(t *testing.T) {
|
||||||
|
|
||||||
func TestWisdomService_UnsuccessfulFlows(t *testing.T) {
|
func TestWisdomService_UnsuccessfulFlows(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
difficulty int
|
difficulty int
|
||||||
createSolution func(*challenge.Challenge, *challenge.Solution) *challenge.Solution
|
createSolution func(*challenge.Challenge, *challenge.Solution) *challenge.Solution
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
|
|
|
||||||
56
test/integration/helpers_test.go
Normal file
56
test/integration/helpers_test.go
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
@ -5,7 +5,6 @@ import (
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"hash-of-wisdom/internal/protocol"
|
|
||||||
"hash-of-wisdom/internal/server"
|
"hash-of-wisdom/internal/server"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
@ -15,7 +14,7 @@ import (
|
||||||
func TestSlowlorisProtection_SlowReader(t *testing.T) {
|
func TestSlowlorisProtection_SlowReader(t *testing.T) {
|
||||||
// Setup server with very short read timeout for testing
|
// Setup server with very short read timeout for testing
|
||||||
serverConfig := &server.Config{
|
serverConfig := &server.Config{
|
||||||
Address: ":0",
|
Address: ":0",
|
||||||
Timeouts: server.TimeoutConfig{
|
Timeouts: server.TimeoutConfig{
|
||||||
Read: 100 * time.Millisecond,
|
Read: 100 * time.Millisecond,
|
||||||
Write: 5 * time.Second,
|
Write: 5 * time.Second,
|
||||||
|
|
@ -48,47 +47,10 @@ func TestSlowlorisProtection_SlowReader(t *testing.T) {
|
||||||
assert.Error(t, err, "Connection should be closed due to slow reading")
|
assert.Error(t, err, "Connection should be closed due to slow reading")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSlowlorisProtection_SlowWriter(t *testing.T) {
|
|
||||||
// Setup server with very short write timeout for testing
|
|
||||||
serverConfig := &server.Config{
|
|
||||||
Address: ":0",
|
|
||||||
Timeouts: server.TimeoutConfig{
|
|
||||||
Read: 5 * time.Second,
|
|
||||||
Write: 100 * time.Millisecond,
|
|
||||||
Connection: 15 * time.Second,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
srv := setupTestServerWithConfig(t, serverConfig)
|
|
||||||
defer srv.Stop()
|
|
||||||
|
|
||||||
// Connect to server but don't read responses (simulate slow writer client)
|
|
||||||
conn, err := net.Dial("tcp", srv.Address())
|
|
||||||
require.NoError(t, err)
|
|
||||||
defer conn.Close()
|
|
||||||
|
|
||||||
// Send a complete challenge request
|
|
||||||
challengeReq := &protocol.ChallengeRequest{}
|
|
||||||
err = challengeReq.Encode(conn)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// Don't read the response - this should trigger write timeout
|
|
||||||
time.Sleep(200 * time.Millisecond)
|
|
||||||
|
|
||||||
// Try to write again - connection should be timed out
|
|
||||||
_, err = conn.Write([]byte{0x01})
|
|
||||||
|
|
||||||
// Verify connection is 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 slow writing")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSlowlorisProtection_SlowConnectionTimeout(t *testing.T) {
|
func TestSlowlorisProtection_SlowConnectionTimeout(t *testing.T) {
|
||||||
// Setup server with very short connection timeout for testing
|
// Setup server with very short connection timeout for testing
|
||||||
serverConfig := &server.Config{
|
serverConfig := &server.Config{
|
||||||
Address: ":0",
|
Address: ":0",
|
||||||
Timeouts: server.TimeoutConfig{
|
Timeouts: server.TimeoutConfig{
|
||||||
Read: 5 * time.Second,
|
Read: 5 * time.Second,
|
||||||
Write: 5 * time.Second,
|
Write: 5 * time.Second,
|
||||||
|
|
@ -117,7 +79,7 @@ func TestSlowlorisProtection_SlowConnectionTimeout(t *testing.T) {
|
||||||
func TestSlowlorisProtection_MultipleSlowClients(t *testing.T) {
|
func TestSlowlorisProtection_MultipleSlowClients(t *testing.T) {
|
||||||
// Setup server with short timeouts
|
// Setup server with short timeouts
|
||||||
serverConfig := &server.Config{
|
serverConfig := &server.Config{
|
||||||
Address: ":0",
|
Address: ":0",
|
||||||
Timeouts: server.TimeoutConfig{
|
Timeouts: server.TimeoutConfig{
|
||||||
Read: 1 * time.Second,
|
Read: 1 * time.Second,
|
||||||
Write: 1 * time.Second,
|
Write: 1 * time.Second,
|
||||||
|
|
@ -150,86 +112,3 @@ func TestSlowlorisProtection_MultipleSlowClients(t *testing.T) {
|
||||||
conn.Close()
|
conn.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSlowlorisProtection_AttackMitigation(t *testing.T) {
|
|
||||||
// Test that server can still serve legitimate clients during an attack
|
|
||||||
serverConfig := &server.Config{
|
|
||||||
Address: ":0",
|
|
||||||
Timeouts: server.TimeoutConfig{
|
|
||||||
Read: 500 * time.Millisecond,
|
|
||||||
Write: 500 * time.Millisecond,
|
|
||||||
Connection: 1 * time.Second,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
srv := setupTestServerWithConfig(t, serverConfig)
|
|
||||||
defer srv.Stop()
|
|
||||||
|
|
||||||
// Start slowloris attack - multiple slow connections
|
|
||||||
var attackConnections []net.Conn
|
|
||||||
for i := 0; i < 3; i++ {
|
|
||||||
conn, err := net.Dial("tcp", srv.Address())
|
|
||||||
require.NoError(t, err)
|
|
||||||
attackConnections = append(attackConnections, conn)
|
|
||||||
// Send partial data
|
|
||||||
conn.Write([]byte{0x01})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Meanwhile, legitimate client should still work
|
|
||||||
legitimateConn, err := net.Dial("tcp", srv.Address())
|
|
||||||
require.NoError(t, err)
|
|
||||||
defer legitimateConn.Close()
|
|
||||||
|
|
||||||
// Send complete request quickly
|
|
||||||
challengeReq := &protocol.ChallengeRequest{}
|
|
||||||
err = challengeReq.Encode(legitimateConn)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// Should receive response despite ongoing attack
|
|
||||||
decoder := protocol.NewMessageDecoder()
|
|
||||||
msg, err := decoder.Decode(legitimateConn)
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Equal(t, protocol.ChallengeResponseType, msg.Type)
|
|
||||||
|
|
||||||
// Clean up attack connections
|
|
||||||
for _, conn := range attackConnections {
|
|
||||||
conn.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSlowlorisProtection_SlowChunkReading(t *testing.T) {
|
|
||||||
// Test protection against clients that read responses very slowly
|
|
||||||
serverConfig := &server.Config{
|
|
||||||
Address: ":0",
|
|
||||||
Timeouts: server.TimeoutConfig{
|
|
||||||
Read: 5 * time.Second,
|
|
||||||
Write: 200 * time.Millisecond,
|
|
||||||
Connection: 10 * time.Second,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
srv := setupTestServerWithConfig(t, serverConfig)
|
|
||||||
defer srv.Stop()
|
|
||||||
|
|
||||||
// Connect and send valid request
|
|
||||||
conn, err := net.Dial("tcp", srv.Address())
|
|
||||||
require.NoError(t, err)
|
|
||||||
defer conn.Close()
|
|
||||||
|
|
||||||
challengeReq := &protocol.ChallengeRequest{}
|
|
||||||
err = challengeReq.Encode(conn)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// Read only first byte of response very slowly
|
|
||||||
buffer := make([]byte, 1)
|
|
||||||
_, err = conn.Read(buffer)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// Wait longer than write timeout before reading more
|
|
||||||
time.Sleep(300 * time.Millisecond)
|
|
||||||
|
|
||||||
// Try to read more - connection should be closed due to slow reading
|
|
||||||
conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
|
|
||||||
_, err = conn.Read(buffer)
|
|
||||||
assert.Error(t, err, "Connection should be closed due to slow chunk reading")
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,12 @@
|
||||||
package integration
|
package integration
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net"
|
"net"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"hash-of-wisdom/internal/config"
|
|
||||||
"hash-of-wisdom/internal/lib/sl"
|
|
||||||
"hash-of-wisdom/internal/pow/challenge"
|
|
||||||
"hash-of-wisdom/internal/protocol"
|
"hash-of-wisdom/internal/protocol"
|
||||||
"hash-of-wisdom/internal/quotes"
|
|
||||||
"hash-of-wisdom/internal/server"
|
"hash-of-wisdom/internal/server"
|
||||||
"hash-of-wisdom/internal/service"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
|
|
@ -21,7 +15,7 @@ import (
|
||||||
func TestTCPServer_TimeoutProtection_SlowReader(t *testing.T) {
|
func TestTCPServer_TimeoutProtection_SlowReader(t *testing.T) {
|
||||||
// Setup server with very short read timeout for testing
|
// Setup server with very short read timeout for testing
|
||||||
serverConfig := &server.Config{
|
serverConfig := &server.Config{
|
||||||
Address: ":0",
|
Address: ":0",
|
||||||
Timeouts: server.TimeoutConfig{
|
Timeouts: server.TimeoutConfig{
|
||||||
Read: 500 * time.Millisecond,
|
Read: 500 * time.Millisecond,
|
||||||
Write: 5 * time.Second,
|
Write: 5 * time.Second,
|
||||||
|
|
@ -55,9 +49,8 @@ func TestTCPServer_TimeoutProtection_SlowReader(t *testing.T) {
|
||||||
|
|
||||||
func TestTCPServer_TimeoutProtection_ConnectionTimeout(t *testing.T) {
|
func TestTCPServer_TimeoutProtection_ConnectionTimeout(t *testing.T) {
|
||||||
// Setup server with very short connection timeout
|
// Setup server with very short connection timeout
|
||||||
_ = config.Load
|
|
||||||
serverConfig := &server.Config{
|
serverConfig := &server.Config{
|
||||||
Address: ":0",
|
Address: ":0",
|
||||||
Timeouts: server.TimeoutConfig{
|
Timeouts: server.TimeoutConfig{
|
||||||
Read: 5 * time.Second,
|
Read: 5 * time.Second,
|
||||||
Write: 5 * time.Second,
|
Write: 5 * time.Second,
|
||||||
|
|
@ -105,9 +98,8 @@ func TestTCPServer_NormalOperation_WithinTimeouts(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTCPServer_MultipleConnections_IndependentTimeouts(t *testing.T) {
|
func TestTCPServer_MultipleConnections_IndependentTimeouts(t *testing.T) {
|
||||||
_ = config.Load
|
|
||||||
serverConfig := &server.Config{
|
serverConfig := &server.Config{
|
||||||
Address: ":0",
|
Address: ":0",
|
||||||
Timeouts: server.TimeoutConfig{
|
Timeouts: server.TimeoutConfig{
|
||||||
Read: 1 * time.Second,
|
Read: 1 * time.Second,
|
||||||
Write: 5 * time.Second,
|
Write: 5 * time.Second,
|
||||||
|
|
@ -156,7 +148,7 @@ func TestTCPServer_MultipleConnections_IndependentTimeouts(t *testing.T) {
|
||||||
// Helper function to create test server with default config
|
// Helper function to create test server with default config
|
||||||
func setupTestServer(t *testing.T) *server.TCPServer {
|
func setupTestServer(t *testing.T) *server.TCPServer {
|
||||||
serverConfig := &server.Config{
|
serverConfig := &server.Config{
|
||||||
Address: ":0",
|
Address: ":0",
|
||||||
Timeouts: server.TimeoutConfig{
|
Timeouts: server.TimeoutConfig{
|
||||||
Read: 5 * time.Second,
|
Read: 5 * time.Second,
|
||||||
Write: 5 * time.Second,
|
Write: 5 * time.Second,
|
||||||
|
|
@ -167,43 +159,3 @@ func setupTestServer(t *testing.T) *server.TCPServer {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper function to create test server with custom config
|
// Helper function to create test server with custom config
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
// testQuoteService provides test quotes
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue