> For the complete documentation index, see [llms.txt](https://docs.tresori.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tresori.xyz/introduction/tresori-mpc/architecture.md).

# ARCHITECTURE

## Overview

This is a **3-Party Threshold ECDSA MPC (Multi-Party Computation) Wallet** system built on AWS Nitro Enclaves. It enables distributed key generation and signing where no single party holds the complete private key, ensuring enhanced security for Ethereum wallet operations.

<figure><img src="/files/5ZNpIDER41nZSc8LO2tY" alt=""><figcaption></figcaption></figure>

### DKG (Distributed Key Generation) Flow

<table data-card-size="large" data-view="cards"><thead><tr><th></th></tr></thead><tbody><tr><td><p>Browser (<code>mpc-client.html</code>):</p><ul><li>Generate client polynomial: f_c(x) = a0 + a1*x</li><li>Compute evaluations: f_c(1), f_c(2), f_c(3)</li><li>Compute public commitment: G * a0</li><li>Generate ECDH keypair for encryption</li></ul></td></tr><tr><td>Parent Relays to EnclaveValidates the request body and calls <code>sendToEnclave({ type: 'dkgInit', data: {...} })</code>.</td></tr><tr><td>Enclave Processes DKG Init<br>Generates session ID, ECDH keypair, enclave and server polynomials, derives shared secret, stores pending DKG state in memory.</td></tr><tr><td>Browser Completes DKGDecrypts enclave share, combines: <code>Share 1 = f_c(1) + f_e(1) + f_s(1)</code>, encrypts client share 3, posts to <code>/api/dkg/contribute</code>.</td></tr><tr><td>Parent Generates KMS KeyCalls <code>generateDataKey()</code> from AWS KMS, receives <code>{ plaintextKey, encryptedKey }</code>, then relays with data key to enclave.</td></tr><tr><td>Enclave Completes DKG<br>Computes Share 2 &#x26; Share 3 via Lagrange, derives Ethereum address from combined public key, encrypts shares with AES-256-GCM.</td></tr><tr><td>Parent Stores &#x26; RespondsUploads <code>sessionId.json</code> with encrypted shares and data key to S3. Returns <code>{ ethereumAddress, combinedPublicKey }</code> to browser.</td></tr></tbody></table>

### Complete Signing Flow

## 3. Enclave Flow

The Nitro Enclave is an isolated VM instance with no network access and no persistent storage. All communication is via vsock only, and all cryptographic operations occur within this hardware-isolated environment.

### Enclave Architecture

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                              NITRO ENCLAVE                                   │
│                          (Isolated VM Instance)                              │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   ┌─────────────────────────────────────────────────────────────────────┐   │
│   │                        VSOCK Server (Port 5000)                      │   │
│   │                          src/vsock-server.ts                         │   │
│   └────────────────────────────────┬────────────────────────────────────┘   │
│                                    │                                        │
│                                    ▼                                        │
│   ┌─────────────────────────────────────────────────────────────────────┐   │
│   │                      Handler Router                                  │   │
│   │                    src/handlers/index.ts                             │   │
│   └────────────────────────────────┬────────────────────────────────────┘   │
│                                    │                                        │
│          ┌─────────────────────────┼─────────────────────────┐              │
│          │                         │                         │              │
│          ▼                         ▼                         ▼              │
│   ┌──────────────┐         ┌──────────────┐         ┌──────────────┐        │
│   │   Health     │         │   Key Gen    │         │   Rust       │        │
│   │   Handler    │         │   Handler    │         │   Handler    │        │
│   │ health.ts    │         │ keygen.ts    │         │ rust.ts      │        │
│   └──────────────┘         └──────────────┘         └──────────────┘        │
│                                    │                                        │
│                                    ▼                                        │
│   ┌─────────────────────────────────────────────────────────────────────┐   │
│   │                    In-Memory Session Storage                         │   │
│   │  ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐        │   │
│   │  │  pendingDKGs    │ │ enclaveSessions │ │ walletSessions  │        │   │
│   │  │  Map<string,    │ │ Map<string,     │ │ Map<string,     │        │   │
│   │  │   PendingDKG>   │ │  EnclaveSession>│ │  WalletSession> │        │   │
│   │  └─────────────────┘ └─────────────────┘ └─────────────────┘        │   │
│   └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│   ┌─────────────────────────────────────────────────────────────────────┐   │
│   │                    Cryptographic Operations                          │   │
│   │  • ECDH Key Exchange (prime256v1)                                    │   │
│   │  • AES-256-GCM Encryption/Decryption                                 │   │
│   │  • ECDSA Partial Signing (secp256k1)                                 │   │
│   │  • EC Point Addition for Public Key                                  │   │
│   │  • Lagrange Interpolation                                            │   │
│   └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│   ┌─────────────────────────────────────────────────────────────────────┐   │
│   │                    NSM Attestation (Rust)                            │   │
│   │                      /app/bin/hello_rust                             │   │
│   │  • Generate attestation document                                     │   │
│   │  • Communicate with Nitro Security Module                            │   │
│   └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Request Types Handled by Enclave

| Type            | Handler              | Purpose                         |
| --------------- | -------------------- | ------------------------------- |
| `health`        | healthHandler        | Return enclave health status    |
| `status`        | statusHandler        | Return initialization status    |
| `dkgInit`       | dkgInitHandler       | Initialize DKG session          |
| `dkgContribute` | dkgContributeHandler | Complete DKG, generate shares   |
| `partialSign`   | partialSignHandler   | Create partial ECDSA signature  |
| `simpleSign`    | simpleSignHandler    | Simple signing (legacy)         |
| `signComplete`  | signCompleteHandler  | Complete signing (legacy)       |
| `getSession`    | getSessionHandler    | Retrieve session info           |
| `deleteSession` | deleteSessionHandler | Clear session data              |
| `init`          | initHandler          | Legacy single-step DKG          |
| `runRust`       | runRustHandler       | Execute Rust attestation binary |
| `compute`       | computeHandler       | Generic computation             |

***

## 4. Vsock Communication Flow

### What is Vsock?

Vsock (Virtual Socket) is a communication protocol that enables communication between a virtual machine and its hypervisor/host, or between virtual machines. In AWS Nitro Enclaves, vsock is the **only** communication channel between the parent EC2 instance and the enclave.

### Vsock Configuration

```javascript
// parent-client.js
const VSOCK_PORT = 5000;  // Must match enclave
const PARENT_CID = 3;     // Parent instance always uses CID 3

// Enclave CID is dynamically discovered:
// nitro-cli describe-enclaves → JSON[0].EnclaveCID
```

### Vsock Connection Lifecycle

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                      VSOCK CONNECTION LIFECYCLE                              │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  PARENT INSTANCE                              NITRO ENCLAVE                 │
│  (parent-client.js)                           (vsock-server.ts)             │
│                                                                             │
│  ┌─────────────────────┐                      ┌─────────────────────┐       │
│  │ 1. Create Socket    │                      │ Listening on        │       │
│  │    VsockSocket()    │                      │ Port 5000           │       │
│  └──────────┬──────────┘                      └──────────┬──────────┘       │
│             │                                            │                  │
│             │  2. Connect to Enclave CID:PORT            │                  │
│             │     client.connect(cid, 5000)              │                  │
│             ├────────────────────────────────────────────▶                  │
│             │                                            │                  │
│             │                      3. Accept Connection  │                  │
│             │                         onConnection()     │                  │
│             ◀────────────────────────────────────────────┤                  │
│             │                                            │                  │
│  ┌──────────┴──────────┐                      ┌──────────┴──────────┐       │
│  │ 4. Send Request     │                      │ 5. Receive Data     │       │
│  │    writeTextSync()  │──────JSON Request───▶│    onData()         │       │
│  │    {type, data}     │                      │    Buffer accumulate│       │
│  └──────────┬──────────┘                      └──────────┬──────────┘       │
│             │                                            │                  │
│             │                                 ┌──────────┴──────────┐       │
│             │                                 │ 6. Parse & Process  │       │
│             │                                 │    JSON.parse()     │       │
│             │                                 │    processRequest() │       │
│             │                                 │    Route to handler │       │
│             │                                 └──────────┬──────────┘       │
│             │                                            │                  │
│  ┌──────────┴──────────┐                      ┌──────────┴──────────┐       │
│  │ 8. Receive Response │                      │ 7. Send Response    │       │
│  │    onData()         │◀─────JSON Response───│    writeTextSync()  │       │
│  │    Parse JSON       │     + newline        │    {success, data}  │       │
│  └──────────┬──────────┘                      └──────────┬──────────┘       │
│             │                                            │                  │
│  ┌──────────┴──────────┐                      ┌──────────┴──────────┐       │
│  │ 9. Close Connection │                      │ 10. Close Socket    │       │
│  │    client.end()     │                      │     setTimeout 10ms │       │
│  └─────────────────────┘                      └─────────────────────┘       │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Vsock Request/Response Protocol

Vsock (Virtual Socket) is the **only** communication channel between the parent EC2 instance and the Nitro Enclave. Each request opens a new connection, sends JSON, waits for a newline-terminated JSON response, then closes.

```typescript
// src/types/vsock.types.ts

interface VsockRequest {
  type: RequestType;      // Handler identifier (e.g., 'dkgInit', 'partialSign')
  data?: any;             // Request-specific payload
}

interface VsockResponse {
  success: boolean;       // Operation success status
  data?: any;             // Response payload
  error?: string;         // Error message if failed
  timestamp: string;      // ISO timestamp
}
```

### Parent → Enclave Communication Code

```javascript
// parent-client.js - sendToEnclave()

async function sendToEnclave(request) {
  return new Promise((resolve, reject) => {
    const cid = getEnclaveCID();  // Dynamic CID discovery
    const client = new VsockSocket();
    let responseData = '';

    const timeout = setTimeout(() => {
      client.end();
      reject(new Error('Request timeout'));
    }, 30000);  // 30 second timeout

    client.on('data', (buf) => {
      responseData += buf.toString();
      if (responseData.includes('\n')) {
        const response = JSON.parse(responseData.trim());
        clearTimeout(timeout);
        client.end();
        resolve(response);
      }
    });

    client.connect(cid, VSOCK_PORT, () => {
      client.writeTextSync(JSON.stringify(request));
    });
  });
}
```

### Enclave Vsock Server Code

```typescript
// src/vsock-server.ts

class EnclaveVsockServer {
  constructor(port: number = 5000) {
    this.server = new VsockServer();

    this.server.on('connection', (socket: VsockSocket) => {
      let dataBuffer = '';

      socket.on('data', async (data: Buffer) => {
        dataBuffer += data.toString();

        // Prevent buffer overflow
        if (dataBuffer.length > 10240) {
          dataBuffer = '';
          return;
        }

        try {
          const request = JSON.parse(dataBuffer);
          const response = await this.processRequest(request);
          socket.writeTextSync(JSON.stringify(response) + '\n');

          setTimeout(() => socket.close(), 10);
        } catch (e) {
          // Not valid JSON yet, wait for more data
        }
      });
    });

    this.server.listen(port);
  }
}
```

## 5. Security Architecture

### 3-Party Threshold Setup

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                        3-PARTY SHARE DISTRIBUTION                            │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   SHARE 1 (Client)          SHARE 2 (Active)         SHARE 3 (Backup)       │
│   ═══════════════           ════════════════          ════════════════       │
│                                                                             │
│   ┌─────────────┐          ┌─────────────────┐       ┌─────────────────┐    │
│   │   Browser   │          │  Nitro Enclave  │       │  Nitro Enclave  │    │
│   │  (Local)    │          │  (Encrypted in  │       │  (Encrypted in  │    │
│   │             │          │   S3 + KMS)     │       │   S3 + KMS)     │    │
│   └─────────────┘          └─────────────────┘       └─────────────────┘    │
│                                                                             │
│   • Stored in browser       • Stored encrypted in     • Stored encrypted    │
│     localStorage             AWS S3                    in AWS S3            │
│   • Never leaves device     • Decrypted only in       • For recovery only   │
│   • Required for signing     enclave                  • 2-of-3 threshold    │
│                             • Required for signing                          │
│                                                                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   SIGNING REQUIRES: Share 1 (Client) + Share 2 (Enclave)                    │
│   RECOVERY USES:    Share 1 (Client) + Share 3 (Enclave) OR                 │
│                     Share 2 (Enclave) + Share 3 (Enclave)                   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Encryption Layers

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                          ENCRYPTION LAYERS                                   │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   Layer 1: ECDH Key Exchange (Browser ↔ Enclave)                            │
│   ═════════════════════════════════════════════                             │
│   • Curve: prime256v1 (P-256)                                               │
│   • Purpose: Encrypt sensitive share contributions during DKG               │
│   • Protection: Man-in-the-middle during DKG handshake                      │
│                                                                             │
│   Layer 2: AES-256-GCM (Share Storage)                                      │
│   ════════════════════════════════════                                      │
│   • Algorithm: AES-256-GCM (authenticated encryption)                       │
│   • Key Source: AWS KMS GenerateDataKey                                     │
│   • Purpose: Encrypt shares before S3 storage                               │
│   • Protection: Shares at rest in S3                                        │
│                                                                             │
│   Layer 3: AWS KMS (Key Management)                                         │
│   ════════════════════════════════                                          │
│   • Purpose: Generate and manage data encryption keys                       │
│   • Key ID: 33b03d30-4e5d-4460-a971-91c975b7b82f                            │
│   • Protection: Data keys never stored in plaintext                         │
│                                                                             │
│   Layer 4: Nitro Enclave (Hardware Isolation)                               │
│   ═══════════════════════════════════════════                               │
│   • Purpose: Isolated execution environment                                 │
│   • Protection: Memory isolation, no persistent storage, attestation        │
│   • Communication: vsock only (no network access)                           │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Data Flow Security

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                     WHAT EACH PARTY CAN ACCESS                               │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   BROWSER (Client)                                                          │
│   ├── ✅ Share 1 (plaintext)                                                │
│   ├── ✅ Public key                                                         │
│   ├── ✅ Ethereum address                                                   │
│   ├── ✅ Session ID                                                         │
│   └── ❌ Share 2, Share 3                                                   │
│                                                                             │
│   PARENT INSTANCE (Relay)                                                   │
│   ├── ✅ Encrypted shares (ciphertext only)                                 │
│   ├── ✅ Encrypted KMS data keys                                            │
│   ├── ✅ Public key, Ethereum address                                       │
│   ├── ✅ Session metadata                                                   │
│   └── ❌ Plaintext shares, plaintext data keys                              │
│                                                                             │
│   NITRO ENCLAVE                                                             │
│   ├── ✅ All shares (temporarily, in memory)                                │
│   ├── ✅ Plaintext data keys (temporarily)                                  │
│   ├── ✅ All cryptographic operations                                       │
│   └── ❌ Network access, persistent storage                                 │
│                                                                             │
│   AWS S3                                                                    │
│   ├── ✅ Encrypted Share 2                                                  │
│   ├── ✅ Encrypted Share 3                                                  │
│   ├── ✅ Encrypted KMS data key                                             │
│   └── ❌ Any plaintext cryptographic material                               │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```
