## CosmWasm Vulnerability Patterns & Audit Checks

> Vulnerability patterns specific to CosmWasm smart contracts (Rust contracts on `wasmd`). Referenced by [SKILL.md](../SKILL.md).

### 1 WRAPPING OVERFLOW IN UINT256/512 ARITHMETIC

**Description**: CosmWasm's `Uint256`, `Uint512`, `Int256`, and `Int512` types used wrapping (modular) math for `pow()` and `neg()` instead of panicking on overflow. This means arithmetic silently wraps around on overflow, producing incorrect results. Token swap calculations, LP share pricing, and any exponentiation-based math become manipulable. `Uint128` and `Uint64` are NOT affected (they already used checked math).

**Affected versions**: `cosmwasm-std` < 1.4.4, < 1.5.4, < 2.0.2

**Detection Patterns**:
```rust
// VULNERABLE: Uint256/512 pow used wrapping math (CWA-2024-002)
let price = Uint256::from(base_price).pow(exponent);
// If result overflows 256 bits, it wraps silently instead of panicking
// Token swap calculations yield incorrect amounts
// LP share pricing becomes manipulable

// VULNERABLE: Int256/512 neg() wraps on MIN value
let negated = Int256::MIN.neg();
// Wraps to Int256::MIN instead of panicking (two's complement)
```

**What to Check**:
- [ ] `cosmwasm-std` version is patched (>= 1.4.4, >= 1.5.4, >= 2.0.2)
- [ ] Any `Uint256::pow()`, `Uint512::pow()`, `Int256::pow()`, `Int512::pow()` usage reviewed for overflow possibility
- [ ] `Int256::neg()` / `Int512::neg()` not called on `MIN` values
- [ ] Contracts using large-number exponentiation for pricing, interest rates, or AMM curves are audited for wrapping behavior on older `cosmwasm-std`

**Mitigation**:
```rust
// SECURE: Use patched cosmwasm-std (>= 2.0.2) where pow() panics on overflow
// OR: Use checked_pow() if available, or manually validate bounds before exponentiation
let max_safe = Uint256::from(2u128).pow(128); // Know your bounds
assert!(base_price < max_safe, "overflow risk");
let price = Uint256::from(base_price).pow(exponent);
```

**References**:
- [CWA-2024-002](https://github.com/CosmWasm/advisories/blob/main/CWAs/CWA-2024-002.md)

---

### 2 NON-DETERMINISTIC QUERIES FROM COSMWASM CONTRACTS

**Description**: CosmWasm contracts can call Cosmos SDK queries via Stargate queries. Queries annotated with `cosmos.query.v1.module_query_safe` are callable from within contracts during execution. If such a query is non-deterministic (returns different results on different validators for the same block height) or consumes variable gas, it causes consensus failures. This is especially dangerous because the query runs inside contract execution which is on the consensus path.

**Detection Patterns**:
```go
// VULNERABLE: Query marked as module_query_safe but produces non-deterministic results
// In proto definition:
// option (cosmos.query.v1.module_query_safe) = true;
//
// But the query handler iterates a map, uses floating point, or returns
// results that vary by node (e.g., local mempool state, peer info)
func (q queryServer) UnsafeQuery(ctx context.Context, req *types.QueryRequest) (*types.QueryResponse, error) {
    // Non-deterministic: map iteration order
    results := make(map[string]string)
    for k, v := range results { // Different order per validator!
        // ...
    }
    return &types.QueryResponse{Data: serialize(results)}, nil
}
```

```rust
// CosmWasm contract calling a Stargate query during execution
let response: QueryResponse = deps.querier.query(&QueryRequest::Stargate {
    path: "/custom.module.v1.Query/UnsafeQuery".to_string(),
    data: request.encode_to_vec().into(),
})?;
// If UnsafeQuery is non-deterministic, this contract execution
// produces different state on different validators → chain halt
```

**What to Check**:
- [ ] ALL queries annotated with `cosmos.query.v1.module_query_safe` are deterministic
- [ ] Module-query-safe queries always consume the same gas for the same input (variable gas consumption causes consensus failure)
- [ ] No map iteration, floating point, system time, or other non-deterministic operations in module-query-safe query handlers
- [ ] Stargate query allowlist reviewed — only deterministic queries are permitted

**References**:
- [CWA-2024-006](https://github.com/CosmWasm/advisories/blob/main/CWAs/CWA-2024-006.md)

---

### 3 IBC REENTRANCY VIA COSMWASM SUBMESSAGES

**Description**: CosmWasm's submessage mechanism (`SubMsg`) amplifies the IBC reentrancy / CEI violation described in [IBC_VULNERABILITY_PATTERNS.md §16](IBC_VULNERABILITY_PATTERNS.md#16-ibc-reentrancy--cei-violations). When `ibc-hooks` middleware invokes a CosmWasm contract on an IBC callback (e.g., `OnTimeoutPacket`), the contract can re-enter via submessages before the original callback's state changes are finalized. See IBC §16 for the full Go-side vulnerability, affected versions, detection patterns, and checklist.

This section covers the **CosmWasm-specific attack surface**: how Rust contracts exploit the underlying IBC CEI violation.

**Vulnerable chain requirements**: ALL of these must be true:
1. IBC-enabled with vulnerable ibc-go version (see [IBC §16](IBC_VULNERABILITY_PATTERNS.md#16-ibc-reentrancy--cei-violations) for versions)
2. CosmWasm-enabled with permissionless contract uploads
3. `ibc-hooks` middleware wrapping ICS-20 transfer

**CosmWasm Exploit Pattern**:
```rust
// CosmWasm contract exploiting IBC reentrancy via submessages
#[entry_point]
pub fn sudo(deps: DepsMut, env: Env, msg: SudoMsg) -> Result<Response, ContractError> {
    match msg {
        // Called by ibc-hooks on IBC packet timeout
        SudoMsg::IBCLifecycleComplete { .. } => {
            // Re-enter by dispatching another timeout via submessage
            let msg = CosmosMsg::Stargate {
                type_url: "/ibc.core.channel.v1.MsgTimeout".to_string(),
                value: craft_timeout_msg(),  // Same packet, same sequence
            };
            Ok(Response::new().add_submessage(SubMsg::new(msg)))
            // Submessage executes before parent's state changes are finalized
            // Double-refund: tokens refunded twice for the same timed-out packet
        }
    }
}
```

**CosmWasm-Specific Checks** (in addition to [IBC §16](IBC_VULNERABILITY_PATTERNS.md#16-ibc-reentrancy--cei-violations) checklist):
- [ ] `ibc-hooks` middleware usage reviewed — this is the bridge between IBC callbacks and CosmWasm execution
- [ ] If CosmWasm uploads are permissionless, the attack surface is maximal — consider permissioned uploads or code review requirements

**Grep Patterns** (use Grep tool with `glob: "*.go"`):
- `ibc-hooks|ibchooks` in `x/` and `app/` — hooks middleware presence
- `InstantiateDefaultPermission|StoreCodeAuthorization` in `x/` and `app/` — upload permissions

**References**: See [IBC_VULNERABILITY_PATTERNS.md §16](IBC_VULNERABILITY_PATTERNS.md#16-ibc-reentrancy--cei-violations) for full references.

---

### SUMMARY

| # | Pattern | Impact | Known Incident / Reference |
|---|---------|--------|---------------------------|
| 1 | Wrapping overflow in Uint256/512 | Fund manipulation (pricing, LP shares) | CWA-2024-002 |
| 2 | Non-deterministic queries from CosmWasm | Chain halt (consensus failure) | CWA-2024-006 |
| 3 | IBC reentrancy via CosmWasm submessages | Fund theft ($150M+ at risk, $6.4M stolen) | ASA-2024-007, Terra exploit |

---

### References

- **CosmWasm Security Advisories**: https://github.com/CosmWasm/advisories
- **ibc-go Security Advisories**: https://github.com/cosmos/ibc-go/security/advisories
- **Asymmetric Research**: "Cosmos IBC Reentrancy Infinite Mint" — https://blog.asymmetric.re/cosmos-ibc-reentrancy-infinite-mint/
