> For the complete documentation index, see [llms.txt](https://docs.bitplanet.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.bitplanet.ai/developer-guides/security-considerations.md).

# Security Considerations

## DoS Prevention

The module implements bounded processing limits as **constants**:

```go
// Constants (not tunable parameters)
MaxBatchSize         = 100  // Max items per batch operation
MaxAddressesPerMint  = 100  // Max addresses per mint call
MaxMarketCapHistory  = 100  // Max market cap snapshots per AI

// Parameters (if defined in Params)
MaxTensorRowsPerBlock  // Max tensor rows per transaction
MaxAisForRewards       // Max AIs processed per block
```

**Validation:**

* All array inputs validated for length
* Tensor processing stops at limits
* Batch minting capped at MaxAddressesPerMint (constant)

## Arithmetic Safety

All mathematical operations include overflow detection:

```go
// Example: Safe accumulation with overflow check
func (k Keeper) CalculateOresToMint(aiTensors []*types.AITensor) (map[string]uint64, error) {
    oresToMint := make(map[string]uint64)

    for _, aiTensor := range aiTensors {
        for _, row := range aiTensor.Tensor {
            totalContributions, err := types.SumContributions(row.Contributions)
            if err != nil {
                return nil, fmt.Errorf("overflow while summing: %w", err)
            }

            current := math.NewIntFromUint64(oresToMint[row.Address])
            updated := current.Add(math.NewIntFromUint64(totalContributions))
            if !updated.IsUint64() {
                return nil, fmt.Errorf("total cores exceed uint64 limit")
            }
            oresToMint[row.Address] = updated.Uint64()
        }
    }
    return oresToMint, nil
}
```

## Two-Phase Validation

Prevents state inconsistencies where checks pass but execution fails:

```go
// Phase 1: Validate grant exists
grant, found := k.GetCoreGrantApplication(ctx, requesterAddr)
if !found {
    return fmt.Errorf("No Core Grant Application found for: %s", requesterAddr)
}

// Phase 2: Check sufficient allocation remains
totalOresNeeded := calculateTotal(aiTensors)
if grant.CoreAllocation < totalOresNeeded {
    return fmt.Errorf("need: %d, have: %d", totalOresNeeded, grant.CoreAllocation)
}

// Phase 3: Atomic state update
grant.CoreAllocation -= totalOresNeeded
k.SetCoreGrantApplication(ctx, requesterAddr, grant)  // Requires requester address
```

## Credential Security

The project implements secure credential management with explicit initialization:

**Security Features:**

* **No Hardcoded Secrets**: All credentials stored in `.env` file (gitignored)
* **Automatic File Permissions**: `.env` automatically set to 600 (owner read/write only)
* **Environment Validation**: Multi-layer checks prevent test credentials in production
* **Explicit Initialization**: No auto-generation during node startup
* **Deterministic Mode**: Reproducible test credentials for consistent testing

**Workflow:**

```bash
# Generate credentials (required before first run)
make init-env-deterministic  # For local dev (same credentials every time)
make init-env               # For random credentials

# Validate configuration
make validate-env           # Checks .env completeness

# Start testnet (now validates .env exists first)
make sh-testnet
```

**Production Safety:**

* Test credentials blocked in `ENVIRONMENT=staging` or `ENVIRONMENT=prod`
* Validation at node startup and in test scripts
* Must manually provide funded credentials for non-local environments

## Next Steps

* Understand module security features in [Module API](/developer-guides/module-api.md)
* Review contract security patterns in [Smart Contract Integration](/developer-guides/smart-contract.md)
* See security in action in [Module Interaction](/developer-guides/module-interaction.md)
* Apply security practices in [Quick Start](/developer-guides/quick-start.md)
