# Samaharam (സമാഹാരം)

> **സമാഹാരം** (samahāram) — Malayalam for "aggregation" or "collection"

**Samaharam** is a high-performance Rust library for aggregating heterogeneous zero-knowledge proofs into a single proof for efficient on-chain verification on EVM chains.

## Features

- **Heterogeneous Aggregation**: Aggregate proofs from different circuits (different verification keys)
- **External Proof Adapters**: Import proofs from snarkjs, gnark, and jf-plonk
- **Variable Public Inputs**: No fixed limit on public inputs per proof
- **BN254 Curve**: Native support for EVM precompiles (ECADD, ECMUL, ECPAIRING)
- **Solidity Verifier Generation**: Automatically generate deployable verifier contracts
- **Parallel Processing**: Optional rayon-based parallelism for high throughput

## Quick Start

```rust
use samaharam::{Bn254, client::{AggregationClient, ProofRequest}, config::Srs};
use std::sync::Arc;

// Initialize with SRS (use Srs::from_ceremony for production)
let srs = Arc::new(Srs::<Bn254>::from_ceremony(powers_g1, tau_g2, g2_gen));
let mut client = AggregationClient::new(srs)?;

// Register circuit types
let transfer_vk = client.register_circuit("transfer", vk);
let deposit_vk = client.register_circuit("deposit", vk);

// Submit proofs
client.submit(ProofRequest {
    circuit_type: "transfer".to_string(),
    proof_data: proof_bytes,
    public_inputs: vec![input1, input2],
})?;

// Aggregate
let result = client.aggregate()?;
println!("Aggregated {} proofs", result.proof_count);
```

## External Proof Adapters

Import proofs from other proving systems:

```rust
use samaharam::adapters::{SnarkjsProof, GnarkPlonkProof, JfPlonkProof, ExternalProof};

// From snarkjs/circom (Groth16)
let proof = SnarkjsProof::from_json(json_data)?;

// From gnark (PLONK)
let proof = GnarkPlonkProof::from_bytes(&proof_bytes)?;

// From jf-plonk/Jellyfish
let proof = JfPlonkProof::from_jf_bytes(&proof_bytes)?;

// Convert to accumulator instances
let instances = proof.to_accumulator_instances()?;
```

## Key Modules

| Module | Description |
|--------|-------------|
| `crypto::kzg` | KZG polynomial commitments with Pippenger MSM |
| `crypto::accumulator` | Proof folding with multi-pairing optimization |
| `adapters` | Import Groth16/PLONK proofs from external systems |
| `solidity::generator` | Generate Solidity verifier contracts |
| `client` | Ergonomic high-level API |

## Solidity Verifier

Two verification methods are available:

```solidity
// Optimized 2-pairing check (~68k gas) - RECOMMENDED
function verifyKzg(
    uint256[2] calldata adjustedCommitment,
    uint256[2] calldata combinedQuotient
) external view returns (bool);

// Groth16-compatible interface (~170k gas)
function verifyGroth16(
    uint256[2] calldata a,
    uint256[2][2] calldata b,
    uint256[2] calldata c,
    uint256[] calldata publicInputs
) external view returns (bool);
```

Generate verifiers:

```rust
use samaharam::solidity::{SolidityGenerator, SolidityConfig};

let gen = SolidityGenerator::<Bn254>::with_config(SolidityConfig::with_name("Verifier"));
let contract = gen.generate_complete(&serialized_vk);
std::fs::write("Verifier.sol", contract)?;
```

## Testing

```bash
cargo test --all-features
```

## Feature Flags

| Flag | Description |
|------|-------------|
| `parallel` | Enable rayon-based parallel processing |
| `solidity` | Enable Solidity verifier generation |
| `testing` | Expose testing utilities for downstream crates |

## Performance

### Gas Efficiency

Samaharam reduces on-chain verification costs by using Batched KZG, which requires only 2 pairings compared to the standard 4 pairings used in Groth16/PLONK verifiers.

| Verification Method | Pairings | Approx. Gas | Use Case |
|---------------------|----------|-------------|----------|
| `verifyKzg` | 2 | ~68,000 | **Recommended** for maximum efficiency |
| `verifyGroth16` | 4 | ~170,000 | Compatibility with existing tooling |

*Note: Gas costs are estimates based on BN254 precompile costs.*

### Off-Chain Optimization

| Operation | Optimization |
|-----------|--------------|
| Multi-scalar multiplication | Pippenger's bucket method with adaptive window |
| Proof verification | Multi-pairing with shared final exponentiation |


## Security

See [docs/SECURITY.md](docs/SECURITY.md) for:
- VK registration trust model
- Threat vectors and mitigations
- On-chain protection recommendations

## Disclaimer

This software is provided "as is", without warranty of any kind, express or implied. The author(s) of this crate ([github.com/ronnakamoto](https://github.com/ronnakamoto)) shall not be held responsible for any damages, losses, or liabilities arising from the use of this software. Use at your own risk.

## License

Licensed under either of

 * Apache License, Version 2.0
   ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license
   ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

## Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.
