# Cryptanalysis of the Keystone Identity System

This document outlines the cryptographic specifications, mathematical bounds, and security assertions of the Keystone challenge-response identity system (V1).

---

## 1. Mathematical Bounds of Target Binding

Target Binding maps a target address (`ib` + `gib`) to a deterministic selection of challenge IDs from a pool.

### 1.1 Combinatorial Probability of Forgery
When Alice signs a claim, she reveals a subset of secrets. If a transmission fails, or if Alice interacts with a compromised node, an attacker may intercept these solutions.

Let:
*   $M$ = Total number of active challenges in the pool.
*   $C$ = Number of target binding challenges required per signature.
*   $K$ = Number of unique solutions the attacker has intercepted.

The probability $P$ that a new, randomly selected target address maps entirely to a subset of the $K$ known secrets is given by:

$$P = \frac{\binom{K}{C}}{\binom{M}{C}}$$

The attacker can "grind" (tweak the salt, timestamp, or minor metadata of a forged claim) until they find a target address that has a target-binding selection mapping entirely to the $K$ solutions they possess. 

The average number of grinding iterations required is:
$$N_{\text{grind}} = \frac{1}{P} = \frac{\binom{M}{C}}{\binom{K}{C}}$$

### 1.2 Quantitative Security Presets (at $C = 10$, $K = 20$)

Assuming $C = 10$ target binding characters are required, and the attacker has intercepted $K = 20$ solutions from a single aborted evolution:

| Pool Size ($M$) | Combinatorial Probability ($P$) | Avg. Grinding Operations ($1/P$) | Classical Security Rating |
| :--- | :--- | :--- | :--- |
| **50** (Medium/Low) | $1.8 \times 10^{-5}$ | $\approx 5.5 \times 10^4$ | **Insecure** (grinded in < 1 ms on a CPU) |
| **100** (Medium) | $1.07 \times 10^{-8}$ | $\approx 9.3 \times 10^7$ | **Low** (grinded in < 1 second on a CPU) |
| **500** (High) | $7.0 \times 10^{-16}$ | $\approx 1.4 \times 10^{15}$ | **Medium** (requires substantial CPU/GPU effort) |
| **1000** (Ultra) | $7.0 \times 10^{-19}$ | $\approx 1.4 \times 10^{18}$ | **High** (computationally infeasible for standard attackers) |

### 1.3 Key Takeaway for Pool Configurations
*   **Small Pools ($M \le 100$)** are highly vulnerable to grinding attacks *if* the attacker intercepts even a single aborted/failed transition where the client modifies the target payload (e.g., updating the timestamp for a retry).
*   **Mitigation**: For small pools to remain secure, **retries must be byte-for-byte identical** (no timestamp/nonce updates), ensuring no new secrets are leaked. Otherwise, pool sizes of **500+** are required to support arbitrary dynamic retries.

---

## 2. Hash Function Strength: SHA-256 vs. SHA-512

While the combinatorial distribution $P$ is identical for both hash functions, the underlying cryptographic strength differs.

| Metric | SHA-256 | SHA-512 |
| :--- | :--- | :--- |
| **Classical Pre-image Strength** | $2^{256}$ operations | $2^{512}$ operations |
| **Quantum Pre-image Strength (Grover)** | $2^{128}$ operations | $2^{256}$ operations (complete quantum immunity) |
| **ASIC Grinding Ecosystem** | Massive (repurposable Bitcoin hardware) | None (commodity CPUs/GPUs only) |

### 2.1 ASIC Grinding Mitigation
Because Bitcoin miners utilize SHA-256, specialized, highly efficient ASIC mining rigs exist globally. An attacker could theoretically lease SHA-256 hash power to perform grinding attacks on Keystone targets. 

Transitioning to **SHA-512** removes this threat vector entirely, as there is no equivalent commodity hardware infrastructure, raising the real-world dollar cost of any grinding attack.

## 3. Challenge ID Length & Salting Analysis

In Keystone V1, the `challengeId` is generated as the truncated hash of the pool salt, timestamp, and challenge index. Crucially, the `challengeId` acts directly as the **cryptographic salt (`indexSalt`)** during the generation and verification of both the solution values and challenge hashes:

```typescript
// Derivation in KeystoneStrategy_HashRevealV1:
const indexSalt = challengeId;
current = Hash(indexSalt + current + indexSalt) ^ Rounds;
```

This dual-role introduces two design constraints: collision resistance and multi-target pre-computation resistance.

### 3.1 Collision Probability (Birthday Paradox)
We analyze the probability of a collision (two challenges having the same ID) within a single active keystone frame's pool of size $M$ over a key space of $d = 2^{B \cdot 4}$ (where $B$ is the number of hex characters, each representing 4 bits of entropy):

$$P_{\text{collision}} \approx 1 - e^{-\frac{M^2}{2d}}$$

Let's evaluate collision probabilities across three key lengths at a large pool size of $M = 2000$:

*   **10 characters (40 bits)**: $d = 2^{40} \approx 1.1 \times 10^{12}$
    $$P_{\text{collision}} \approx 1 - e^{-\frac{4 \cdot 10^6}{2.2 \cdot 10^{12}}} \approx 1.8 \times 10^{-6}$$
    *(Not acceptable: A collision is likely to occur once in every 550,000 frames.)*
*   **12 characters (48 bits)**: $d = 2^{48} \approx 2.8 \times 10^{14}$
    $$P_{\text{collision}} \approx 1 - e^{-\frac{4 \cdot 10^6}{5.6 \cdot 10^{14}}} \approx 7.1 \times 10^{-9}$$
    *(Highly secure: 1 in 140 million chance of collision.)*
*   **16 characters (64 bits)**: $d = 2^{64} \approx 1.8 \times 10^{19}$
    $$P_{\text{collision}} \approx 1 - e^{-\frac{4 \cdot 10^6}{3.6 \cdot 10^{19}}} \approx 1.1 \times 10^{-13}$$
    *(Astronomically secure.)*

### 3.2 Multi-Target Pre-computation (Rainbow Table) Defense
Because the `challengeId` is used as a salt (`indexSalt`) for the solution derivation, it prevents an attacker from building a generic, reusable pre-computation database (like rainbow tables) to crack solutions across different pools or different slots in the same pool.

If the salt is too short, an attacker can pre-compute a table of solutions for a large number of common salts:
*   **40-bit salt (10 chars)**: The search space ($2^{40}$) is small enough that a well-funded adversary could pre-calculate a complete table mapping `poolSecret` and `challengeId` combinations, speeding up cracking times.
*   **48-bit salt (12 chars)**: The search space ($2^{48}$) is significantly harder to pre-calculate, but still within theoretical reach of nation-state or high-end distributed cloud infrastructures.
*   **64-bit salt (16 chars)**: The search space ($2^{64}$) is globally recognized as computationally impossible to pre-compute.

### 3.3 Influence of Truncation on Solution Entropy
Importantly, **truncating the `challengeId` does NOT reduce the entropy of the secret solution itself.**
The solution is a full-length hash (e.g. 256-bit or 512-bit) derived from the secret master key. The `challengeId` is only the salt. Therefore, even if the `challengeId` is truncated to 12 characters, a pre-image attack aiming to guess the secret solution still faces a search space of $2^{256}$ or $2^{512}$.

### 3.4 Quantum Pre-image Attacks & Grover's Algorithm
Quantum computers will theoretically accelerate pre-image search attacks using Grover's search algorithm, which provides a quadratic speedup.
*   A search space of $2^b$ is reduced to $2^{b/2}$ quantum operations.
*   For SHA-256 solutions, Grover's algorithm reduces the security margin from 256 bits to **128 bits**. 128 bits is still globally considered secure against any foreseeable quantum threat.
*   For SHA-512 solutions, Grover's algorithm reduces the security margin from 512 bits to **256 bits** (the gold standard for quantum immunity).
*   Grover's algorithm does not make pre-computation (rainbow tables) easier; it only speeds up direct brute-force guessing of the in-flight secret solution.

### 3.5 Storage Costs vs. Security Benefits
Comparing storage space requirements for a pool of size $M = 2000$:
*   **12-char Keys**: $2000 \times 12 \text{ bytes} = 24 \text{ KB}$
*   **16-char Keys**: $2000 \times 16 \text{ bytes} = 32 \text{ KB}$

**Conclusion**: 16 characters (64 bits) remains the recommended default for production deployments because it provides absolute collision immunity ($10^{-13}$) and complete protection against multi-target pre-computation attacks, for an insignificantly small storage premium (+8 KB per 2,000 challenges). For low-resource networks, 12 characters (48 bits) is a viable alternative.

---

## 4. Keystone Security & Performance Profiles (Presets)

To balance performance (CPU rounds, database footprint) with security (grinding protection, pre-image resistance), we define five standard profiles:

### 4.1 "Test" Profile
*   **Purpose**: Unit testing and rapid local prototyping.
*   **Performance**: Near-instantaneous execution.
*   **Configuration**:
    *   Pool Size ($M$): `12`
    *   Algorithm: `SHA-256`
    *   Rounds: `1`
    *   Replenishment: `top-up`
    *   Selection: `1` Sequential (FIFO) + `1` Random
    *   Target Binding Count: `3`
*   **Security Grade**: **Weak/Non-existent**. Easily broken by grinding. Strictly for offline/developer use.

### 4.2 "Session" (Very Short-Lived) Profile
*   **Purpose**: Ephemeral session-scoped keystones (e.g., sync sagas).
*   **Performance**: Fast generation/handshake, keeping UI responsiveness high.
*   **Configuration**:
    *   Pool Size ($M$): `50`
    *   Algorithm: `SHA-256`
    *   Rounds: `1`
    *   Replenishment: `top-up`
    *   Selection: `2` Sequential (FIFO) + `2` Random
    *   Target Binding Count: `6` (12 characters recommended for `challengeId` salt)
*   **Security Rationale**: A sync session saga typically evolves only 3 to 5 times (Init $\to$ Ack $\to$ Delta $\to$ Commit/Conflict) and is bound to a single transaction lifespan. Once completed, the session is discarded, preventing attackers from accumulating enough secrets to forge transitions before the transaction context expires.

### 4.3 "Low" Profile
*   **Purpose**: Low-value transactions or high-frequency web hooks.
*   **Configuration**:
    *   Pool Size ($M$): `100`
    *   Algorithm: `SHA-256`
    *   Rounds: `1`
    *   Replenishment: `top-up`
    *   Selection: `3` Sequential (FIFO) + `3` Random
    *   Target Binding Count: `8`
*   **Security Grade**: **Moderate**. Requires strict client/server enforcement of byte-for-byte identical retries to prevent pool secret leakage under network failures.

### 4.4 "Medium" Profile (Standard Production Default)
*   **Purpose**: Standard user identity, sync authorizations, and general credentials.
*   **Configuration**:
    *   Pool Size ($M$): `500`
    *   Algorithm: `SHA-256`
    *   Rounds: `2`
    *   Replenishment: `top-up`
    *   Selection: `5` Sequential (FIFO) + `5` Random
    *   Target Binding Count: `10`
*   **Security Grade**: **Strong**. Grinding search space is $\approx 1.4 \times 10^{15}$ hashes, rendering attacks economically impractical for standard targets.

### 4.5 "High" Profile (Root/Admin Default)
*   **Purpose**: Root identity management (`manage`), recovery, and revocation (`revoke`).
*   **Configuration**:
    *   Pool Size ($M$): `2000`
    *   Algorithm: `SHA-512`
    *   Rounds: `4`
    *   Replenishment: `replace-all` (or `delete-all` for revocation)
    *   Selection: `10` Sequential (FIFO) + `10` Random
    *   Target Binding Count: `16`
*   **Security Grade**: **Ultra/Quantum-Resistant**. Fully immune to multi-target pre-computation, ASIC mining farms, and quantum pre-image attacks.

### 4.6 Mathematical Rationale for Lower Hashing Rounds
Because the Keystone system derives `indexSalt` (the `challengeId`) dynamically for each challenge, pre-computation lookup tables (rainbow tables) are completely blocked. An attacker must perform a first-preimage attack to crack any individual challenge solution, which requires brute-forcing a full-length hash (256-bit or 512-bit). Since $2^{256}$ is mathematically secure, raising `rounds` does not increase this pre-image margin.

Furthermore, **grinding target addresses does not require evaluating the hash rounds**. When an attacker grinds the claim metadata to find a target address that maps to their known solution indices, they only hash the target address to find the indices (which is a fast 1-round operation). They do not need to evaluate the challenge values themselves during grinding.

Therefore, increasing `rounds` to high numbers (e.g. 10 or 15) only adds significant CPU overhead during pool initialization/replenishment (e.g. computing 20,000 hashes on a weak device), without providing any corresponding security benefits against target grinding. Reducing `rounds` to **1 (Session/Low)**, **2 (Medium)**, or **4 (High)** maintains sub-millisecond execution times while preserving all mathematical security guarantees.


