Production Architecture · April 2024–Present

Brain-Computer
Interface DApp

EEG · LLM Intent Classification · Ed25519 Provenance · Blockchain Ledger

A clinical-grade BCI pipeline designed for children with motor impairments. Raw EEG signals become cryptographically signed, tamper-evident session records committed to a SHA-256 hash-chained ledger, no full blockchain node required.

Live Demo View Source
41 Tests · 100% Passing
4 EEG Channels
5 Band Powers
<200ms Per Session

The Problem Space

Giving Children a Voice
Without Words or Motion

Children with motor impairments need a non-invasive path to digital interaction. Raw EEG signals are noisy, high-dimensional, and clinically meaningless without interpretation, and every interpretation used in therapy must be auditable.

🧠

EEG Signal Complexity

Raw 4-channel Emotiv EPOC data spanning delta through gamma bands requires FFT band-power extraction and SNR estimation before any meaningful classification can begin.

🤖

Intent Classification

Mapping EEG features to user intent, relax, focus, fatigue, select, requires either rule-based heuristics or an LLM agent with a domain-specific system prompt and temperature-controlled inference.

🔐

Clinical Auditability

Any therapeutic BCI system must produce tamper-evident records. Every session must be cryptographically signed with Ed25519 so clinicians can verify that no interpretation was altered.

⛓️

Blockchain Provenance

SHA-256 hash-chained blocks provide a ledger that any party can audit offline. The architecture is chain-agnostic, swap _save/_load for Anchor calls to go on-chain with Solana.

System Architecture

Four-Stage Pipeline

Each session flows through four deterministic, independently testable stages. The signing and hashing layers are fully chain-agnostic.

🌊
EEG Simulator
EEGSimulator · EEGFrame
🧬
BCI Agent
BCIAgent · IntentResult
🔏
Provenance
ProvenanceManager · Ed25519
📦
Blockchain Ledger
MockBlockchainLedger · Block

EEG · Channels

  • Fp1, Fp2, C3, C4
  • 256 Hz sampling rate
  • 2.0s analysis window
  • FFT band-power extraction
  • SNR estimation (dB)

LLM · Inference

  • relax / focus / fatigue / select
  • OpenAI-compatible endpoint
  • temperature = 0.2
  • Rule-based fallback (offline)
  • Confidence + reasoning output

Provenance · Signing

  • Ed25519 (128-bit security)
  • ~64-byte signatures
  • Canonical JSON (sort_keys)
  • Self-contained verification
  • Solana-native key format

Ledger · Chain

  • SHA-256 hash-chaining
  • Frozen immutable Blocks
  • JSON persistence
  • verify_chain() audit
  • Solana Anchor-ready

Live BCI Pipeline Demo

Watch simulated EEG sessions flow through the full pipeline in real time. Each session generates intent, signs provenance, and appends a block.

bci-dapp · murtazai-bci-dapp · main
$ bci-dapp --n 5 --export
════════════════════════════════════════════════════════════
  MurtazAI BCI DApp, EEG: LLM → Blockchain Provenance
════════════════════════════════════════════════════════════
 
Ready
Fp1, Prefrontal Left
Fp2, Prefrontal Right
C3, Motor Cortex Left
C4, Motor Cortex Right

Module Reference

Six Core Modules

Each module is independently testable, strictly typed with mypy strict mode, and frozen-dataclass immutable. 41 tests across 3 test files.

eeg_simulator.py

Generates intent-biased 4-channel EEG frames at 256 Hz. FFT band-power extraction across δ θ α β γ bands. All randomness through seeded numpy Generator for full reproducibility.

EEGSimulator EEGFrame FFT numpy 256 Hz 11 tests
llm_agent.py

Classifies EEG features into relax / focus / fatigue / select via any OpenAI-compatible endpoint. Rule-based fallback handles offline/CI runs. Never silently drops a session.

BCIAgent IntentResult temperature=0.2 fallback 13 tests
provenance.py

Ed25519 keypair generation and session signing. Canonical JSON serialisation (sort_keys=True) ensures deterministic signatures regardless of field insertion order.

ProvenanceManager Ed25519 cryptography≥42 Solana-native
blockchain_ledger.py

Append-only SHA-256 hash-chained ledger with JSON persistence. verify_chain() walks every block recomputing hashes. Swap _save/_load with Anchor calls for Solana deployment.

MockBlockchainLedger Block SHA-256 ChainVerification 17 tests
exceptions.py

Typed error hierarchy: BCIDAppError: SignatureError, ChainIntegrityError, ClassificationError. Always catch specific types rather than bare Exception.

BCIDAppError SignatureError ChainIntegrityError ClassificationError
settings.py

Frozen, slots=True dataclass singleton loaded once at import. All fields overridable via environment variables. LLM_BASE_URL defaults to OpenAI but accepts any compatible endpoint.

Settings frozen=True slots=True env vars dotenv

Quick Start

Python ≥ 3.11. No API key needed for rule-based mode. One command launches the full pipeline.

01

Clone & Install

Clone the repo and install with dev tools using pip install -e ".[dev]". Pre-commit hooks included.

02

Configure

Copy .env.example to .env. Set OPENAI_API_KEY for LLM mode, or leave empty for rule-based fallback.

03

Run

Execute bci-dapp for 5 sessions. Add --n 20 --llm --export to customise count, classifier, and ledger export.

bash
# Clone and install
git clone https://github.com/murtazaai/murtazai-bci-dapp.git
cd murtazai-bci-dapp
pip install -e ".[dev]"

# Run the pipeline (rule-based, no API key needed)
bci-dapp

# Options
bci-dapp --n 20                 # custom session count
bci-dapp --llm                  # LLM classifier (requires OPENAI_API_KEY)
bci-dapp --export               # write data/ledger_export.json
bci-dapp --n 10 --llm --export  # combine flags

# Tests
pytest                          # all 41 tests
pytest --cov-report=html:htmlcov # coverage report
python
from bci_dapp import (
    EEGSimulator, BCIAgent,
    ProvenanceManager, MockBlockchainLedger,
)

sim        = EEGSimulator(seed=42)       # seed=None for random
agent      = BCIAgent(use_llm=False)    # True requires OPENAI_API_KEY
provenance = ProvenanceManager()
ledger     = MockBlockchainLedger(ledger_path="data/ledger.json")
keypair    = provenance.generate_keypair()

# Run one session
frame    = sim.generate_frame()
features = sim.to_feature_dict(frame)
result   = agent.classify(features)
record   = provenance.sign_session(result.to_payload(), keypair)
block    = ledger.append(record)

print(f"intent={result.intent}  confidence={result.confidence:.0%}")
print(f"block=#{block.index}  hash={block.block_hash[:16]}…")
print(f"sig_valid={provenance.verify_record(record)}")

# Verify full chain
v = ledger.verify_chain()
print(f"chain valid={v.valid}  blocks={ledger.height}")
Variable Default Description
LLM_BASE_URL https://api.openai.com/v1 OpenAI-compatible endpoint, swap for rig-core or Ollama
LLM_MODEL gpt-4o-mini Model identifier passed to the completion endpoint
OPENAI_API_KEY empty When absent, rule-based classifier is used automatically
EEG_SAMPLING_RATE 256 Simulated sample rate in Hz (matches Emotiv EPOC)
EEG_WINDOW_SEC 2.0 Analysis window duration in seconds
LEDGER_PATH data/ledger.json JSON file path for ledger persistence
LOG_LEVEL INFO DEBUG, INFO, WARNING, ERROR, CRITICAL
APP_DEBUG false Enable debug mode (true / 1 / yes)

Engineering Choices

Design Decisions

Every architectural choice was deliberate. Here's the reasoning behind the most consequential ones.

Ed25519 over ECDSA
Ed25519 provides 128-bit security with ~64-byte signatures and constant-time signing, suitable for resource-constrained BCI hardware. The same key format is native to Solana's Ed25519Program, so on-chain migration requires no cryptographic changes. The cryptography≥42 implementation is production-grade.
Frozen Dataclasses Everywhere
EEGFrame, IntentResult, Block, ChainVerification, and Settings are all frozen=True, slots=True. This enforces immutability at the Python level, reduces per-instance memory overhead, and makes objects safe to hash and cache. Block.__post_init__ uses object.__setattr__ to set block_hash, the correct idiom for frozen instances.
Rule-based Fallback, Not Silent Failure
BCIAgent.classify catches only recoverable errors (URLError, JSONDecodeError, KeyError, ValueError) and returns a valid IntentResult prefixed [LLM fallback: …]. The pipeline never silently drops a session. This is explicitly tested: test_fallback_on_llm_failure_preserves_result points at localhost:0 to force a connection error.
Seeded numpy RNG Throughout
All randomness flows through self._rng = np.random.default_rng(seed), including intent selection, phase angles, noise, and SNR sampling. The original code used random.choice which bypassed the numpy seed, that was fixed. Two tests enforce reproducibility as a regression guard.
Canonical JSON for All Hashing
Both ProvenanceManager.sign_session and Block.compute_hash serialise with sort_keys=True, separators=(",", ":"). Field insertion order is irrelevant to signature and hash validity, which matters when records travel over HTTP or are reconstructed from storage.

Project Story

Situation · Task · Action · Result

A system designed to bridge neuroscience, agentic AI, and Web3 provenance, all in a single runnable project.

S, Situation

Children Who Can't Speak or Move Need a Digital Voice

Children with motor impairments need a non-invasive way to interact with digital environments. Raw EEG signals are noisy, high-dimensional, and clinically meaningless without interpretation, and any interpretation used in a therapeutic context must be auditable and tamper-evident to maintain trust with clinicians and families.

T, Task

One Project. Three Domains. Fully Runnable.

Design and build a complete BCI DApp pipeline that takes simulated Emotiv EPOC signals, classifies user intent with an LLM agent, and commits every interpretation to a cryptographically signed, hash-chained ledger, demonstrating rig-core agentic AI and Web3 blockchain architecture in a single screencast-ready project.

A, Action

Four Modules, Built for Production from Day One

  • Built EEGSimulator to produce intent-biased 4-channel EEG at 256 Hz with FFT band-power extraction. All randomness through seeded numpy Generator, every test run is exactly reproducible.
  • Wired BCIAgent against rig-core / OpenAI-compatible /chat/completions with a BCI-specific system prompt and temperature=0.2. Deterministic rule-based fallback for offline/CI runs.
  • Implemented ProvenanceManager using Ed25519 — every payload canonically serialised and signed before it touches the ledger. Self-contained records verifiable without trusting any server.
  • Built MockBlockchainLedger with SHA-256 hash-chaining, frozen immutable Block dataclasses, JSON persistence, and full verify_chain() integrity checking.
  • Applied python_template standard: src/ layout, pyproject.toml, ruff, mypy strict, pytest-cov ≥ 80%, pre-commit hooks, GitHub Actions CI on Python 3.11 + 3.12.
  • Added Zed IDE integration: 29 task runner configs and 17 DAP debug configurations covering every module, pytest variant, CLI option, and remote-attach scenario.
R, Result

41 Tests. 100% Passing. <200ms Per Session.

A fully runnable, screen-capturable demo showing EEG : LLM: signed provenance: verified chain in under 200 ms per session. Replacing _save/_load in MockBlockchainLedger with Anchor program calls produces a production Solana deployment, the signing, hashing, and classification layers are fully chain-agnostic and production-grade today.

MA
Pakistan · Remote · Open to US/EU
Python 3.11+ MIT License Typed: Strict Ruff Linted

Murtaza Ali Imtiaz

Polar Bear Systems · MurtazAI

Builder of production-architecture AI systems at the intersection of neuroscience, language models, and decentralised provenance. Designed the BCI DApp to demonstrate that clinical-grade auditability doesn't require a full blockchain node, just good cryptography and disciplined engineering.