Apply fmt

This commit is contained in:
Savely Krendelhoff 2025-08-23 18:52:32 +07:00
parent 78beb401fe
commit c9fb9f91c1
No known key found for this signature in database
GPG key ID: F70DFD34F40238DE
17 changed files with 79 additions and 85 deletions

View file

@ -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,

View file

@ -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)

View file

@ -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 {

View file

@ -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 {

View file

@ -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

View file

@ -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
} }

View file

@ -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",

View file

@ -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{}

View file

@ -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

View file

@ -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()

View file

@ -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
} }

View file

@ -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)

View file

@ -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 {

View file

@ -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()
}, },

View file

@ -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
}{ }{
{ {

View file

@ -14,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,
@ -47,11 +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_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,
@ -80,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,

View file

@ -15,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,
@ -50,7 +50,7 @@ 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
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,
@ -99,7 +99,7 @@ func TestTCPServer_NormalOperation_WithinTimeouts(t *testing.T) {
func TestTCPServer_MultipleConnections_IndependentTimeouts(t *testing.T) { func TestTCPServer_MultipleConnections_IndependentTimeouts(t *testing.T) {
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,
@ -148,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,