> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/sammwyy/mikuMikuBeam/llms.txt
> Use this file to discover all available pages before exploring further.

# Engine Package

> Core attack orchestration and worker coordination system

The `engine` package provides the core attack orchestration system for Miku Miku Beam. It coordinates attack workers, manages concurrent execution, and handles real-time statistics reporting.

## Package Overview

```go theme={null}
import "github.com/sammwyy/mikumikubeam/internal/engine"
```

The engine package consists of three main components:

* **Engine**: Orchestrates attack lifecycles and worker coordination
* **Registry**: Maps attack types to their worker implementations
* **AttackWorker Interface**: Contract for implementing attack methods

## Core Types

### AttackKind

```go theme={null}
type AttackKind string
```

Enumerates supported attack types.

**Constants:**

<ParamField name="AttackHTTPFlood" type="AttackKind">
  HTTP flood attack with GET/POST requests
</ParamField>

<ParamField name="AttackHTTPBypass" type="AttackKind">
  HTTP attack with bypass techniques (randomized paths, headers)
</ParamField>

<ParamField name="AttackHTTPSlowloris" type="AttackKind">
  Slowloris attack - keeps connections open with incomplete headers
</ParamField>

<ParamField name="AttackTCPFlood" type="AttackKind">
  Raw TCP flood with random payloads
</ParamField>

<ParamField name="AttackMinecraftPing" type="AttackKind">
  Minecraft server status ping attack
</ParamField>

### AttackParams

```go theme={null}
type AttackParams struct {
    Target      string
    TargetNode  targetpkg.Node
    Duration    time.Duration
    PacketDelay time.Duration
    PacketSize  int
    Method      AttackKind
    Threads     int
    Verbose     bool
}
```

Common parameters passed to all attack workers.

<ParamField name="Target" type="string">
  Raw target string (URL or host:port)
</ParamField>

<ParamField name="TargetNode" type="targetpkg.Node">
  Parsed target with scheme, host, port, and path components
</ParamField>

<ParamField name="Duration" type="time.Duration">
  How long the attack should run
</ParamField>

<ParamField name="PacketDelay" type="time.Duration">
  Delay between packets per thread
</ParamField>

<ParamField name="PacketSize" type="int">
  Size of each packet payload in bytes
</ParamField>

<ParamField name="Method" type="AttackKind">
  Attack method to use
</ParamField>

<ParamField name="Threads" type="int">
  Number of concurrent worker threads (defaults to NumCPU if ≤ 0)
</ParamField>

<ParamField name="Verbose" type="bool">
  Enable detailed per-packet logging
</ParamField>

### Proxy

```go theme={null}
type Proxy struct {
    Username string
    Password string
    Protocol string
    Host     string
    Port     int
}
```

Represents a network proxy for routing attacks.

<ParamField name="Protocol" type="string">
  Proxy protocol: `http`, `https`, `socks4`, or `socks5`
</ParamField>

<ParamField name="Host" type="string">
  Proxy hostname or IP address
</ParamField>

<ParamField name="Port" type="int">
  Proxy port number
</ParamField>

<ParamField name="Username" type="string">
  Optional authentication username
</ParamField>

<ParamField name="Password" type="string">
  Optional authentication password
</ParamField>

### AttackStats

```go theme={null}
type AttackStats struct {
    Timestamp    time.Time
    PacketsPerS  int64
    TotalPackets int64
    Proxies      int
    Log          string
}
```

Live statistics reported by the engine and workers.

<ResponseField name="Timestamp" type="time.Time">
  When this stat was recorded
</ResponseField>

<ResponseField name="PacketsPerS" type="int64">
  Packets sent in the last second
</ResponseField>

<ResponseField name="TotalPackets" type="int64">
  Cumulative packets sent since attack start
</ResponseField>

<ResponseField name="Proxies" type="int">
  Number of proxies in use
</ResponseField>

<ResponseField name="Log" type="string">
  Optional log message (e.g., "Miku miku beam from 1.2.3.4:8080 to target.com")
</ResponseField>

## Engine

```go theme={null}
type Engine struct {
    // contains filtered or unexported fields
}
```

Coordinates attack lifecycles, manages concurrent workers, and aggregates statistics.

### NewEngine

```go theme={null}
func NewEngine(reg Registry) *Engine
```

Creates a new Engine with the given worker registry.

**Example:**

```go theme={null}
registry := engine.NewRegistry()
registry.Register(engine.AttackHTTPFlood, http.NewFloodWorker())
registry.Register(engine.AttackTCPFlood, tcp.NewFloodWorker())

eng := engine.NewEngine(*registry)
```

### Start

```go theme={null}
func (e *Engine) Start(
    attackID string,
    parent context.Context,
    params AttackParams,
    proxies []Proxy,
    userAgents []string,
) (<-chan AttackStats, error)
```

Launches a new attack with the given ID. If an attack with the same ID is already running, it will be stopped first.

**Parameters:**

<ParamField name="attackID" type="string">
  Unique identifier for this attack instance
</ParamField>

<ParamField name="parent" type="context.Context">
  Parent context for cancellation propagation
</ParamField>

<ParamField name="params" type="AttackParams">
  Attack configuration parameters
</ParamField>

<ParamField name="proxies" type="[]Proxy">
  List of proxies to rotate through (randomly selected per packet)
</ParamField>

<ParamField name="userAgents" type="[]string">
  List of user agents to rotate through
</ParamField>

**Returns:**

<ResponseField name="statsCh" type="<-chan AttackStats">
  Channel that receives statistics updates every second
</ResponseField>

<ResponseField name="error" type="error">
  Error if attack could not be started (always nil in current implementation)
</ResponseField>

**Behavior:**

* Creates `params.Threads` concurrent worker goroutines (defaults to `runtime.NumCPU()`)
* Each thread fires at intervals defined by `params.PacketDelay`
* Randomly selects a proxy and user agent for each packet
* Aggregates statistics and sends updates every 1 second
* Automatically stops after `params.Duration` elapses
* Closes the stats channel when the attack ends

**Example:**

```go theme={null}
ctx := context.Background()
params := engine.AttackParams{
    Target:      "https://example.com",
    TargetNode:  targetNode,
    Duration:    30 * time.Second,
    PacketDelay: 10 * time.Millisecond,
    Method:      engine.AttackHTTPFlood,
    Threads:     8,
    Verbose:     true,
}

statsCh, err := eng.Start("attack-1", ctx, params, proxies, userAgents)
if err != nil {
    log.Fatal(err)
}

for stat := range statsCh {
    fmt.Printf("PPS: %d, Total: %d\n", stat.PacketsPerS, stat.TotalPackets)
    if stat.Log != "" {
        fmt.Println(stat.Log)
    }
}
```

### Stop

```go theme={null}
func (e *Engine) Stop(attackID string)
```

Cancels a specific attack by ID. Safe to call if attack doesn't exist.

**Example:**

```go theme={null}
eng.Stop("attack-1")
```

### StopAll

```go theme={null}
func (e *Engine) StopAll()
```

Cancels all running attacks.

### IsRunning

```go theme={null}
func (e *Engine) IsRunning(attackID string) bool
```

Checks if a specific attack is currently running.

### GetRunningAttacks

```go theme={null}
func (e *Engine) GetRunningAttacks() []string
```

Returns a list of all running attack IDs.

## Registry

```go theme={null}
type Registry struct {
    // contains filtered or unexported fields
}
```

Maps `AttackKind` values to their worker implementations.

### NewRegistry

```go theme={null}
func NewRegistry() *Registry
```

Creates an empty worker registry.

### Register

```go theme={null}
func (r *Registry) Register(kind AttackKind, w AttackWorker)
```

Registers a worker implementation for an attack kind.

**Example:**

```go theme={null}
registry := engine.NewRegistry()
registry.Register(engine.AttackHTTPFlood, http.NewFloodWorker())
registry.Register(engine.AttackHTTPBypass, http.NewBypassWorker())
registry.Register(engine.AttackHTTPSlowloris, http.NewSlowlorisWorker())
registry.Register(engine.AttackTCPFlood, tcp.NewFloodWorker())
registry.Register(engine.AttackMinecraftPing, game.NewPingWorker())
```

### Get

```go theme={null}
func (r *Registry) Get(kind AttackKind) (AttackWorker, bool)
```

Retrieves the worker for a given attack kind. Returns `false` if not registered.

### ListKinds

```go theme={null}
func (r *Registry) ListKinds() []AttackKind
```

Returns all registered attack kinds.

## Logging Helpers

### SendAttackLog

```go theme={null}
func SendAttackLog(logCh chan<- AttackStats, proxy Proxy, target string)
```

Sends a standardized attack log message to the stats channel. Non-blocking - safe to call on closed channels.

**Log Format:**

```
Miku miku beam from <source> to <target>
```

Where `<source>` is either the proxy address or `<local>` if no proxy is used.

### SendAttackLogIfVerbose

```go theme={null}
func SendAttackLogIfVerbose(
    logCh chan<- AttackStats,
    proxy Proxy,
    target string,
    verbose bool,
)
```

Conditionally sends a log only if `verbose` is true. Used by workers to respect the `AttackParams.Verbose` flag.

**Example (from worker implementation):**

```go theme={null}
func (w *worker) Fire(ctx context.Context, params core.AttackParams, proxy core.Proxy, userAgent string, logCh chan<- core.AttackStats) error {
    // ... perform attack ...
    
    // Send log only if verbose enabled
    core.SendAttackLogIfVerbose(logCh, proxy, params.Target, params.Verbose)
    return nil
}
```

## Architecture

### Concurrency Model

1. **Thread Pool**: Engine spawns `N` worker threads (configured via `AttackParams.Threads`)
2. **Per-Thread Ticker**: Each thread fires at `PacketDelay` intervals
3. **Fire-and-Forget**: Worker `Fire()` calls are dispatched in goroutines to avoid blocking
4. **Statistics Aggregation**: A dedicated goroutine collects and sends stats every second

### Attack Lifecycle

```mermaid theme={null}
sequenceDiagram
    participant Client
    participant Engine
    participant Worker
    participant Target
    
    Client->>Engine: Start(attackID, params, ...)
    Engine->>Engine: Create AttackInstance
    Engine->>Engine: Spawn N thread goroutines
    Engine->>Engine: Start stats aggregator
    Engine-->>Client: Return statsCh
    
    loop Every PacketDelay
        Engine->>Worker: Fire(ctx, params, proxy, ua, logCh)
        Worker->>Target: Send payload
        Worker->>Engine: Send log (if verbose)
    end
    
    loop Every second
        Engine->>Client: statsCh <- AttackStats
    end
    
    Note over Engine: Duration elapsed or Stop() called
    Engine->>Engine: Cancel context
    Engine->>Client: Close statsCh
```

## See Also

* [AttackWorker Interface](/api/attack-workers) - Implementing custom attack methods
* [Proxy Package](/api/proxy) - Loading and filtering proxies
