# API-007: No Reimplementation of Upstream Functionality

> **Authoritative requirement:** [API-007](../NORMATIVE.md#API-007)
> **Verification:** [VERIFICATION.md](../VERIFICATION.md)
> **Tracking:** [TRACKING.yaml](../TRACKING.yaml)
> **Spec reference:** [SPEC.md](../../../../resources/SPEC.md) — Sections 1, 2, 3

---

## Summary

`dig-clvm` MUST NOT contain custom implementations of any functionality already provided by the Chia crate ecosystem. This includes CLVM execution, condition parsing, tree hashing, currying, BLS signature verification, opcode definitions, and cost constants. All of these MUST come from the upstream crates (`clvmr`, `clvm-utils`, `clvm-traits`, `chia-consensus`, `chia-bls`, `chia-sdk-types`, `chia-sdk-driver`). The crate is a thin orchestration layer, not a reimplementation.

This is the most important architectural constraint in the entire crate. Chia L1 parity is achieved "by construction" -- because `dig-clvm` delegates to the exact same Rust libraries that Chia full nodes use, the behavior is identical by definition. Any custom reimplementation, no matter how correct it appears, introduces a divergence risk. A reimplemented tree hash function could produce different results for edge cases. A reimplemented condition parser could miss a new opcode. A reimplemented BLS verifier could have subtle constant-time bugs. By using upstream directly, these risks are eliminated.

The SPEC (Section 1) states this explicitly as Goal #1: "Maximize reuse -- Use `chia-consensus`, `chia-sdk-types`, `chia-sdk-driver`, `clvmr`, `clvm-utils`, `clvm-traits`, `chia-bls`, and `chia-sdk-test` directly. Never reimplement what they provide." Goal #2 reinforces it: "1:1 Chia L1 parity -- Identical behavior to Chia full nodes because we use the same libraries they use." The Non-Goals section explicitly lists "Reimplementing anything the Chia crates already provide" as out of scope.

---

## Specification

### Prohibited Reimplementations

The following categories of functionality MUST NOT be reimplemented in `dig-clvm/src/`:

| Category | Upstream Source | Prohibited Custom Code |
|---|---|---|
| CLVM execution | `clvmr::run_program()` | Custom CLVM interpreter, bytecode evaluator, or dialect |
| Condition parsing | `chia-consensus` conditions module | Custom condition opcode parser, condition struct definitions |
| Tree hashing | `clvm_utils::tree_hash()` | Custom SHA256-based tree hash (atom: `sha256(0x01\|\|data)`, pair: `sha256(0x02\|\|left\|\|right)`) |
| Currying | `clvm_utils::CurriedProgram`, `curry_tree_hash()` | Custom curry/uncurry implementations |
| BLS signatures | `chia_bls::aggregate_verify()`, `verify()`, `sign()` | Custom BLS12-381 operations, pairing checks, key derivation |
| Opcode constants | `chia_consensus::opcodes` | Custom `AGG_SIG_ME`, `CREATE_COIN`, etc. constant definitions |
| Cost constants | `chia_consensus` cost modules | Custom `AGG_SIG_COST`, `CREATE_COIN_COST`, etc. (L2-specific cost *limits* like `L2_MAX_COST_PER_BLOCK` are allowed) |
| Spend bundle execution | `chia_consensus::run_spendbundle()` | Custom spend-by-spend CLVM execution loop |
| Signature validation | `chia_consensus::validate_clvm_and_signature()` | Custom signature message construction or verification flow |
| Condition types | `chia_sdk_types::Condition`, `Conditions` | Custom condition enum or builder |
| Puzzle drivers | `chia_sdk_driver::Layer`, `SpendContext` | Custom puzzle parsing or spend construction framework |

### What dig-clvm IS Allowed to Implement

The crate's own code (in `src/consensus/`) is limited to L2-specific orchestration:

| Component | Why It Is Not a Reimplementation |
|---|---|
| `ValidationContext` | L2 chain state struct -- no equivalent in upstream |
| `ValidationConfig` | L2-specific parameters (configurable cost limits, flags) |
| `validate_spend_bundle()` | Orchestrates upstream `run_spendbundle()` with L2 rules |
| `validate_block()` | Orchestrates upstream `run_block_generator2()` with L2 rules |
| `build_block_generator()` | Assembles bundles into block generator using upstream `solution_generator_backrefs()` |
| `SpendResult` | Output struct -- extracts additions/removals from upstream `OwnedSpendBundleConditions` |
| `ValidationError` | L2-specific error enum wrapping upstream errors |
| BLS cache management | Passes `BlsCache` through to upstream functions |
| `L2_MAX_COST_PER_BLOCK` | L2-specific cost constant (not an upstream opcode/cost reimplementation) |

### Heuristic Tests

If any of the following patterns are found in `dig-clvm/src/`, it is likely a reimplementation violation:

- `sha256` called directly on CLVM node data (should use `tree_hash()`)
- Manual `(a (q . program) args)` construction (should use `CurriedProgram`)
- BLS pairing operations or `G1`/`G2` point arithmetic
- Opcode byte constants defined as `const AGG_SIG_ME: u8 = ...`
- Cost constants like `const AGG_SIG_COST: u64 = 1_200_000`
- A loop over `CoinSpend` items calling `run_program()` individually (should use `run_spendbundle()`)
- Custom `enum Condition { CreateCoin(...), AggSig(...), ... }`

---

## Acceptance Criteria

- [ ] No custom CLVM execution loop exists in `dig-clvm/src/` -- all execution goes through `run_spendbundle()` or `validate_clvm_and_signature()`
- [ ] No custom tree hash implementation exists -- all tree hashing uses `clvm_utils::tree_hash()` or `curry_tree_hash()`
- [ ] No custom BLS verification exists -- all signature checks use `chia_bls::aggregate_verify()` or upstream validation functions
- [ ] No custom opcode or cost constants are defined -- all use `chia_consensus::opcodes` and upstream cost values
- [ ] No custom condition enum or parser exists -- all condition handling uses `chia_sdk_types::Condition` and `chia_consensus::conditions`
- [ ] The crate's own code is confined to orchestration (context, config, result, error, cache management) as listed in the allowed table

---

## Implementation Notes

- Helper functions that compose upstream APIs are acceptable. For example, a function that calls `tree_hash()` and then compares the result to a puzzle hash is not a reimplementation -- it is orchestration.
- Test code may use lower-level upstream APIs (e.g., `run_program()` directly) for testing specific behaviors. This is acceptable because test code is not shipped.
- If upstream crates are missing functionality that `dig-clvm` needs, the correct approach is to contribute upstream or request the feature, not to reimplement it locally.
- The `L2_MAX_COST_PER_BLOCK = 550_000_000_000` constant is L2-specific and does not exist upstream. This is allowed because it is a *configuration value*, not a reimplementation of cost accounting logic.

---

## Verification

### Test Plan

1. **Source code audit for reimplementation patterns**:
   ```bash
   # Check for custom tree hashing
   grep -rn "sha256.*0x01\|sha256.*0x02\|atom_hash\|pair_hash" dig-clvm/src/

   # Check for custom CLVM execution
   grep -rn "run_program\|ChiaDialect::new" dig-clvm/src/

   # Check for custom opcode constants
   grep -rn "const AGG_SIG\|const CREATE_COIN\|const ASSERT_" dig-clvm/src/

   # Check for custom BLS operations
   grep -rn "pairing\|G1Element\|G2Element\|bls12_381" dig-clvm/src/

   # Check for custom condition enum
   grep -rn "enum Condition\|enum ConditionOpcode" dig-clvm/src/
   ```
   - All commands MUST produce no output (or only false positives that are clearly not reimplementations).

2. **Dependency usage verification**:
   - Confirm that `validate_spend_bundle()` calls `chia_consensus::spendbundle_conditions::run_spendbundle()` internally.
   - Confirm that BLS verification is delegated to `chia_consensus::spendbundle_validation::validate_clvm_and_signature()` or `chia_bls::aggregate_verify()`.

3. **L1 parity by construction**:
   - Run the parity test suite (`tests/parity_tests.rs`) which validates that `dig-clvm` produces identical results to known Chia L1 outputs. This is the ultimate verification that no reimplementation divergence exists.

4. **Code line count check**:
   - The total lines of code in `dig-clvm/src/` should be relatively small (estimated <1000 lines). If it is significantly larger, investigate whether functionality is being reimplemented.

---

## Source Citations

- [SPEC.md Section 1](../../../../resources/SPEC.md) — Goals: "Maximize reuse", "1:1 Chia L1 parity", Non-Goals: "Reimplementing anything the Chia crates already provide"
- [SPEC.md Section 2](../../../../resources/SPEC.md) — Complete inventory of upstream crate functionality
- [SPEC.md Section 3](../../../../resources/SPEC.md) — "What dig-clvm Adds" vs. what comes from upstream

---

## References

- [API-001](API-001.md) — Re-exports define what comes from upstream
- [API-008](API-008.md) — Module structure constrains where own code lives
- [API-002](API-002.md) — Dependency set defines the upstream crate surface
