# BLK-006: `validate_block` Entry Point

> **Authoritative requirement:** [BLK-006](../NORMATIVE.md#BLK-006)
> **Verification:** [VERIFICATION.md](../VERIFICATION.md)
> **Tracking:** [TRACKING.yaml](../TRACKING.yaml)
> **Spec reference:** [SPEC.md](../../../../resources/SPEC.md) — Section 5

---

## Summary

BLK-006 defines the public entry point for block-level validation in dig-clvm. The function `validate_block()` accepts a `BlockGenerator`, a slice of `generator_refs` (serialized generators from previous blocks for back-reference resolution), a `ValidationContext`, a `ValidationConfig`, and an optional `BlsCache`, and returns `Result<SpendResult, ValidationError>`. This is the validation counterpart to `build_block_generator()` ([BLK-001](BLK-001.md)), completing the Path B flow.

The function mirrors Chia L1's `_run_block()` at [`multiprocess_validation.py:62`](https://github.com/Chia-Network/chia-blockchain/blob/main/chia/consensus/multiprocess_validation.py#L62) followed by `validate_block_body()` at [`block_body_validation.py:191`](https://github.com/Chia-Network/chia-blockchain/blob/main/chia/consensus/block_body_validation.py#L191). On L1, `_run_block()` executes the generator to produce `SpendBundleConditions`, then `validate_block_body()` checks the results (cost, conditions, signatures, conservation). dig-clvm combines both steps into a single `validate_block()` call.

The optional `BlsCache` parameter enables signature caching across mempool and block validation. When a bundle is first validated in the mempool via `validate_spend_bundle()`, its BLS pairings are cached. When the same bundle later appears in a block, `validate_block()` can reuse those cached pairings, avoiding expensive re-verification. This matches L1's pattern where `BLSCache` is threaded through the validation pipeline.

---

## Specification

### Function Signature

```rust
pub fn validate_block(
    generator: &BlockGenerator,
    generator_refs: &[Vec<u8>],
    context: &ValidationContext,
    config: &ValidationConfig,
    bls_cache: Option<&mut BlsCache>,
) -> Result<SpendResult, ValidationError>;
```

### Parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `generator` | `&BlockGenerator` | The block-level CLVM program to execute. Typically from `BlockGeneratorResult.generator`. |
| `generator_refs` | `&[Vec<u8>]` | Serialized generators from previous blocks, indexed by `block_refs`. Used for cross-block back-reference resolution. Pass `&[]` if no cross-block references exist. |
| `context` | `&ValidationContext` | L2 chain state: height, timestamp, genesis challenge, coin records. |
| `config` | `&ValidationConfig` | Validation parameters: cost limits, flags (e.g., `MEMPOOL_MODE`, `DONT_VALIDATE_SIGNATURE`). |
| `bls_cache` | `Option<&mut BlsCache>` | Optional BLS signature cache. When `Some`, verified pairings are cached/reused. When `None`, all signatures are verified from scratch. |

### Return Value

On success, returns `Ok(SpendResult)` containing:
- `additions`: All coins created by `CREATE_COIN` conditions in the block
- `removals`: All coins spent by the block
- `fee`: Total fee (`sum(removals) - sum(additions)`)
- `conditions`: Full `OwnedSpendBundleConditions` from `chia-consensus`

On failure, returns `Err(ValidationError)` with the specific validation failure (cost exceeded, invalid condition, BLS failure, conservation violation, etc.).

### Behavioral Contract

1. The function MUST execute the generator via `run_block_generator2()` as specified in [BLK-007](BLK-007.md).
2. The function MUST apply all validation checks specified in [BLK-008](BLK-008.md).
3. The function MUST use the `bls_cache` for signature verification when provided.
4. The function MUST NOT perform any I/O, database lookups, or network calls.
5. The `generator_refs` MUST correspond positionally to the `block_refs` from the block that produced the generator.

### L1 Correspondence

| dig-clvm | Chia L1 | Source |
|----------|---------|--------|
| `validate_block()` | `_run_block()` + `validate_block_body()` | [`multiprocess_validation.py:62`](https://github.com/Chia-Network/chia-blockchain/blob/main/chia/consensus/multiprocess_validation.py#L62), [`block_body_validation.py:191`](https://github.com/Chia-Network/chia-blockchain/blob/main/chia/consensus/block_body_validation.py#L191) |
| `generator` parameter | `FullBlock.transactions_generator` | Chia block format |
| `generator_refs` parameter | Previous block generators loaded from DB | [`multiprocess_validation.py:62`](https://github.com/Chia-Network/chia-blockchain/blob/main/chia/consensus/multiprocess_validation.py#L62) |
| `bls_cache` parameter | `BLSCache` passed through validation | L1 validation pipeline |

---

## Acceptance Criteria

- [ ] `validate_block` compiles with the exact signature `(&BlockGenerator, &[Vec<u8>], &ValidationContext, &ValidationConfig, Option<&mut BlsCache>) -> Result<SpendResult, ValidationError>`
- [ ] Calling with a valid generator from `build_block_generator()` returns `Ok(SpendResult)`
- [ ] The returned `SpendResult` contains `additions`, `removals`, `fee`, and `conditions`
- [ ] Calling with an invalid generator (malformed CLVM) returns `Err(ValidationError)`
- [ ] When `bls_cache` is `Some`, verified pairings are stored in the cache after validation
- [ ] The function does not perform any I/O or storage operations

---

## Implementation Notes

- The `BlockGenerator` type is `chia_consensus::run_block_generator::BlockGenerator`, re-exported by dig-clvm.
- The `generator_refs` parameter enables cross-block back-references. For DIG's initial blocks, this will likely be `&[]`. As the chain grows, block producers may reference previous generators to achieve better compression.
- The `BlsCache` enables a key optimization: bundles validated in the mempool have their BLS pairings cached. When those bundles appear in a block, `validate_block()` can skip re-verifying those pairings. This is safe because the individual pairings are the same whether they appear in a single-bundle validation or a block-level validation.
- The `SpendResult` output is identical in structure to what `validate_spend_bundle()` returns, making it easy for callers to handle both Path A and Path B results uniformly.

---

## Verification

### Test Plan

| Test Case | Input | Expected Outcome |
|-----------|-------|------------------|
| Valid block | Generator from `build_block_generator()` with valid bundles | `Ok(SpendResult)` with correct additions/removals |
| Invalid generator | Malformed CLVM bytes as generator | `Err(ValidationError)` |
| Empty generator_refs | Valid generator, `&[]` for refs | Succeeds if generator has no cross-block references |
| BLS cache populated | Valid block, `Some(&mut cache)` where cache starts empty | Cache contains entries after call |
| BLS cache reuse | Validate bundle in mempool (populating cache), then validate block containing same bundle | Block validation reuses cached pairings |
| Type signature check | Compile-time | Function signature matches the spec |

### Verification Method

- **Unit test**: Call `validate_block` with a generator produced by `build_block_generator()`. Assert the result is `Ok(SpendResult)` with the expected additions and removals.
- **Integration test**: Build a block from known bundles, validate it, and compare the `SpendResult` to the expected output.
- **Cache test**: Validate a bundle via `validate_spend_bundle()` with a cache, then validate a block containing that bundle with the same cache. Measure that the block validation is faster (fewer BLS verifications).

---

## Source Citations

- Chia L1 `_run_block()`: [`multiprocess_validation.py:62`](https://github.com/Chia-Network/chia-blockchain/blob/main/chia/consensus/multiprocess_validation.py#L62)
- Chia L1 `validate_block_body()`: [`block_body_validation.py:191`](https://github.com/Chia-Network/chia-blockchain/blob/main/chia/consensus/block_body_validation.py#L191)
- `run_block_generator2()`: [`multiprocess_validation.py:69`](https://github.com/Chia-Network/chia-blockchain/blob/main/chia/consensus/multiprocess_validation.py#L69)

---

## References

- [BLK-001](BLK-001.md) — `build_block_generator` (produces the generator validated here)
- [BLK-004](BLK-004.md) — `BlockGeneratorResult` (contains the `generator` field)
- [BLK-007](BLK-007.md) — Delegates to `run_block_generator2`
- [BLK-008](BLK-008.md) — Same validation checks as `validate_spend_bundle`
- [BLK-009](BLK-009.md) — Round-trip consistency
- [VAL-001](../../validation/NORMATIVE.md#VAL-001) — `validate_spend_bundle` (Path A counterpart)
- [SPEC.md Section 5](../../../../resources/SPEC.md) — Public API surface
- [SPEC.md Section 6](../../../../resources/SPEC.md) — Validation flow (Path B)
