ckb light esp
A from-scratch C implementation of the CKB light client protocol (RFC 0044), targeting the ESP32-P4 with external PSRAM. Also builds as a POSIX library for host
ENGLISH VERSION
1. Introduction: Blockchain Light Clients and Their Challenges
A blockchain light client is a simplified node that verifies transactions without storing the entire blockchain. Unlike full nodes that maintain complete transaction history (often 100GB+), light clients download only block headers and verify authenticity through cryptographic proofs.
Why Light Clients Matter:
- Mobile & IoT Accessibility: Enables blockchain verification on resource-constrained devices (smartphones, embedded systems)
- Instant Sync: No need to download gigabytes of blockchain data—synchronization completes in seconds
- Trust-Minimized Verification: Cryptographically verifies data without relying on centralized servers
This project implements a CKB (Common Knowledge Base) blockchain light client on the ESP32-P4 microcontroller, using pure C99 without external dependencies. The implementation follows RFC 0044 and leverages hardware-accelerated networking for efficient verification.
2. Technical Challenge: Why Traditional Approaches Fall Short
Most blockchain light client implementations face a critical tradeoff between security and resource requirements:
| Approach | Pros | Cons |
|---|---|---|
| SPV (Simplified Payment Verification) | Lightweight, downloads only block headers (80 bytes each) | Vulnerable to malicious majority attacks; still requires downloading every header |
| FlyClient Sampling | Downloads only logarithmic sample of blocks; cryptographic security via MMR proofs | Requires sophisticated cryptography (Blake2b, MMR); complex P2P protocol implementation |
The Solution: FlyClient + Hardware TCP/IP
This project implements FlyClient's logarithmic verification approach, but offloads networking complexity to a hardware TCP/IP stack. By using the ESP32-P4's native networking capabilities, the MCU can focus 100% of CPU cycles on cryptographic verification rather than managing TCP connections, TLS handshakes, or socket buffers.
3. Hardware Architecture: ESP32-P4 and External PSRAM
Component Selection Rationale:
ESP32-P4 Microcontroller:
- Dual-core RISC-V processor at 400MHz: Sufficient computational power for Blake2b hashing (cryptographic hash function used in CKB)
- Hardware cryptography accelerator: Offloads SHA-256 and AES operations (future-proof for ChaCha20-Poly1305 encryption in Phase 2)
- Native Ethernet MAC: No external PHY required—direct connection to network via RMII interface
External PSRAM (Pseudo-Static RAM):
- Capacity: 8MB+ external PSRAM for storing MMR (Merkle Mountain Range) proofs, block headers, and transaction buffers
- Why PSRAM?: CKB headers (~200 bytes each) and MMR proofs can exceed internal SRAM (512KB). PSRAM provides expandable memory without requiring external DRAM controllers.
Memory Management Strategy: The implementation uses a hybrid memory model—frequently accessed data (current header, verification state) resides in fast SRAM, while historical headers and MMR proof chains are cached in PSRAM. This minimizes PSRAM access latency while maintaining compact memory footprint.
4. Core Cryptographic Components
A. Blake2b Hash Function
Blake2b is CKB's primary hash function, chosen over SHA-256 for its speed and security:
- Performance: Faster than SHA-256 on modern hardware (even without SIMD acceleration)
- Security: Derived from ChaCha stream cipher; resistant to length-extension attacks
- Implementation: Pure C99, no external dependencies. Supports both Blake2b-256 (32-byte output for block hashes) and Blake2b-512 (64-byte output for transaction IDs)
Verification Workflow:
Each block header contains a Blake2b-256 hash of the previous header. The light client verifies chain continuity by recomputing hashes and comparing against received headers—if hashes match, the chain is authentic; if not, the header is rejected as fraudulent.
B. Molecule Serialization
Molecule is CKB's zero-copy serialization format, designed for deterministic encoding:
- Zero-copy parsing: Data structures are accessed directly from network buffers without deserialization—critical for memory-constrained devices
- Type safety: Schema-defined structures prevent parsing errors (fixed-size arrays vs. dynamic vectors)
- Compact representation: Optimized for network transmission—no padding, no metadata overhead
The implementation includes C parsers for CKB block headers, scripts, transactions, and cell outputs. Each parser validates structure boundaries before accessing fields, preventing buffer overruns.
C. MMR (Merkle Mountain Range) Proof Verifier
MMR is the core of FlyClient's logarithmic verification. Unlike traditional Merkle trees (which require power-of-2 leaf counts), MMR allows incremental proof construction as new blocks arrive:
- Structure: A forest of perfect binary trees, where each tree has height H (0, 1, 2, 3...) corresponding to 2^H leaves
- Proof size: O(log n) hashes to prove inclusion of any block in a chain of n blocks
- Verification: Client samples random blocks → receives MMR proofs → recomputes root hash → compares against known MMR commitment
Security Guarantee: If an adversary modifies even one block, the MMR root hash will mismatch with overwhelming probability (≈ 1 - 2^-256 for Blake2b-256). This makes fraudulent chains computationally infeasible to forge.
5. Network Communication: Hardware TCP/IP vs. Software Stacks
The Critical Decision: Why Hardware TCP/IP?
Blockchain P2P protocols involve complex requirements:
- Multiple concurrent connections: Light clients must maintain connections to 4-8 peers simultaneously for redundancy
- TLS encryption: CKB uses Noise protocol (X25519 key exchange + ChaCha20-Poly1305 AEAD) for encrypted transport
- Stream multiplexing: Yamux protocol multiplexes multiple logical streams over single TCP connection
Implementing these in software (e.g., lwIP TCP/IP stack + mbedTLS) would consume:
- ~80KB SRAM: For TCP buffers, TLS session state, and stack overhead
- ~40% CPU: For TCP acknowledgment, retransmission logic, and TLS cipher operations
ESP32-P4's Hardware Advantage:
The ESP32-P4's integrated Ethernet MAC + PHY handles the entire TCP/IP stack in hardware. The MCU simply writes data to DMA buffers, and the hardware manages:
- TCP segment framing and checksumming
- ACK generation and retransmission timers
- IP fragmentation and reassembly
This frees the CPU to focus on Blake2b hashing, MMR verification, and Molecule parsing—operations that cannot be hardware-accelerated.
6. Software Architecture and Data Flow
A. Three-Phase Development Strategy
Phase 1: Core Crypto & Serialization (Current)
- Deliverables: Blake2b implementation, Molecule parser, MMR proof verifier, CKB address derivation (secp256k1 lock script)
- Testing: POSIX host build for Linux/macOS—tests run on development machine before deploying to ESP32-P4
Phase 2: Transport Layer
- Components: Noise protocol handshake (X25519 ECDH + ChaCha20-Poly1305), Yamux stream multiplexer, Tentacle frame codec
- Integration: ESP-IDF's lwIP provides TCP sockets; this phase adds encryption and multiplexing on top
Phase 3: Light Client Protocol
- RFC 0044 message types: GetHeaders, SendHeaders, GetTransactions, SendTransactions
- FlyClient block sampling: Probabilistic verification of chain weight
- Script watching: Monitor specific addresses for incoming transactions
B. Testing and Deployment Strategy
The project uses a dual-build system:
- Host build (POSIX): Compiles to Linux/macOS executable. Runs unit tests (test_blake2b, test_mmr) with known test vectors from CKB reference implementation.
- ESP-IDF build: Cross-compiles to RISC-V binaries. Flashes to ESP32-P4 development board and connects to CKB testnet for live verification.
This approach ensures cryptographic correctness before deploying to hardware, reducing debugging cycles.
7. Comparison with Hardware Ethernet Solutions
Architectural Parallel to Hardware TCP/IP Projects:
This project shares design philosophy with hardware TCP/IP-based IoT systems:
- Offload network complexity to hardware: Dedicated TCP/IP chips handle protocol processing; ESP32-P4's Ethernet MAC provides similar offloading
- Wired connectivity for reliability: Ethernet guarantees deterministic latency vs. Wi-Fi's variable connection overhead
- Minimalist software stack: No OS overhead—bare-metal firmware for predictable timing
Key Difference: Single-Chip Integration
Unlike multi-chip solutions (MCU + separate Ethernet controller communicating via SPI), ESP32-P4 integrates MCU and Ethernet MAC on a single die. This eliminates SPI bus bottlenecks and reduces board complexity—ideal for cost-sensitive IoT deployments where every component counts.
8. Conclusion and Future Applications
Technical Achievements:
- Zero-dependency implementation: Pure C99 code, no external libraries—maximizes portability and audit surface
- Hardware-accelerated verification: Offloads networking to dedicated silicon, freeing CPU for cryptographic operations
- Logarithmic sync time: FlyClient protocol reduces sync from O(n) to O(log n) block downloads
Practical Applications:
- IoT Payment Terminals: Embedded devices accepting CKB payments without full node infrastructure
- Edge Computing: Manufacturing sensors verifying blockchain-recorded provenance data in real-time
- Decentralized Oracles: Low-power nodes aggregating off-chain data and submitting to CKB mainnet
Final Thoughts: By combining blockchain light client technology with hardware-accelerated networking, this project demonstrates that trustless verification is feasible even on resource-constrained embedded systems. The architecture scales from single-chip microcontrollers to industrial IoT deployments, providing a foundation for decentralized applications beyond traditional server-based infrastructure.
Technical Specifications
| Component | Specification |
|---|---|
| MCU | ESP32-P4 (Dual-core RISC-V @ 400MHz) |
| Memory | 512KB SRAM + 8MB+ PSRAM |
| Networking | Integrated Ethernet MAC (RMII interface) |
| Cryptography | Blake2b (software), Hardware SHA/AES accelerator |
| Protocol | CKB RFC 0044 Light Client, FlyClient verification |
| Development | Pure C99, ESP-IDF framework, POSIX host testing |
References
- RFC 0044 — CKB Light Client Protocol: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0044-ckb-light-client/
- Molecule Serialization: https://github.com/nervosnetwork/molecule
- FlyClient Paper: https://eprint.iacr.org/2019/226.pdf
- ESP32-P4 Technical Reference: https://www.espressif.com/en/products/socs/esp32-p4
한국어 버전
1. 서론: 블록체인 라이트 클라이언트와 그 도전 과제
블록체인 라이트 클라이언트는 전체 블록체인을 저장하지 않고도 트랜잭션을 검증할 수 있는 간소화된 노드입니다. 완전한 트랜잭션 기록을 유지하는 풀 노드(종종 100GB 이상)와 달리, 라이트 클라이언트는 블록 헤더만 다운로드하고 암호화 증명을 통해 진위를 검증합니다.
라이트 클라이언트가 중요한 이유:
- 모바일 & IoT 접근성: 리소스가 제한된 장치(스마트폰, 임베디드 시스템)에서 블록체인 검증 가능
- 즉시 동기화: 기가바이트의 블록체인 데이터를 다운로드할 필요 없이 몇 초 만에 동기화 완료
- 신뢰 최소화 검증: 중앙 서버에 의존하지 않고 암호학적으로 데이터 검증
이 프로젝트는 ESP32-P4 마이크로컨트롤러에서 순수 C99로 CKB(Common Knowledge Base) 블록체인 라이트 클라이언트를 구현하며, 외부 의존성이 없습니다. 구현은 RFC 0044를 따르고 효율적인 검증을 위해 하드웨어 가속 네트워킹을 활용합니다.
2. 기술적 과제: 전통적 접근 방식의 한계
대부분의 블록체인 라이트 클라이언트 구현은 보안과 리소스 요구사항 사이의 중요한 트레이드오프에 직면합니다:
| 접근 방식 | 장점 | 단점 |
|---|---|---|
| SPV (간소화된 결제 검증) | 경량, 블록 헤더만 다운로드(각 80바이트) | 악의적 다수 공격에 취약; 여전히 모든 헤더 다운로드 필요 |
| FlyClient 샘플링 | 로그 샘플의 블록만 다운로드; MMR 증명을 통한 암호학적 보안 | 정교한 암호화 필요(Blake2b, MMR); 복잡한 P2P 프로토콜 구현 |
해결책: FlyClient + 하드웨어 TCP/IP
이 프로젝트는 FlyClient의 로그 검증 방식을 구현하지만, 네트워킹 복잡성을 하드웨어 TCP/IP 스택으로 오프로드합니다. ESP32-P4의 네이티브 네트워킹 기능을 사용함으로써 MCU는 TCP 연결, TLS 핸드셰이크 또는 소켓 버퍼 관리가 아닌 암호화 검증에 CPU 사이클의 100%를 집중할 수 있습니다.
3. 하드웨어 아키텍처: ESP32-P4와 외부 PSRAM
구성 요소 선택 근거:
ESP32-P4 마이크로컨트롤러:
- 400MHz 듀얼 코어 RISC-V 프로세서: Blake2b 해싱(CKB에서 사용되는 암호화 해시 함수)을 위한 충분한 계산 능력
- 하드웨어 암호화 가속기: SHA-256 및 AES 작업 오프로드 (Phase 2의 ChaCha20-Poly1305 암호화를 위한 미래 대비)
- 네이티브 이더넷 MAC: 외부 PHY 불필요—RMII 인터페이스를 통한 네트워크 직접 연결
외부 PSRAM (Pseudo-Static RAM):
- 용량: MMR(Merkle Mountain Range) 증명, 블록 헤더 및 트랜잭션 버퍼 저장을 위한 8MB+ 외부 PSRAM
- PSRAM을 사용하는 이유: CKB 헤더(각 ~200바이트)와 MMR 증명은 내부 SRAM(512KB)을 초과할 수 있습니다. PSRAM은 외부 DRAM 컨트롤러 없이 확장 가능한 메모리를 제공합니다.
메모리 관리 전략: 구현은 하이브리드 메모리 모델을 사용합니다—자주 액세스되는 데이터(현재 헤더, 검증 상태)는 빠른 SRAM에 상주하고, 과거 헤더와 MMR 증명 체인은 PSRAM에 캐시됩니다. 이는 PSRAM 액세스 지연 시간을 최소화하면서 컴팩트한 메모리 풋프린트를 유지합니다.
4. 핵심 암호화 구성 요소
A. Blake2b 해시 함수
Blake2b는 CKB의 주요 해시 함수로, 속도와 보안을 위해 SHA-256 대신 선택되었습니다:
- 성능: 현대 하드웨어에서 SHA-256보다 빠름(SIMD 가속 없이도)
- 보안: ChaCha 스트림 암호에서 파생; 길이 확장 공격에 저항
- 구현: 순수 C99, 외부 의존성 없음. Blake2b-256(블록 해시용 32바이트 출력) 및 Blake2b-512(트랜잭션 ID용 64바이트 출력) 모두 지원
검증 워크플로:
각 블록 헤더에는 이전 헤더의 Blake2b-256 해시가 포함됩니다. 라이트 클라이언트는 해시를 재계산하고 수신된 헤더와 비교하여 체인 연속성을 검증합니다—해시가 일치하면 체인이 진짜이고, 일치하지 않으면 헤더가 사기로 거부됩니다.
B. Molecule 직렬화
Molecule은 CKB의 제로 카피 직렬화 형식으로, 결정적 인코딩을 위해 설계되었습니다:
- 제로 카피 파싱: 데이터 구조가 역직렬화 없이 네트워크 버퍼에서 직접 액세스됨—메모리 제약 장치에 중요
- 타입 안전성: 스키마 정의 구조가 파싱 오류 방지(고정 크기 배열 vs. 동적 벡터)
- 컴팩트 표현: 네트워크 전송에 최적화—패딩 없음, 메타데이터 오버헤드 없음
구현에는 CKB 블록 헤더, 스크립트, 트랜잭션 및 셀 출력용 C 파서가 포함됩니다. 각 파서는 필드에 액세스하기 전에 구조 경계를 검증하여 버퍼 오버런을 방지합니다.
C. MMR (Merkle Mountain Range) 증명 검증기
MMR은 FlyClient의 로그 검증의 핵심입니다. 전통적인 머클 트리(2의 거듭제곱 리프 수 필요)와 달리, MMR은 새 블록이 도착할 때 증분 증명 구성을 허용합니다:
- 구조: 완벽한 이진 트리의 숲, 각 트리는 높이 H(0, 1, 2, 3...)를 가지며 2^H 리프에 해당
- 증명 크기: n개의 블록 체인에서 임의 블록의 포함을 증명하기 위한 O(log n) 해시
- 검증: 클라이언트가 무작위 블록 샘플링 → MMR 증명 수신 → 루트 해시 재계산 → 알려진 MMR 커밋과 비교
보안 보장: 공격자가 단 하나의 블록만 수정해도 MMR 루트 해시가 압도적인 확률(Blake2b-256의 경우 ≈ 1 - 2^-256)로 불일치합니다. 이는 사기 체인을 계산적으로 위조하기 불가능하게 만듭니다.
5. 네트워크 통신: 하드웨어 TCP/IP vs 소프트웨어 스택
중요한 결정: 왜 하드웨어 TCP/IP인가?
블록체인 P2P 프로토콜은 복잡한 요구사항을 포함합니다:
- 다중 동시 연결: 라이트 클라이언트는 중복성을 위해 4-8개의 피어에 동시 연결을 유지해야 함
- TLS 암호화: CKB는 암호화된 전송을 위해 Noise 프로토콜(X25519 키 교환 + ChaCha20-Poly1305 AEAD) 사용
- 스트림 다중화: Yamux 프로토콜이 단일 TCP 연결을 통해 여러 논리적 스트림 다중화
소프트웨어로 이를 구현하면(예: lwIP TCP/IP 스택 + mbedTLS) 다음을 소비합니다:
- ~80KB SRAM: TCP 버퍼, TLS 세션 상태 및 스택 오버헤드용
- ~40% CPU: TCP 확인 응답, 재전송 로직 및 TLS 암호 작업용
ESP32-P4의 하드웨어 이점:
ESP32-P4의 통합 이더넷 MAC + PHY는 전체 TCP/IP 스택을 하드웨어로 처리합니다. MCU는 단순히 DMA 버퍼에 데이터를 쓰고, 하드웨어가 다음을 관리합니다:
- TCP 세그먼트 프레임 및 체크섬
- ACK 생성 및 재전송 타이머
- IP 단편화 및 재조립
이는 CPU가 Blake2b 해싱, MMR 검증 및 Molecule 파싱—하드웨어 가속될 수 없는 작업—에 집중할 수 있게 합니다.
6. 소프트웨어 아키텍처 및 데이터 흐름
A. 3단계 개발 전략
Phase 1: 핵심 암호화 및 직렬화 (현재)
- 산출물: Blake2b 구현, Molecule 파서, MMR 증명 검증기, CKB 주소 유도(secp256k1 잠금 스크립트)
- 테스트: Linux/macOS용 POSIX 호스트 빌드—ESP32-P4에 배포하기 전에 개발 머신에서 테스트 실행
Phase 2: 전송 계층
- 구성 요소: Noise 프로토콜 핸드셰이크(X25519 ECDH + ChaCha20-Poly1305), Yamux 스트림 멀티플렉서, Tentacle 프레임 코덱
- 통합: ESP-IDF의 lwIP가 TCP 소켓을 제공; 이 단계는 그 위에 암호화 및 멀티플렉싱 추가
Phase 3: 라이트 클라이언트 프로토콜
- RFC 0044 메시지 유형: GetHeaders, SendHeaders, GetTransactions, SendTransactions
- FlyClient 블록 샘플링: 체인 가중치의 확률적 검증
- 스크립트 감시: 들어오는 트랜잭션에 대한 특정 주소 모니터링
B. 테스트 및 배포 전략
프로젝트는 이중 빌드 시스템을 사용합니다:
- 호스트 빌드 (POSIX): Linux/macOS 실행 파일로 컴파일. CKB 참조 구현의 알려진 테스트 벡터로 단위 테스트(test_blake2b, test_mmr) 실행.
- ESP-IDF 빌드: RISC-V 바이너리로 크로스 컴파일. ESP32-P4 개발 보드에 플래시하고 CKB 테스트넷에 연결하여 라이브 검증.
이 접근 방식은 하드웨어에 배포하기 전에 암호학적 정확성을 보장하여 디버깅 주기를 줄입니다.
7. 하드웨어 이더넷 솔루션과의 비교
하드웨어 TCP/IP 프로젝트와의 아키텍처 유사성:
이 프로젝트는 하드웨어 TCP/IP 기반 IoT 시스템과 설계 철학을 공유합니다:
- 네트워크 복잡성을 하드웨어로 오프로드: 전용 TCP/IP 칩이 프로토콜 처리를 담당; ESP32-P4의 이더넷 MAC은 유사한 오프로딩 제공
- 신뢰성을 위한 유선 연결: 이더넷은 Wi-Fi의 가변 연결 오버헤드 대비 결정적 지연시간 보장
- 미니멀리스트 소프트웨어 스택: OS 오버헤드 없음—예측 가능한 타이밍을 위한 베어메탈 펌웨어
주요 차이점: 단일 칩 통합
다중 칩 솔루션(MCU + SPI를 통해 통신하는 별도 이더넷 컨트롤러)과 달리, ESP32-P4는 MCU와 이더넷 MAC을 단일 다이에 통합합니다. 이는 SPI 버스 병목 현상을 제거하고 보드 복잡성을 줄입니다—모든 구성 요소가 중요한 비용에 민감한 IoT 배포에 이상적입니다.
8. 결론 및 향후 응용
기술적 성과:
- 제로 의존성 구현: 순수 C99 코드, 외부 라이브러리 없음—이식성 및 감사 표면 최대화
- 하드웨어 가속 검증: 네트워킹을 전용 실리콘으로 오프로드하여 암호화 작업을 위한 CPU 해방
- 로그 동기화 시간: FlyClient 프로토콜은 동기화를 O(n)에서 O(log n) 블록 다운로드로 축소
실용적 응용:
- IoT 결제 단말: 풀 노드 인프라 없이 CKB 결제를 수락하는 임베디드 장치
- 엣지 컴퓨팅: 블록체인 기록 출처 데이터를 실시간으로 검증하는 제조 센서
- 분산 오라클: 오프체인 데이터를 집계하고 CKB 메인넷에 제출하는 저전력 노드
최종 생각: 블록체인 라이트 클라이언트 기술을 하드웨어 가속 네트워킹과 결합함으로써, 이 프로젝트는 신뢰 없는 검증이 리소스 제약 임베디드 시스템에서도 실현 가능함을 증명합니다. 아키텍처는 단일 칩 마이크로컨트롤러에서 산업용 IoT 배포로 확장되어 전통적인 서버 기반 인프라를 넘어 분산 애플리케이션의 기반을 제공합니다.
기술 사양
| 구성 요소 | 사양 |
|---|---|
| MCU | ESP32-P4 (듀얼 코어 RISC-V @ 400MHz) |
| 메모리 | 512KB SRAM + 8MB+ PSRAM |
| 네트워킹 | 통합 이더넷 MAC (RMII 인터페이스) |
| 암호화 | Blake2b (소프트웨어), 하드웨어 SHA/AES 가속기 |
| 프로토콜 | CKB RFC 0044 라이트 클라이언트, FlyClient 검증 |
| 개발 | 순수 C99, ESP-IDF 프레임워크, POSIX 호스트 테스팅 |
참고 자료
- RFC 0044 — CKB 라이트 클라이언트 프로토콜: https://github.com/nervosnetwork/rfcs/blob/master/rfcs/0044-ckb-light-client/
- Molecule 직렬화: https://github.com/nervosnetwork/molecule
- FlyClient 논문: https://eprint.iacr.org/2019/226.pdf
- ESP32-P4 기술 참조: https://www.espressif.com/en/products/socs/esp32-p4
