High-Performance Secp256k1 Implementation with CUDA and RISC-V Support

18 replies 302 views
fox_nodeFull Member
Posts: 59 · Reputation: 495
#1Mar 30, 2017, 08:58 PM
Hey all, I’ve been developing a super-efficient version of secp256k1 from the ground up using C++ and CUDA, with optional optimizations for x86-64 (BMI2/ADX) and RISC-V. This project is all about boosting architectural efficiency, conducting benchmarks, and creating a hardware-optimized ECC implementation. Just to be clear, it’s not aimed at cracking cryptography or recovering private keys. ### What I'm Aiming For * Build secp256k1 without relying on any external big-integer libraries * Keep a predictable memory layout * Steer clear of dynamic allocations in performance-critical areas * Push the limits of hardware performance ### What’s Included * Full field arithmetic (mod p) * Scalar arithmetic (mod n) * Support for Affine and Jacobian coordinates * GLV optimization * CPU tweaks (BMI2/ADX) * RISC-V RV64GC compatibility * Batch kernels with CUDA * A suite for benchmarking is also part of it ### Performance Stats On an RTX 5060: Around 2.5 billion Jacobian mixed-add operations per second (this is what I measured) The CPU tests show a 3-5x boost compared to basic implementations when leveraging BMI2/ADX. ### My Design Philosophy I see elliptic curve math as a challenge of interfacing with hardware: * Little-endian limb layout that enhances computation efficiency * Explicit management of carries * Using Montgomery’s trick for batch inversion * Keeping abstraction low in performance-critical code The aim is to minimize unnecessary data movement and maintain predictability in arithmetic at the instruction level. ### Important Clarification This project does NOT assert: * Any vulnerabilities in secp256k1 * The feasibility of discrete log attacks * The possibility of private key recovery It’s designed solely for research on performance, benchmarking, and educational purposes related to ECC implementation.
2 Reply Quote Share
fox_nodeFull Member
Posts: 59 · Reputation: 495
#2Mar 31, 2017, 03:14 AM
Thank you for the valuable observation — I fully agree with your point regarding Fermat-based inversion and side-channel considerations. At the current stage, the library is primarily focused on performance research and architectural exploration. Some inversion paths are optimized for raw throughput rather than strict constant-time guarantees, particularly in closed or controlled environments where side-channel exposure is not a concern. However, side-channel resistance and deterministic execution are already planned as a next development stage. The long-term design goal is to maintain two distinct operational modes: 1. A maximum-performance mode     Intended for closed systems or benchmarking scenarios where side-channel leakage is not a threat model and absolute throughput is prioritized. 2. A hardened mode     Intended for exposed or wallet-level architectures, where additional protections will be introduced, including:    - Fermat-based inversion (p-2 exponentiation)    - Montgomery ladder for scalar multiplication    - Strict constant-time arithmetic paths    - Reduced branch-dependent behavior The idea is to allow developers integrating the library to explicitly choose the security/performance profile that matches their deployment environment. I believe separating performance research from hardened cryptographic deployment is important to avoid mixing tradeoffs implicitly. Your comment reinforces the direction I intend to take in the hardened path — much appreciated.
6 Reply Quote Share
fox_nodeFull Member
Posts: 59 · Reputation: 495
#3Apr 2, 2017, 04:02 AM
Added OpenCL ESP32 support optimized few more library part
4 Reply Quote Share
fox_nodeFull Member
Posts: 59 · Reputation: 495
#4Apr 3, 2017, 02:05 PM
# 🔥 UltrafastSecp256k1 — Feature Overview UltrafastSecp256k1 is a zero-dependency, multi-platform secp256k1 stack covering the entire modern Bitcoin/EVM ecosystem — from field arithmetic to advanced multi-party protocols. ## 🧠 Core Engine * Field / Scalar / Point arithmetic * GLV endomorphism acceleration * Precomputation tables * Deterministic RFC6979 nonces * Strict low-S normalization ## ⚙ Assembly & SIMD * x64 (MASM/GAS, BMI2/ADX) * ARM64 inline assembly * RISC-V + RVV * Montgomery batch inversion * AVX2 / AVX-512 batch ops ## 🔐 Constant-Time Layer * Constant-time field/scalar/point operations * Separate `secp256k1::ct` namespace * Montgomery ladder scalar multiplication * Side-channel resistant design * No runtime flag switching (explicit API separation) ## ✍ Digital Signatures ### ECDSA * Sign / Verify * DER / Compact * Pubkey recovery (recid) * Batch verification ### Schnorr (BIP-340) * Sign / Verify * Batch verification * X-only public keys ## 🤝 Multi-Party & Advanced Protocols * MuSig2 (2-round aggregation) * FROST (t-of-n threshold signatures) * Adaptor signatures * Pedersen commitments * Multi-scalar multiplication (Strauss/Shamir) * ECDH (raw, x-only, SHA-256) ## 🟢 Bitcoin Stack * Taproot (BIP-341/342) * BIP-32 HD derivation (xprv/xpub) * BIP-44 coin-type derivation * BIP-352 Silent Payments * Address generation:   * P2PKH   * P2WPKH   * P2TR   * Base58Check   * Bech32 / Bech32m ## 🌍 Multi-Chain Support (27+ Coins) * BTC, LTC, DOGE, BCH, BSV * ETH (EIP-55) * DASH, ZEC, RVN, QTUM, etc. * Auto-dispatch address generation * Coin-aware HD derivation * Built-in Keccak-256 ## 🔬 Research & Customization * Custom generator support * Fully custom curve context * Zero-overhead default path * Deterministic vector self-tests * Cross-backend layout validation ## 🚀 GPU Backends * CUDA kernels * OpenCL backend * ROCm/HIP portability * Occupancy tuning * PGO support * Inline PTX * Branchless field ops ## 📦 Platforms * x86-64 * ARM64 * RISC-V * ESP32 * STM32 * WebAssembly (Emscripten) * iOS (SPM, CocoaPods, XCFramework) * Android (NDK) * CUDA / OpenCL / ROCm ## 🧪 Testing & Quality * 200+ tests * Fuzz harnesses * Cross-platform CI * Known vector verification * Deterministic reproducibility
4 Reply Quote Share
5tack5atsSenior Member
Posts: 142 · Reputation: 897
#5Apr 3, 2017, 02:45 PM
Went through the repo. Your code is the first (public) I've ever seen which does block batch inversion (e.g. a single inverse for the entire block of threads, via shared memory). So, congrats on this, it took me several weeks to write something which is almost identical in nature (and later discovering syncthreads bugs after two years, reading un-synced sibling values from bad warp scheduling, only on specific cards, it was a pain to debug!). So this looks good but seems way too generic. Obviously, specific requirements can benefit from much larger optimizations.
0 Reply Quote Share
LuckyCoinLegendary
Posts: 832 · Reputation: 4795
#6Apr 3, 2017, 05:36 PM
I am interested in knowing what hardware you used to test the RISC-V version. Maybe even the ARM version as well, since Raspberry-Pis and Arduinos aren't exactly known for their compute power (to say nothing about their NVIDIA gpu interfacing support). This can run on Metal, correct? On Apple silicon. It would be the first secp256k1 library to do that if true.
1 Reply Quote Share
fox_nodeFull Member
Posts: 59 · Reputation: 495
#7Apr 3, 2017, 09:37 PM
hello i have Milk-V Mars Device and i compiled and benchmarked on it i dont have any other risc-v device at this moment. i also ordered esp32 risc-v version planing to port on it too I used Milk-v Mars, My library is zero dependent will work evrywhere you wish i tested on esp32-s3 esp32-pico-4d on STM32 on android device with rockchip works and builds evrywhere without any problems i'm not using any external libraries. i dont have apple devices for test but with githubg actions it builded without problem i dont have all kind of hardware but will be glad to hire benchmar results from comunity on different platforms. and see any issues so i fixed them with you on Raspi will work without problem i dont have raspi at this moment to build and test on it but with CLand LLVM you can build it on all platforms. I'm open on any new ideas and optimization suggestions all code is open in repo evry one can check all part of code. will be glad to hire suggestions and new benchmark results on different hardware i started Metal Support development but dont have real device to test it if you have we can colaborate v3.3.0 Latest What's New in v3.3.0 Comprehensive Benchmarks (Metal + WASM) Metal GPU benchmark (bench_metal.mm): 9 operations — Field Mul/Add/Sub/Sqr/Inv, Point Add/Double, Scalar Mul (P×k), Generator Mul (G×k). Matches CUDA benchmark format with warmup, kernel-only timing, and throughput tables. 3 new Metal GPU kernels: field_add_bench, field_sub_bench, field_inv_bench added to secp256k1_kernels.metal WASM benchmark (bench_wasm.mjs): Node.js benchmark for all WASM-exported operations — Pubkey Create (G×k), Point Mul (P×k), Point Add (P+Q), ECDSA Sign/Verify, Schnorr Sign/Verify, SHA-256 (32B/1KB) WASM Benchmark Results (CI, Node.js v20, linux x64) Operation   Time/Op   Throughput SHA-256 (32B)   649 ns   1.54 M/s SHA-256 (1KB)   6.33 µs   158 K/s Point Add (P+Q)   22 µs   45 K/s Pubkey Create (G×k)   70 µs   14 K/s Schnorr Sign   92 µs   11 K/s ECDSA Sign   146 µs   7 K/s Point Mul (P×k)   693 µs   1.4 K/s ECDSA Verify   825 µs   1.2 K/s Schnorr Verify   874 µs   1.1 K/s CI Hardening WASM benchmark now runs in CI (Node.js 20 setup + execution in wasm job) Metal: skip generator_mul test on non-Apple7+ paravirtual devices (CI fix) Benchmark alert threshold raised from 120% → 150% (reduces false positives on shared CI runners) Fix WASM runtime crash: removed --closure 1, added -fno-exceptions, increased WASM memory (4MB initial, 512KB stack) Bug Fixes Fix Metal shader compilation errors (MSL address space mismatches, jacobian_to_affine ordering) Fix keccak rotl64 undefined behavior (shift by 0) Fix macOS build flags for Clang compatibility Fix metal2.4 shader standard for newer Xcode toolchains Remove unused .cuh files and sorted_ecc_db Testing & Quality Unified test runner (12 test files consolidated) Selftest modes: smoke (fast), ci (full), stress (extended) Boundary KAT vectors, field limb boundary tests, batch inverse sweep Repro bundle support for deterministic test reproduction Sanitizer CI integration (ASan/UBSan) Security & Maturity SECURITY.md v3.2, THREAT_MODEL.md API stability guarantees documented Fuzz testing documentation Security contact: payysoon@gmail.com Documentation Batch inverse & mixed addition API reference with examples (full point, X-only, CUDA, division, scratch reuse, Montgomery trick) README cleanup: removed AI-generated text, translated Georgian → English Removed database/lookup/bloom references from public docs Metal Backend Improvements Apple Metal GPU backend with Comba-accelerated field arithmetic 4-bit windowed scalar multiplication on GPU Chunked Montgomery batch inverse Branchless bloom check with coalesced memory access Apple Metal (Apple M3 Pro) — Kernel-Only Operation   Time/Op   Throughput Field Mul   1.9 ns   527 M/s Field Add   1.0 ns   990 M/s Field Sub   1.1 ns   892 M/s Field Sqr   1.1 ns   872 M/s Field Inv   106.4 ns   9.40 M/s Point Add   10.1 ns   98.6 M/s Point Double   5.1 ns   196 M/s Scalar Mul (P×k)   2.94 μs   0.34 M/s Generator Mul (G×k)   3.00 μs   0.33 M/s v3.4.0 — Apple Metal GPU Backend Latest @shrec shrec released this 2 minutes ago  v3.4.0  c068e1d What's New Apple Metal GPU Compute Backend First secp256k1 library with Apple Metal compute support (M1/M2/M3/M4). 8x32-bit Comba product scanning (MSL has no uint64_t) 4-bit windowed scalar multiplication with branchless table select Zero-copy unified memory (MTLResourceStorageModeShared) Comprehensive benchmark suite (CUDA-format output) Runtime .metallib compilation fallback Benchmarks (Apple M3 Pro, 18 GPU cores) Operation   Time/Op   Throughput Field Mul   1.8 ns   560 M/s Field Add   1.2 ns   801 M/s Field Sqr   1.0 ns   985 M/s Field Inv   106.4 ns   9.4 M/s Point Double   5.0 ns   198 M/s Point Add   11.1 ns   90 M/s Scalar Mul (P*k)   2.95 us   340 K/s Generator Mul (G*k)   2.85 us   350 K/s Fixes Apple9+ (M3) GPU family detection fix (enum vs macro guard) All Supported Platforms CPU: x86-64, ARM64, RISC-V, ESP32-S3, ESP32, STM32F103 GPU: CUDA, OpenCL, Metal (NEW) Mobile: Android ARM64 Web: WebAssembly
7 Reply Quote Share
im_lynxHero Member
Posts: 515 · Reputation: 2161
#8Apr 4, 2017, 01:37 AM
Your completely unnecessary consecutive posts are a nuisance and violation of rule #32 of Unofficial list of (official) Bitcointalk.org rules, guidelines, FAQ. I'm sure you can do better. It's not rocket science to edit your own post if it's the last in a thread and you want to add something new. Your topic is interesting, don't ruin it by annoying consecutive posts.
5 Reply Quote Share
fox_nodeFull Member
Posts: 59 · Reputation: 495
#9Apr 4, 2017, 05:34 AM
thanks. I will take into account
1 Reply Quote Share
5igm442Member
Posts: 3 · Reputation: 76
#10Apr 4, 2017, 10:01 AM
Very interesting project! Keep up the good work. Out of curiosity which AI assistant / agent / model do you use to speed up the process?
2 Reply Quote Share
fox_nodeFull Member
Posts: 59 · Reputation: 495
#11Apr 4, 2017, 03:06 PM
thanks. I'm Using my 20 year development experience and all models together to fast analyze and found bottlenecks and improve them. to make platform specific assembler codes and so on.
0 Reply Quote Share
fox_nodeFull Member
Posts: 59 · Reputation: 495
#12Apr 4, 2017, 05:30 PM
Benchmark: UltrafastSecp256k1 vs libsecp256k1 on BIP-352 scanning pipeline https://github.com/shrec/UltrafastSecp256k1/issues/87
0 Reply Quote Share
farm_2014Member
Posts: 9 · Reputation: 93
#13Apr 4, 2017, 06:17 PM
Hello shrec. I quickly check your code on github for Cuda and maybe i miss something but you don't seem to use precomputed table for Ecmult . With this trick you can speed up the k.G process maybe by 15 times with 2x32MB  table (one for x one for y). (16 jacobians additions instead of 256) . Of course the tables are only compatible with one Generator (typically the G of secp256k1)  You can read this post if you want more info https://bitcointalk.org/index.php?topic=5396293.20
4 Reply Quote Share
fox_nodeFull Member
Posts: 59 · Reputation: 495
#14Apr 5, 2017, 12:06 AM
thank you very much for your answer i noted this. i'm still optimizing cpu/mcu/sbc part soon will move on gpu optimizations on gpu still some futures are on baselines need future optimizations and tests. i just finished self audit system form improving code quality and correctness
2 Reply Quote Share
fox_nodeFull Member
Posts: 59 · Reputation: 495
#15Apr 5, 2017, 05:17 PM
UltrafastSecp256k1 v3.21 released. Major improvements: • constant‑time SafeGCD scalar inverse • faster CT ECDSA signing • stricter BIP‑340 parsing • expanded audit infrastructure The project now includes cross‑platform benchmarks and reproducible Docker CI. GitHub: https://github.com/shrec/UltrafastSecp256k1 i used your suggestion and get 13x speedup thansk
5 Reply Quote Share
farm_2014Member
Posts: 9 · Reputation: 93
#16Apr 5, 2017, 11:16 PM
You're welcome!
4 Reply Quote Share
fox_nodeFull Member
Posts: 59 · Reputation: 495
#17Apr 6, 2017, 05:27 AM
Ultrafastsecp256k1 and BIP352 with i5cpu and Nvidia 5060ti | Pipeline | Median time | ns/op | Throughput | Speedup | |---|---:|---:|---:|---:| | CPU reference | 244.0 ms / 10,000 ops | 24,404.6 | 0.041 Mops/s | 1.00x | | CUDA GLV | 2.609 ms / 10,000 ops | 260.9 | 3.83 Mops/s | 93.55x vs CPU | | CUDA LUT | 1.274 ms / 10,000 ops | 127.4 | 7.85 Mops/s | 191.56x vs CPU, 2.05x vs CUDA GLV |
1 Reply Quote Share
fox_nodeFull Member
Posts: 59 · Reputation: 495
#18Apr 7, 2017, 03:34 AM
UltrafastSecp256k1 v3.3 Implemented GPU CABI now on all languages are avalible GPU futures via CABI and Language Bindings Added Ethereum ZK layer 17–67× batch ops speedup OpenCL ~10% generator mul — affine table optimization CUDA precomputed tweak tables Schnorr batch verify — 8 optimization and speedup Metal GPU — GLV + wNAF + LUT feature parity Security — Solinas reduction, CT signing, secret cleanup 463+ code-scanning alerts Audit infrastructure P0+P1+P2 complete Bug fixes (ARM64 SHA-256, MSVC C2026) BIP352 with 5060ti 10 milions /sec CUDA/OPENCL
1 Reply Quote Share
fox_nodeFull Member
Posts: 59 · Reputation: 495
#19Apr 8, 2017, 03:04 PM
Update: CAAS — Continuous Adversarial Audit Standard Instead of a $100K third-party audit PDF, I built a continuous adversarial audit system that runs on every commit: ~1,000,000+ assertions per build 205 security test files (187 exploit PoCs covering CVE/ePrint attack classes) 3 independent CT pipelines: LLVM ct-verif + Valgrind taint + dudect Formal proofs: Z3 SMT (17 proofs) + Lean 4 (19 theorems) on scalar inverse 1.3M nightly differential checks vs libsecp256k1 Full Docker CI — reproducible by anyone: docker run --rm ufsecp-auditor Real catch: RISC-V port, GCC optimized CT code into secret-dependent branches. Caught on first run. Bug capsule created, permanent CI gate. CAAS spec: https://github.com/shrec/UltrafastSecp256k1/blob/main/docs/AUDIT_STANDARD.md
0 Reply Quote Share

Related topics