# Technical Explanation

## Architecture Overview

PIVY uses a multi-layered cryptographic system for privacy-preserving payments which can be visually explained in the flow diagram below.

<img src="/files/MNYpbtcu5MF89OgGE4Jd" alt="" class="gitbook-drawing">

***

## Core Components

### 1. Meta Key Generation

Meta keys are deterministically derived from the user's wallet signature and PIN:

```typescript
// Derive meta spend key
const spendSeed = sha512(
  Uint8Array.from([
    ...walletSignature,           // Unique per wallet
    ...pinBytes,                  // User's PIN
    ...new TextEncoder().encode("PIVY Spend Authority | Deterministic Derivation")
  ])
).slice(0, 32);

const metaSpendKeypair = Secp256k1Keypair.fromSecretKey(spendSeed);
```

#### Meta Keys Overview

PIVY uses two types of meta keys derived from your wallet + PIN.

{% tabs %}
{% tab title="Meta Viewing Keys" %}

* Meta View Private Key (metaViewPriv): Decrypts payment details.
* Meta View Public Key (metaViewPub): Used by senders to encrypt data.
  {% endtab %}

{% tab title="Meta Spending Keys" %}

* Meta Spend Private Key (metaSpendPriv): Grants spending access and never exposed.
* Meta Spend Public Key (metaSpendPub): Used by senders to create stealth addresses.
  {% endtab %}
  {% endtabs %}

#### Key Security and Flow

Private keys (`metaSpendPriv`, `metaViewPriv`) are the most critical piece of security and are **NEVER EXPOSED**:\
❌ Never transmitted, logged, or shared with external services.\
✅ Only used **locally** for cryptographic operations.

Public keys (`metaSpendPub`, `metaViewPub`) are shared and used by senders for payment routing and encryption. They **cannot** be used to spend your funds.

**Usage Flow and Critical Security**

| Action                 | Keys Used    | Security Note                    |
| ---------------------- | ------------ | -------------------------------- |
| **Sending**            | Public Keys  | Used for address generation.     |
| **Receiving/Spending** | Private Keys | Used to detect and unlock funds. |

{% hint style="success" %}
The `metaSpendPriv` is your master key. It's **never published**, **only** used for key derivation, and is securely **protected by PIN-based encryption** in your local storage.
{% endhint %}

**Key Properties**

* **Deterministic:** Your meta keys are always the same (Wallet + PIN).
* **Two-Factor:** Control requires both your wallet and your PIN.
* **Domain Separated:** Keys are unique for different contexts.

### 2. Ephemeral Key Encryption

Payment details are encrypted using one-time ephemeral keys:

```typescript
// ECDH key agreement
const shared = secp.getSharedSecret(ephPriv, metaViewPub, true);
const key = hkdf(sha256, shared.slice(1), salt, "ephemeral-key-encryption", 32);

// Encrypt with ChaCha20-Poly1305
const encrypted = chacha20poly1305(key, nonce).encrypt(plaintext);
```

**Security Properties:**

* **Forward Secrecy**: Each payment uses unique ephemeral key.
* **Authenticated Encryption**: ChaCha20-Poly1305 provides integrity.
* **Key Derivation**: HKDF ensures proper key material.

### 3. Stealth Address System

Each payment uses a unique, unlinkable address derived from meta keys:

```typescript
// ECDH shared secret between ephemeral key and meta view key
const shared = secp.getSharedSecret(ephPriv, metaViewPub, true);
const tweak = sha256(shared.slice(1));

// Point arithmetic: StealthPub = MetaSpendPub + tweak * G
const stealthPoint = metaSpendPoint.add(secp.Point.BASE.multiply(tweakScalar));
```

**Mathematical Foundation:**

* **Stealth Public Key**: `S = M + t * G` (where M = meta spend pub, t = tweak).
* **Stealth Private Key**: `s = m + t` (where m = meta spend priv).
* **Unlinkability**: Each payment uses different ephemeral key → different stealth address.

***

## Payment Flow

### 1. Sending Payment

1. **Generate Ephemeral Keypair**

   ```typescript
   const ephemeral = pivy.generateEphemeralKey();
   ```
2. **Derive Stealth Address**

   ```typescript
   const stealthAddress = await pivy.deriveStealthPub(
     receiverMetaSpendPub,
     receiverMetaViewPub,
     ephemeral.privateKey
   );
   ```
3. **Encrypt Payment Data**

   ```typescript
   const encryptedMemo = await pivy.encryptEphemeralPrivKey(
     ephemeral.privateKey,
     receiverMetaViewPub
   );
   ```

### 2. Receiving Payment

1. **Detect Payment**: System monitors blockchain for stealth address activity.

### **3. Withdrawing Payment**

1. **Derive Stealth Keypair**:

   ```typescript
   const stealthKP = await pivy.deriveStealthKeypair(
     metaSpendPriv,
     metaViewPriv,
     payment.ephemeralPubkey
   );
   ```
2. **Spend Funds**: Use derived keypair to sign withdraw transactions.

***

## Security Model

#### Cryptographic Primitives

| Component          | Algorithm                   | Purpose                  |
| ------------------ | --------------------------- | ------------------------ |
| **Key Derivation** | SHA-512 + domain separation | Meta key generation      |
| **Key Agreement**  | ECDH (secp256k1)            | Shared secret generation |
| **Encryption**     | ChaCha20-Poly1305           | Ephemeral key encryption |
| **Storage**        | AES-256-GCM + PBKDF2        | Local key storage        |
| **Hashing**        | SHA-256                     | Tweak derivation         |

#### Attack Resistance

| Attack Vector               | Protection Mechanism                                                                                                                      |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| **PIN Brute Force**         | 6-digit PIN with rate limiting. The PIN alone **does not grant access** to user's fund, it needs to be combines with the user's wallet.   |
| **Wallet Compromise**       | PIN still required for meta keys. The wallet alone **does not grant access** to user's fund, it needs to be combines with the user's PIN. |
| **Storage Theft**           | AES-256-GCM encryption.                                                                                                                   |
| **Network Analysis**        | Unlinkable stealth addresses.                                                                                                             |
| **Transaction Correlation** | Ephemeral keys prevent linking.                                                                                                           |

#### Security Guarantees

1. **Unlinkability**: Stealth addresses cannot be linked to user identity.
2. **Forward Secrecy**: Compromising one payment doesn't affect others.
3. **Deterministic Recovery**: Meta keys can be regenerated from wallet + PIN.
4. **No Single Point of Failure**: Both wallet and PIN required for access.

***

## Multi-Chain Implementation

#### Sui Network

* **Curve**: secp256k1
* **Address Format**: 0x-prefixed hex
* **Transaction**: Move smart contracts

#### Solana Network

* **Curve**: Ed25519
* **Address Format**: Base58
* **Transaction**: Anchor program calls

Both implementations follow the same cryptographic principles, but use chain-specific primitives, account generation formula, and transaction formats.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.pivy.me/basics/how-pivy-works/technical-explanation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
