> ## Documentation Index
> Fetch the complete documentation index at: https://docs.verity.usher.so/llms.txt
> Use this file to discover all available pages before exploring further.

# zkTLS Implementation

> This document provides an overview of the Verity DP modules utilised in the zkTLS implementation, explaining where and why they are used.

## Modules Overview

### `ic/managed/verifier`

* **Purpose**: The Verity Verifier canister is responsible for verifying TLS proofs, performing pre-computations for the ZK VDPE, and producing proofs of computation for external verification.
* **Usage**:
  * **Verification**: Verifies TLS proofs via inter-canister calls or external system updates.
  * **Pre-computation**: Prepares computations for the ZK VDPE.
  * **Proof Production**: Generates proofs for verification in systems like a zkVM.
  * **Security Protocol**: Orchestrates a protocol to ensure the security and integrity of Verity Notary network nodes.

### `rs/verity-client`

* **Purpose**: A Rust SDK for interfacing with a Verity Prover.
* **Usage**: Used in the host application to generate TLS attestations and interact with the Verity Prover.
  * [**Code Reference**](https://github.com/usherlabs/verity-dp/blob/347eb2e58a9abc1b712402c1a068ae22faec1d1a/examples/zktls/host/src/main.rs#L8-L64):

    ```rust theme={null}
    use verity_client::client::{VerityClient, VerityClientConfig};
    use verity_verify_remote::{
        config::Config,
        ic::{Verifier, DEFAULT_IC_GATEWAY_LOCAL},
    };
    use verity_verify_tls::verify_proof;
    // use verity_dp_zk_host::generate_groth16_proof;

    pub const DEFAULT_PROVER_URL: &str = "http://127.0.0.1:8080";
    pub const DEFAULT_VERITY_VERIFIER_ID: &str = "bkyz2-fmaaa-aaaaa-qaaaq-cai";

    /// The input parameters for the zk_circuit
    ///
    /// Contains the details needed for proof verification
    #[derive(Serialize, Deserialize, Debug, Clone)]
    pub struct ZkInputParam {
        /// Session header information
        pub tls_proof: String,
        /// Proof of substrings
        pub remote_verifier_proof: String,
        /// Remote verifier's ECDSA public key
        pub remote_verifier_public_key: String,
    }

    #[derive(Deserialize, Serialize, Debug, Clone)]
    pub struct RemoteVerificationProof {
        pub results: Vec<String>,
        pub root: String,
        pub signature: String,
    }

    #[tokio::main()]
    async fn main() -> anyhow::Result<()> {
        env::set_var("RISC0_DEV_MODE", "1"); // Included to ensure the zkVM prover is fast for demo purposes.

        // Initialize tracing. In order to view logs, run `RUST_LOG=info cargo run`
        tracing_subscriber::fmt()
            .with_env_filter(tracing_subscriber::filter::EnvFilter::from_default_env())
            .init();

        // Entry point of the program
        println!("Hello Verity zkTLS Demo!");

        // -------------------- // THE PLAN // ------------------------
        // Generate a TLS attestation using Verity Client
        // Pepare the TLS proof for the guest
        // Call the zkVM guest for zkSNARK
        // Verify the SNARK
        // -------------------- // THE PLAN // ------------------------

        println!("Proving a GET request using VerityClient...");

        let config = VerityClientConfig {
            prover_url: String::from(DEFAULT_PROVER_URL),
        };

        let client = VerityClient::new(config);
    ```

### `rs/verify-remote`

* **Purpose**: Sends TLS proofs/attestations to the IC for partial or full verification.
* **Usage**:
  * **Partial Verification**: Used when leveraging the zkVM to maintain high performance by partially verifying proofs.
  * **Full Verification**: Used when the data processed is public.
  * [**Code Reference**](https://github.com/usherlabs/verity-dp/blob/347eb2e58a9abc1b712402c1a068ae22faec1d1a/examples/zktls/host/src/main.rs#L119-L150):

    ```rust theme={null}
    let rv_identity_path = "fixtures/identity.pem";
    let rv_id = DEFAULT_VERITY_VERIFIER_ID.to_string();
    let rv_config = Config::new(
        DEFAULT_IC_GATEWAY_LOCAL.to_string(),
        rv_identity_path.to_string(),
        rv_id,
    );

    // 2. Create verifier from a config file
    let remote_verifier = Verifier::from_config(&rv_config).await.unwrap();

    // 3. Extract our the public/private sub-proofs
    let proof_value: serde_json::Value = serde_json::from_str(&response.proof).unwrap();
    let session = proof_value["session"].to_string();

    // 4. Verify a proof and get the response
    let verified_by_remote = remote_verifier
        .verify_proof(
            // You can verify multiple proofs at once
            vec![session],
            notary_pub_key,
        )
        .await
        .unwrap();

    // Assuming `verified_by_remote` is of type `VerifierResponse` and has a field `results`
    // which is a vector of some type that has a method `get_content()`.
    let leaves: Vec<String> = verified_by_remote
        .results
        .iter()
        .map(|proof_response| proof_response.get_content())
        .collect();
    ```

### `rs/verify-local`

* **Purpose**: Performs TLS proof verification by combining remote proof of computation verification with private facets of the TLS proof.
* **Usage**: Primarily used in the zkVM guest environment to verify TLS proofs.
  * [**Code Reference**](https://github.com/usherlabs/verity-dp/blob/347eb2e58a9abc1b712402c1a068ae22faec1d1a/examples/zktls/methods/guest/src/main.rs#L4-L57):

    ```rust theme={null}
    use verity_verify_local::{self, ecdsa::validate_ecdsa_signature, merkle::validate_merkle_tree};
    use verity_verify_tls::verify_proof;

    /// The input parameters for the zk_circuit
    ///
    /// Contains the details needed for proof verification
    #[derive(Serialize, Deserialize, Debug, Clone)]
    pub struct ZkInputParam {
        /// Session header information
        pub tls_proof: String,
        /// Proof of substrings
        pub remote_verifier_proof: String,
        /// Remote verifier's ECDSA public key
        pub remote_verifier_public_key: String,
    }

    #[derive(Deserialize, Debug, Clone)]
    pub struct RemoteVerificationProof {
        pub results: Vec<String>,
        pub root: String,
        pub signature: String,
    }

    fn main() {
        // Read the input data for this application.
        let input_bytes: Vec<u8> = env::read();

        let params: String = String::from_utf8(input_bytes).unwrap();
        let params: ZkInputParam = serde_json::from_str(params.as_str()).unwrap();

        // Verify the Tls proof -- partially.
        let (recv, sent) = verify_proof(&params.tls_proof).unwrap();

        // Verify the remote verifier's verification of the other part.
        let remote_verification_proof: RemoteVerificationProof =
            serde_json::from_str(params.remote_verifier_proof.as_str()).unwrap();

        // Verify the signature and the Merkle tree root
        let root_hash = &remote_verification_proof.root;
        let is_signature_valid = validate_ecdsa_signature(
            &remote_verification_proof.signature,
            root_hash,
            &params.remote_verifier_public_key,
        )
        .unwrap();
        let is_merkle_valid = validate_merkle_tree(&remote_verification_proof.results, root_hash);

        // Return the verification result
        assert!(is_signature_valid && is_merkle_valid);

        // write public output to the journal
        env::commit(&recv);
        env::commit(&sent);
    }
    ```

### `rs/verity-tls`

* **Purpose**: Abstracts the verification of TLS proofs produced by the Verity Network.
* **Usage**: Utilised in both the host and guest environments to verify TLS proofs.
  * [**Code Reference**](https://github.com/usherlabs/verity-dp/blob/347eb2e58a9abc1b712402c1a068ae22faec1d1a/examples/zktls/host/src/main.rs#L108-L111):
    ```rust theme={null}
    // Totally optional to verify proof on host too.
    // For the sake of this demo, we'll verify the proof on the host to ensure both the zkVM and host agree to the verification.
    let verified_by_host: (String, String) =
        verify_proof(&response.proof, &notary_pub_key).unwrap();
    ```

### `zk`

* **Purpose**: Provides utilities and tests supporting zkVM usage.
* **Usage**: Supports the zkVM environment by providing necessary utilities for proof generation and verification.

## Conclusion

The Verity DP framework provides a comprehensive set of modules that facilitate the generation and verification of zkTLS proofs. Each module plays a crucial role in ensuring the integrity and privacy of data processed within the Verity platform.
