> ## 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.

# Architecture

> Understanding the internal architecture of Miku Miku Beam

## Overview

Miku Miku Beam is built with a modular architecture that separates concerns into distinct layers: the attack engine, worker implementations, proxy handling, and network utilities.

## Core Components

### Attack Engine

The engine (`internal/engine/engine.go`) is the heart of Miku Miku Beam, coordinating all attack operations and managing worker lifecycles.

<Card title="Engine Responsibilities" icon="gear">
  * Managing multiple concurrent attacks with unique IDs
  * Dispatching work across configurable thread pools
  * Aggregating and reporting real-time statistics
  * Handling graceful start/stop of attack instances
</Card>

#### Key Structures

```go theme={null}
type Engine struct {
    registry Registry
    attacks  map[string]*AttackInstance
}

type AttackInstance struct {
    ID        string
    Params    AttackParams
    Cancel    context.CancelFunc
    StatsCh   chan AttackStats
    TotalSent int64
}
```

#### Attack Lifecycle

1. **Start**: Creates a new attack instance with unique ID
2. **Thread Spawning**: Spawns worker threads (defaults to CPU count)
3. **Packet Dispatch**: Each thread dispatches packets at configured intervals
4. **Stats Aggregation**: Background goroutine aggregates stats every second
5. **Stop**: Context cancellation terminates all workers gracefully

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

The engine automatically:

* Selects random proxies and user agents for each packet
* Tracks total packets sent across all threads
* Prevents duplicate attack IDs by stopping existing instances
* Uses context cancellation for clean shutdown

<Info>
  Thread count defaults to `runtime.NumCPU()` when not specified, optimizing for the host machine's capabilities.
</Info>

### Worker Registry

The registry (`internal/engine/registry.go`) maintains a mapping of attack methods to their implementations.

```go theme={null}
type Registry struct {
    m map[AttackKind]AttackWorker
}
```

#### Attack Methods

Five attack types are registered:

| Attack Kind      | Protocol   | Description                                   |
| ---------------- | ---------- | --------------------------------------------- |
| `http_flood`     | HTTP/HTTPS | High-volume HTTP GET/POST requests            |
| `http_bypass`    | HTTP/HTTPS | Browser-mimicking requests with randomization |
| `http_slowloris` | HTTP/HTTPS | Slow header transmission attack               |
| `tcp_flood`      | TCP        | Raw TCP packet flooding                       |
| `minecraft_ping` | TCP        | Minecraft server status requests              |

### Attack Worker Interface

All attack methods implement the `AttackWorker` interface:

```go theme={null}
type AttackWorker interface {
    Fire(
        ctx context.Context,
        params AttackParams,
        proxy Proxy,
        userAgent string,
        logCh chan<- AttackStats
    ) error
}
```

<Note>
  The `Fire` method should return quickly and not block. The engine dispatches calls concurrently using goroutines.
</Note>

## Attack Parameters

Common parameters shared across all attack methods:

```go theme={null}
type AttackParams struct {
    Target      string           // Raw target string
    TargetNode  targetpkg.Node   // Parsed target details
    Duration    time.Duration    // Attack duration
    PacketDelay time.Duration    // Delay between packets per thread
    PacketSize  int              // Packet/payload size in bytes
    Method      AttackKind       // Attack method type
    Threads     int              // Number of worker threads
    Verbose     bool             // Enable detailed logging
}
```

### Target Parsing

Targets are parsed into a `Node` structure (`pkg/target/node.go`) that handles:

* **URLs with scheme**: `http://example.com:8080/path`
* **Host:port notation**: `192.168.1.1:80`
* **Hostname only**: `example.com` (defaults to port 80)

```go theme={null}
type Node struct {
    Raw    string  // Original input
    Scheme string  // "http", "https", or ""
    Host   string  // Hostname or IP
    Port   int     // Port number
    Path   string  // URL path component
    Query  string  // URL query string
    IsURL  bool    // Whether input was a full URL
}
```

The `ToURL()` method automatically infers HTTPS for port 443, otherwise defaults to HTTP for L7 attacks.

## Statistics & Monitoring

The engine provides real-time attack statistics through a channel:

```go theme={null}
type AttackStats struct {
    Timestamp    time.Time
    PacketsPerS  int64  // Packets sent in last second
    TotalPackets int64  // Cumulative packet count
    Proxies      int    // Number of proxies in use
    Log          string // Individual worker logs
}
```

### Aggregation Strategy

* Each worker thread increments a shared counter (with mutex protection)
* Background goroutine samples counter every second
* Calculates delta to determine packets/second rate
* Sends stats only when there's activity or on first tick

## Concurrency Model

### Thread Distribution

```
Engine.Start()
  └─> Spawns N threads (N = params.Threads or CPU count)
       ├─> Thread 0: ticker loop → dispatch → random proxy/UA → Fire()
       ├─> Thread 1: ticker loop → dispatch → random proxy/UA → Fire()
       ├─> ...
       └─> Thread N-1: ticker loop → dispatch → random proxy/UA → Fire()
  └─> Stats aggregator goroutine (1 per attack)
       └─> Ticks every second → calculate rate → send to StatsCh
```

Each `Fire()` call is dispatched in its own goroutine for non-blocking operation.

### Context Cancellation

```go theme={null}
ctx, cancel := context.WithCancel(parent)
```

All workers respect context cancellation:

* Engine stores `cancel` function in `AttackInstance`
* `Stop()` calls cancel, propagating to all goroutines
* Workers check `<-ctx.Done()` and exit gracefully
* Stats channel is closed after all workers terminate

<Warning>
  The engine automatically stops existing attacks with the same ID when starting a new one. Ensure unique IDs for concurrent attacks.
</Warning>

## Configuration

Global configuration (`internal/config/config.go`) uses TOML format:

```go theme={null}
type Config struct {
    ProxiesFile    string  // default: "data/proxies.txt"
    UserAgentsFile string  // default: "data/uas.txt"
    ServerPort     int     // default: 3000
    AllowedOrigin  string  // default: "http://localhost:5173"
}
```

Configuration is loaded with fallback to defaults if file is missing or invalid.

## Network Layer

Network utilities (`internal/netutil/`) provide abstraction for:

* **HTTP clients** with proxy support (HTTP, HTTPS, SOCKS4, SOCKS5)
* **TCP connections** with proxy tunneling (HTTP CONNECT, SOCKS)
* **TLS wrapping** for secure connections
* **Browser mimicking** with realistic headers

See [Proxy Configuration](/proxy-configuration) for detailed proxy handling.
