# Technical deep Dive

### Overview

The Python files implement a **Pedersen Commitment** scheme for privacy-preserving encrypted values and a Flask web application to facilitate user interaction with the model training process. This includes functionalities for file uploads, model training, and encrypted data handling.

#### 1. **Pedersen Commitment Implementation**

**Imports**

```python
pythonCopy codeimport os
import sys
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
```

* The `os` module is used for file handling and generating random bytes.
* The `sys` module allows interaction with the Python interpreter, particularly for command-line arguments.
* The `cryptography` library provides the necessary cryptographic primitives, specifically for RSA key generation.

**Prime Generation**

```python
pythonCopy codedef generate_large_prime(bit_length):
    return rsa.generate_private_key(public_exponent=65537, key_size=bit_length, backend=default_backend()).private_numbers().p
```

* This function generates a large prime number using RSA. The `bit_length` parameter specifies the size of the prime.
* It leverages RSA's private key generation to extract the prime ppp.

**Pedersen Commitment Class**

```python
pythonCopy codeclass PedersonCommitment:
    def __init__(self, security=1024):
        self.p = generate_large_prime(security)
        self.q = generate_large_prime(security * 2)
        self.g = int.from_bytes(os.urandom(32), 'big') % self.q
        self.s = int.from_bytes(os.urandom(32), 'big') % self.q
        self.h = pow(self.g, self.s, self.q)
```

* **Initialization**: The constructor initializes the Pedersen commitment scheme:
  * Generates two large primes ppp and qqq.
  * Initializes the generator ggg and a secret sss from random bytes, ensuring ggg is less than qqq.
  * Computes hhh using ggg raised to the power of sss modulo qqq.

**Commitment Methods**

```python
pythonCopy code    def commit(self, x):
        r = int.from_bytes(os.urandom(32), 'big') % self.q
        c = (pow(self.g, x, self.q) * pow(self.h, r, self.q)) % self.q
        return c, r
```

* **Commit**: This method takes a value xxx and commits it using a random value rrr:
  * The commitment ccc is computed using gxg^xgx and hrh^rhr, both modulo qqq.
  * Returns the commitment and the random value rrr.

```python
pythonCopy code    def verify(self, c, x, r):
        return c == (pow(self.g, x, self.q) * pow(self.h, r, self.q)) % self.q
```

* **Verify**: Validates a commitment against the original value and randomness, ensuring that the provided ccc matches the expected computation.

```python
pythonCopy code    def add_commitments(self, c1, c2):
        return (c1 * c2) % self.q
```

* **Add Commitments**: Allows the addition of two commitments, crucial for aggregating multiple encrypted values.

#### Utility Functions

```python
pythonCopy codedef encrypt_cost(cost):
    cost_int = int(cost)
    c, r = commitment.commit(cost_int)
    print(f"Encrypted cost: {c}")
    sys.stdout.flush()
    return c, r
```

* **Encrypt Cost**: Takes a cost as input, commits it using the Pedersen scheme, and prints the encrypted value. It returns the commitment and the random value.

```python
pythonCopy codedef aggregate_commitments(commitments):
    result = 1
    for c in commitments:
        result = commitment.add_commitments(result, c)
    return result
```

* **Aggregate Commitments**: Iterates through a list of commitments, adding them together to form a single aggregated commitment.

#### Flask Web Application

**Flask Setup**

```python
pythonCopy codeapp = Flask(__name__)
CORS(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
```

* Initializes a Flask application and enables CORS (Cross-Origin Resource Sharing) to allow requests from other origins.

**File Upload Functions**

```python
pythonCopy codedef allowed_file_dataset(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS_DATASET

def allowed_file_model(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS_MODEL
```

* **File Validation**: These utility functions check if uploaded files have the correct extensions (CSV for datasets and PKL/PY for models).

**Routes**

```python
pythonCopy code@app.route('/')
def index():
    return render_template('index.html')
```

* **Index Route**: Renders the main page of the application.

```python
pythonCopy code@app.route('/model_trainer', methods=['POST'])
def model_trainer():
    ...
```

* **Model Trainer Route**: Handles dataset uploads. It checks if the uploaded file is valid, saves it to the specified directory, and redirects to the index page.

```python
pythonCopy code@app.route('/model_upload', methods=['POST'])
def model_upload():
    ...
```

* **Model Upload Route**: Accepts model files via JSON data in the request body, saves them, and confirms successful uploads.

```python
pythonCopy code@app.route('/stake')
def stake():
    ...
```

* **Stake Route**: Executes a bash script for model training. It captures the output and returns it as a JSON response, providing feedback on the training process.
