/*
* ═══════════════════════════════════════════════════════════════
* AṆU ASTRA CHROMATIC OPU — PHASE 1 FIRMWARE
* "Quantum Source Validation Engine"
*
* Hardware: ESP32 DevKit V1 + BPW34 + LM358
* Purpose: Harvest shot-noise entropy from a reverse-biased
* photodiode and validate its quantum origin via
* statistical tests.
*
* Author: CryptoPIX (OPC) Private Limited
* License: Proprietary — Aṇu Astra Platform
* ═══════════════════════════════════════════════════════════════
*/
#include <Arduino.h>
// ─── Hardware Pins ───────────────────────────────────────────
#define PIN_PHOTODIODE 34 // ADC1_CH6 — Amplified shot noise input
#define PIN_STATUS_LED 2 // Onboard LED — blinks on entropy harvest
// ─── Sampling Configuration ─────────────────────────────────
#define SAMPLE_RATE_US 100 // 100µs between samples = 10 kHz
#define CALIBRATION_SAMPLES 10000
#define ENTROPY_BUFFER_SIZE 256 // Bytes per harvest batch
// ─── Chromatic Ontology State ───────────────────────────────
struct ChromaticVector {
float c0; // Probability axis (maps to Bloch Z)
float c1; // Coherence real (maps to Bloch X)
float c2; // Coherence imag (maps to Bloch Y)
};
// ─── Global State ───────────────────────────────────────────
static float baseline_mean = 0.0;
static float baseline_stddev = 0.0;
static bool calibrated = false;
static uint32_t total_bits_harvested = 0;
static uint32_t total_ones = 0;
static uint32_t total_zeros = 0;
static ChromaticVector current_state = {1.0, 0.0, 0.0};
// ─── Von Neumann Debiasing ──────────────────────────────────
// Takes pairs of bits: (0,1)→0, (1,0)→1, (0,0) and (1,1) discarded.
// This guarantees 50/50 output even from a biased source.
// This is the ONLY scientifically valid method for raw entropy.
int von_neumann_extract(int bit1, int bit2) {
if (bit1 == 0 && bit2 == 1) return 0;
if (bit1 == 1 && bit2 == 0) return 1;
return -1; // Discard
}
// ─── ADC Noise → Quantum Bit Extraction ─────────────────────
// Reads the amplified shot noise, compares to baseline,
// and converts the analog fluctuation into a raw bit.
int sample_raw_bit() {
int raw = analogRead(PIN_PHOTODIODE);
// Bit = 1 if above mean, 0 if below
return (raw > (int)baseline_mean) ? 1 : 0;
}
// ─── Harvest One Byte of Quantum Entropy ────────────────────
// Uses Von Neumann debiasing to produce 8 unbiased bits.
uint8_t harvest_quantum_byte() {
uint8_t result = 0;
int bits_collected = 0;
while (bits_collected < 8) {
delayMicroseconds(SAMPLE_RATE_US);
int b1 = sample_raw_bit();
delayMicroseconds(SAMPLE_RATE_US);
int b2 = sample_raw_bit();
int clean_bit = von_neumann_extract(b1, b2);
if (clean_bit >= 0) {
result |= (clean_bit << bits_collected);
bits_collected++;
// Track statistics
if (clean_bit == 1) total_ones++;
else total_zeros++;
total_bits_harvested++;
}
}
return result;
}
// ─── Chromatic State Update ─────────────────────────────────
// Maps the harvested entropy into the CQO Chromatic Vector.
// λ = 550 - (C0 × 170) + (C2 × 200)
void update_chromatic_state(uint8_t entropy_byte) {
// Normalize byte to [-1, 1] range
float normalized = ((float)entropy_byte / 255.0) * 2.0 - 1.0;
// Evolve the chromatic state (rotation in C0-C1 plane)
float delta = normalized * 0.1; // Small rotation per sample
float cos_d = cos(delta);
float sin_d = sin(delta);
float new_c0 = cos_d * current_state.c0 + sin_d * current_state.c1;
float new_c1 = -sin_d * current_state.c0 + cos_d * current_state.c1;
current_state.c0 = new_c0;
current_state.c1 = new_c1;
// Normalize to stay on the Bloch sphere
float mag = sqrt(current_state.c0 * current_state.c0 +
current_state.c1 * current_state.c1 +
current_state.c2 * current_state.c2);
if (mag > 0.0001) {
current_state.c0 /= mag;
current_state.c1 /= mag;
current_state.c2 /= mag;
}
}
// ─── Calculate Aṇu Wavelength ───────────────────────────────
float get_wavelength() {
return 550.0 - (current_state.c0 * 170.0) + (current_state.c2 * 200.0);
}
// ─── Calibration Phase ──────────────────────────────────────
// Reads N samples in the dark to establish the noise baseline.
void calibrate() {
Serial.println("[CALIBRATION] Reading baseline noise...");
Serial.println("[CALIBRATION] Ensure photodiode is in COMPLETE DARKNESS.");
float sum = 0;
float sum_sq = 0;
for (int i = 0; i < CALIBRATION_SAMPLES; i++) {
int raw = analogRead(PIN_PHOTODIODE);
sum += raw;
sum_sq += (float)raw * (float)raw;
delayMicroseconds(SAMPLE_RATE_US);
}
baseline_mean = sum / CALIBRATION_SAMPLES;
float variance = (sum_sq / CALIBRATION_SAMPLES) - (baseline_mean * baseline_mean);
baseline_stddev = sqrt(variance);
calibrated = true;
// ─── Noise Profile Analysis ─────────────────────────────
// Analyze for 50Hz/60Hz interference (Common in antenna noise)
int periodic_hits = 0;
for (int i = 0; i < 1000; i++) {
int s = analogRead(PIN_PHOTODIODE);
if (abs(s - baseline_mean) > (1.5 * baseline_stddev)) periodic_hits++;
delayMicroseconds(100);
}
Serial.println("═══════════════════════════════════════");
Serial.println(" AṆU ASTRA — CALIBRATION COMPLETE");
Serial.println("═══════════════════════════════════════");
Serial.printf(" Baseline Mean: %.2f\n", baseline_mean);
Serial.printf(" Baseline StdDev: %.2f\n", baseline_stddev);
// VALIDATION LOGIC
if (baseline_stddev < 1.0) {
Serial.println(" ❌ STATUS: [FAIL]");
Serial.println(" REASON: No signal detected. Pin is floating.");
Serial.println(" ACTION: Connect BPW34 + LM358 Circuit.");
} else if (baseline_stddev > 100.0) {
Serial.println(" ❌ STATUS: [FAIL]");
Serial.println(" REASON: Extreme Interference Detected.");
Serial.println(" ACTION: Check shielding. Power lines nearby?");
} else {
Serial.println(" ✅ STATUS: [READY]");
Serial.println(" SOURCE: Noise floor verified.");
}
Serial.println("═══════════════════════════════════════");
Serial.println();
}
// ─── Serial Command Protocol ────────────────────────────────
// H <n> — Harvest n bytes of entropy (hex output)
// S — Show statistics (bit balance, total harvested)
// C — Show current Chromatic State
// T — Run self-test (harvest 1000 bits, check balance)
// R — Recalibrate baseline
void process_command(String cmd) {
cmd.trim();
if (cmd.startsWith("H")) {
// Harvest entropy
int count = ENTROPY_BUFFER_SIZE;
if (cmd.length() > 2) {
count = cmd.substring(2).toInt();
if (count <= 0 || count > 4096) count = ENTROPY_BUFFER_SIZE;
}
Serial.printf("[HARVEST] Collecting %d bytes of quantum entropy...\n", count);
digitalWrite(PIN_STATUS_LED, HIGH);
for (int i = 0; i < count; i++) {
uint8_t qbyte = harvest_quantum_byte();
update_chromatic_state(qbyte);
// Print as hex
if (qbyte < 0x10) Serial.print("0");
Serial.print(qbyte, HEX);
}
Serial.println();
digitalWrite(PIN_STATUS_LED, LOW);
Serial.printf("[HARVEST] Complete. %d bytes delivered.\n", count);
} else if (cmd == "S") {
// Statistics
Serial.println("═══════════════════════════════════════");
Serial.println(" AṆU ASTRA — QUANTUM SOURCE STATS");
Serial.println("═══════════════════════════════════════");
Serial.printf(" Total Bits Harvested: %u\n", total_bits_harvested);
Serial.printf(" Ones: %u (%.2f%%)\n", total_ones,
total_bits_harvested > 0 ? (total_ones * 100.0 / total_bits_harvested) : 0);
Serial.printf(" Zeros: %u (%.2f%%)\n", total_zeros,
total_bits_harvested > 0 ? (total_zeros * 100.0 / total_bits_harvested) : 0);
Serial.printf(" Bias: %.4f%% (ideal = 0%%)\n",
total_bits_harvested > 0 ?
fabs((total_ones * 100.0 / total_bits_harvested) - 50.0) : 0);
Serial.println("═══════════════════════════════════════");
} else if (cmd == "C") {
// Chromatic State
Serial.println("═══════════════════════════════════════");
Serial.println(" AṆU ASTRA — CHROMATIC STATE");
Serial.println("═══════════════════════════════════════");
Serial.printf(" C0 (Probability): %.6f\n", current_state.c0);
Serial.printf(" C1 (Coherence Re): %.6f\n", current_state.c1);
Serial.printf(" C2 (Coherence Im): %.6f\n", current_state.c2);
Serial.printf(" Wavelength (nm): %.2f\n", get_wavelength());
Serial.printf(" Magnitude: %.6f\n",
sqrt(current_state.c0 * current_state.c0 +
current_state.c1 * current_state.c1 +
current_state.c2 * current_state.c2));
Serial.println("═══════════════════════════════════════");
} else if (cmd == "T") {
// Self-Test: Harvest and compare Raw vs Quantum data
Serial.println("[TEST] Analyzing 2000 raw samples (1000 quantum bits)...");
uint32_t raw_ones = 0, raw_zeros = 0;
uint32_t clean_ones = 0, clean_zeros = 0;
int clean_total = 0;
int last_raw = -1, last_clean = -1;
int raw_corr = 0, clean_corr = 0;
while (clean_total < 1000) {
delayMicroseconds(SAMPLE_RATE_US);
int b1 = sample_raw_bit();
if (b1 == 1) raw_ones++; else raw_zeros++;
if (last_raw != -1 && b1 == last_raw) raw_corr++;
last_raw = b1;
delayMicroseconds(SAMPLE_RATE_US);
int b2 = sample_raw_bit();
if (b2 == 1) raw_ones++; else raw_zeros++;
if (last_raw != -1 && b2 == last_raw) raw_corr++;
last_raw = b2;
int clean = von_neumann_extract(b1, b2);
if (clean >= 0) {
if (clean == 1) clean_ones++;
else clean_zeros++;
if (last_clean != -1 && clean == last_clean) clean_corr++;
last_clean = clean;
clean_total++;
}
}
float raw_bias = fabs(((raw_ones * 100.0) / (raw_ones + raw_zeros)) - 50.0);
float clean_bias = fabs(((clean_ones * 100.0) / clean_total) - 50.0);
float raw_corr_pct = (raw_corr * 100.0) / (raw_ones + raw_zeros - 1);
float clean_corr_pct = (clean_corr * 100.0) / (clean_total - 1);
Serial.println("══════════════════════════════════════════════════");
Serial.println(" AṆU ASTRA — DATA INTEGRITY REPORT");
Serial.println("══════════════════════════════════════════════════");
Serial.println(" METRIC RAW DATA QUANTUM DATA");
Serial.println(" ────── ──────── ────────────");
Serial.printf(" Sample Count: %-15d %-15d\n", raw_ones + raw_zeros, clean_total);
Serial.printf(" Ones / Zeros: %u/%u %u/%u\n", raw_ones, raw_zeros, clean_ones, clean_zeros);
Serial.printf(" Bias: %-14.2f%% %-14.2f%%\n", raw_bias, clean_bias);
Serial.printf(" Correlation: %-14.2f%% %-14.2f%%\n", raw_corr_pct, clean_corr_pct);
Serial.println(" ────── ──────── ────────────");
bool bias_ok = clean_bias < 2.0;
bool corr_ok = fabs(clean_corr_pct - 50.0) < 5.0;
if (bias_ok && corr_ok) {
Serial.println(" ✅ PASS: Source is Quantum-Grade.");
} else {
Serial.println(" ❌ FAIL: Source is NON-RANDOM.");
if (!bias_ok) Serial.println(" -> High Bias in Corrected Data.");
if (!corr_ok) Serial.println(" -> Periodic Pattern Detected.");
}
Serial.println("══════════════════════════════════════════════════");
} else if (cmd == "R") {
calibrated = false;
calibrate();
} else {
Serial.println("[HELP] Commands:");
Serial.println(" H <n> — Harvest n bytes of quantum entropy");
Serial.println(" S — Show statistics");
Serial.println(" C — Show chromatic state");
Serial.println(" T — Run self-test (1000 bits)");
Serial.println(" R — Recalibrate baseline");
}
}
// ─── Setup ──────────────────────────────────────────────────
void setup() {
Serial.begin(115200);
while (!Serial) { delay(10); }
pinMode(PIN_PHOTODIODE, INPUT);
pinMode(PIN_STATUS_LED, OUTPUT);
// Set ADC to 12-bit resolution (0-4095)
analogReadResolution(12);
// Use 11dB attenuation for full 0-3.3V range
analogSetAttenuation(ADC_11db);
Serial.println();
Serial.println("═══════════════════════════════════════════════════");
Serial.println(" AṆU ASTRA CHROMATIC OPU v1.0");
Serial.println(" Quantum Source Validation Engine");
Serial.println(" CryptoPIX (OPC) Private Limited");
Serial.println("═══════════════════════════════════════════════════");
Serial.println();
// Phase 1: Calibrate the noise baseline
calibrate();
Serial.println("Ready. Type 'H 32' to harvest 32 bytes, 'T' to self-test.");
Serial.println();
}
// ─── Main Loop ──────────────────────────────────────────────
void loop() {
if (Serial.available()) {
String cmd = Serial.readStringUntil('\n');
process_command(cmd);
}
}