Inline the P = [P0, -1, -1, -1] constant into sub and neg instead
of going through generic U256.addTo/subTo + P array reads.
For sub (add-back P on borrow): when carry from limb 0 is 1, adding
P[1..3]=-1 with carry is identity (no-op). When carry is 0, just
subtract 1 with borrow propagation through limbs 1-3. Replaces a
full 4-limb generic addition with a conditional decrement.
For neg (P - a): uses bitwise NOT for limbs 1-3 (since P[i]=-1,
P[i]-a[i] = ~a[i]) with simple borrow propagation from limb 0.
Replaces a full 4-limb generic subtraction with P array reads.
These are called ~500 times per verify. On JVM/HotSpot the gain is
marginal (inlining already handles this), but on Android ART the
reduced function call depth and eliminated array loads should help.
https://claude.ai/code/session_017UbWduFi1sLUsgVUMUH2nx
Pool toAffine/toAffineX temp LongArrays (zInv, zInv2, zInv3) into
PointScratch. Add scratch-aware overloads that hot paths now use,
keeping allocating convenience overloads for one-time init paths
(buildCombTable).
Consolidate verify/sign/pubCreate/ECDH scratch into shared entry*
fields in PointScratch (entryPx, entryPy, entryPoint, entryResult,
entryTmp, entryTmp2). This replaces the old verify-specific fields
(verifyPx/Py/R/S/E/Rx/Ry/PPoint/Result) with fewer, shared buffers.
Update all Secp256k1 entry points (pubkeyCreate, signSchnorr,
signSchnorrInternal, verifySchnorr, pubKeyTweakMul, ecdhXOnly)
to use scratch instead of per-call allocations.
Add KeyCodec.liftX overload accepting a temp buffer to avoid 1
LongArray allocation per call.
Eliminate 2 longArrayOf allocations in ScalarN.reduceWideTo by
reusing the output array as temporary storage for hi limbs.
https://claude.ai/code/session_017UbWduFi1sLUsgVUMUH2nx
Extract MutablePoint, AffinePoint, and PointScratch from Point.kt into
PointTypes.kt (140 lines). Rename Point.kt to ECPoint.kt (897 lines)
to match the single top-level declaration (ktlint convention).
Remove dead code:
- addWnafJacobian: private function never called (replaced by
addWnafMixedPP with effective-affine tables)
Remove 5 KeyCodec wrapper functions from ECPoint that just delegated
(liftX, hasEvenY, parsePublicKey, serializeUncompressed,
serializeCompressed). Callers in Secp256k1.kt and PointTest.kt now
use KeyCodec directly, making ownership clear: KeyCodec owns key
encoding/decoding, ECPoint owns point arithmetic.
Update Secp256k1.kt header documentation with current benchmark
numbers (verify 1.7x, sign 0.9x faster than native, etc.) and
a concise list of optimizations.
No functional or performance changes — all 170 tests pass, benchmark
numbers unchanged.
https://claude.ai/code/session_017UbWduFi1sLUsgVUMUH2nx
In mulDoubleG (verify), the P-side wNAF-5 affine table (8 odd multiples
of P plus 8 GLV λ counterparts) is rebuilt from scratch on every call.
This costs ~437 field ops: 1 doublePoint + 7 addPoints + 8 β-multiplies
+ 1 batch inversion with full field inversion (~270 ops alone).
Add a 256-entry direct-mapped cache that stores these affine tables
keyed by the point's x-coordinate. On cache hit, the table build is
skipped entirely — the cached arrays are used directly (zero-copy).
This saves ~27% of mulDoubleG cost (~20% of total verify) for repeated
pubkeys. Combined with the liftX cache from the previous commit,
repeated-pubkey verifications now skip ~33% of the work.
JVM benchmark: verify ratio improved from 2.0x to 1.6-1.8x vs native C
(with the benchmark's 100% cache hit rate). Original baseline was 3.0x.
https://claude.ai/code/session_017UbWduFi1sLUsgVUMUH2nx
Add in-place ScalarN operations (mulTo, addTo, negTo) that write to
caller-provided output arrays instead of allocating. Add
Glv.splitScalarInto that uses pre-allocated scratch buffers from
PointScratch, eliminating ~26 LongArray allocations per call (called
2x per verify = ~52 allocs saved). Both mul and mulDoubleG now use
the allocation-free split path.
Pool all LongArray and MutablePoint allocations in verifySchnorr
into thread-local PointScratch (verifyPx/Py/R/S/E/Rx/Ry, verifyPPoint,
verifyResult). Add U256.fromBytesInto for decoding into pre-allocated
arrays. Total: ~14 object allocations eliminated per verify call.
Add pubkey decompression cache (256-entry direct-mapped) that skips
the liftX square root (~280 field ops) for repeated pubkeys. In Nostr,
the same authors are verified repeatedly, so cache hit rate is high.
This saves ~13% of verify cost per cache hit.
Increase benchmark warmup/iterations for more stable measurements
(e.g., verifySchnorr: 200/500 -> 2000/5000).
JVM benchmark result: verify ratio improved from 3.0x to 2.0x vs
native C (with 100% cache hit rate on the benchmark's single pubkey).
https://claude.ai/code/session_017UbWduFi1sLUsgVUMUH2nx
The previous counts (200 warmup / 500 iterations for verify) were too
low for reliable measurements on noisy VMs. Increase to 2000+ warmup
and 3000-50000 iterations depending on operation cost, giving the JIT
time to fully optimize and reducing variance between runs.
https://claude.ai/code/session_017UbWduFi1sLUsgVUMUH2nx
Unroll hot-path loops in U256 (mulWide, sqrWide, addTo, subTo) to
eliminate loop control overhead and array bounds checks that ART JIT
on Android does not optimize as aggressively as HotSpot. These functions
are called ~1,900× per signature verification.
Optimize unsignedMultiplyHighFallback to compute the unsigned 128-bit
product directly from 32-bit sub-products, avoiding the signed
multiplyHigh + correction path. Saves ~8 instructions per call on
Android < API 31 (~30,000 calls per verify).
Unroll FieldP.reduceWide carry propagation and inline the reduceSelf
subtraction (avoiding P array access and U256.subTo call). Unroll
FieldP.half with P[1..3]=-1 inlined as mask.
Replace copyFrom pattern in mul, mulG, and mulDoubleG with ping-pong
point buffers — alternate between two MutablePoints via reference swap
instead of copying 12 Longs after every addition. Eliminates ~170
copyFrom calls per verify and avoids the internal copy buffer in
doublePoint's out===inp path (~130 per verify). Also removes the
MutablePoint() allocation in mulG (3 LongArrays per sign/pubCreate).
https://claude.ai/code/session_017UbWduFi1sLUsgVUMUH2nx
ThreadLocal.withInitial is a JVM-only API that doesn't compile on
Kotlin/Native or iOS targets. Replace all usages in commonMain
(FieldP.kt, Point.kt) with a new ScratchLocal expect/actual:
- jvmMain/androidMain: delegates to java.lang.ThreadLocal (same behavior)
- nativeMain: holds value directly (Kotlin/Native coroutines are
cooperative, scratch buffers don't need thread isolation)
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
When the app restarts and reconnects to relays, old call offer events
from completed calls could be replayed, causing the phone to ring for
calls that already ended. This was especially noticeable when the user
killed and restarted the app shortly after a call.
Three protections added to CallManager:
1. Track completed call IDs: hangup/reject events mark their call-id as
completed. Subsequent offer events for the same call-id are ignored.
2. Init timestamp guard: events created before the CallManager was
initialized (minus a grace period) are rejected, preventing stale
events from a previous app session from triggering ringing.
3. Completed call IDs survive reset(): the set is intentionally not
cleared when the call state machine resets to Idle, ensuring that
stale offers remain blocked for the lifetime of the CallManager.
https://claude.ai/code/session_0145VKiG8yZMqcMsaBEjNPxv
Three Android-specific optimizations:
1. Use Math.unsignedMultiplyHigh on API 35+ (Android 15): single UMULH
instruction, eliminates the 4-insn signed→unsigned correction that
the fallback path requires. Same optimization as our JVM 18+ path.
2. Use Math.multiplyHigh + correction on API 31-34 (Android 12-14):
avoids the pure-Kotlin 4×32-bit sub-product fallback entirely.
3. Resolve API level check ONCE at class load via static final fields
(HAS_MULTIPLY_HIGH, HAS_UNSIGNED_MULTIPLY_HIGH) instead of checking
Build.VERSION.SDK_INT on every call. These functions are called 16×
per field multiply (~12,000× per signature verify), so eliminating
the per-call branch matters.
Performance tiers on Android:
API 35+ (Android 15): ~same as JVM 18+ (UMULH intrinsic)
API 31-34 (Android 12-14): SMULH + 3 correction insns per product
API 26-30 (Android 8-11): pure-Kotlin fallback (4 sub-products)
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
Add precise per-operation cost analysis from comparing our Kotlin
implementation with bitcoin-core/secp256k1's C source:
- doublePoint: 1,516 insns (Kotlin) vs 530 insns (C) = 2.9×
- mul/sqr accounts for 76% of gap (UMULH+MUL+carry vs single MUL)
- add/neg/half accounts for 24% (reduceSelf vs lazy magnitude tracking)
- Update performance numbers to Java 21 results (verify 3.4×, sign 1.1×)
- Document all optimizations implemented during this session
- Note that lazy reduction penalty (4.2× on cheap ops) is the main
remaining algorithmic opportunity, but requires 5×52-bit limb change
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
- Add `inline` to hot-path tiny functions: U256.isZero, U256.testBit,
FieldP.reduceSelf, FieldP.neg, MutablePoint.isInfinity. These are
called thousands of times per EC operation; inline eliminates virtual
call overhead (mostly helps Kotlin/Native; JVM JIT already inlines).
- Fix stale comment: G_TABLE_SIZE is 1024 for w=12 (was "64 for w=8")
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
Move transitionToEnded() before the signing + relay publish in hangup()
so the UI stops ringing/ringback immediately, matching the pattern
already used by rejectCall(). Add onDestroy safety net in CallActivity
to hang up if the Activity is destroyed while a call is active. Wrap
audio stop methods in try-catch to prevent one failure from blocking
the others.
https://claude.ai/code/session_01Rip2HPCbF48PPFDiB2X5ik
inv() and sqrt() each allocated 11 LongArray(4) (plus 2 for sqrt
verification) on every call. These are now served from a thread-local
Array(11) { LongArray(4) } cache, eliminating 22-24 allocations per
ECDH operation (inv called in toAffine, sqrt called in liftX).
Also reuses chain scratch slots for sqrt's verification step instead
of allocating separate check/ar arrays.
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
Eliminates ~80 LongArray allocations per mul/mulDoubleG call by
pre-allocating the P-side Jacobian and affine tables, the doubling
temp, and the batch inversion scratch buffers in PointScratch
(thread-local, allocated once per thread, reused across calls).
Before: mul() allocated 8 MutablePoint (24 LongArray) + 8 MutablePoint
(24 LongArray) + 16 AffinePoint (32 LongArray) + batch temps = ~92
LongArray per call. After: 0 allocations in the table construction path.
Also fixes minor allocation in addMixed degenerate case (use t[5]
scratch instead of new LongArray(4)).
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
The JVM target is Java 21, so Math.unsignedMultiplyHigh (Java 18+) can
be called directly without MethodHandle reflection. The previous approach
used MethodHandle.invokeExact which Kotlin compiles with Object return
type, causing Long boxing on every call (3 box/unbox per invocation ×
16 calls per field multiply = 48 boxed objects per mul).
Direct call compiles to a single UMULH instruction with zero overhead.
This is the most performance-critical function: called ~12,000× per
signature verification.
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
Two microoptimizations:
1. reduceSelf: exploit P's structure (P[1..3] = 0xFFFFFFFFFFFFFFFF).
a >= P only if all top 3 limbs are max AND a[0] >= P[0]. The first
check (a[3] == -1) fails >99.99% of the time, making this a single
branch miss prediction instead of a 4-limb comparison loop.
Called ~1,300× per verify, ~500× per ECDH.
2. Pre-allocate wNAF IntArrays and scratch MutablePoint/LongArray in
PointScratch. Eliminates 8-12 IntArray(145) + 8-12 LongArray(4)
allocations per mul/mulDoubleG call. Adds wnafInto() to Glv that
writes into caller-provided arrays.
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
After swapping with an adjacent item, the dragOffset adjustment can
flip its sign (e.g. negative becomes positive), which immediately
triggers the second if-block to swap back in the opposite direction
within the same onDrag call. This causes the dragged item to jump
and the user to end up dragging a different item. Fix by returning
after each successful swap so only one swap occurs per drag event.
https://claude.ai/code/session_01RVM5kEJGrCaJTaP3GmVHDd
pOdd and pLamOdd always have identical Z coordinates (the GLV
endomorphism λ(X,Y,Z) = (β·X, Y, Z) preserves Z). Previously we
called batchToAffine separately for each table, paying two full field
inversions (~270 field ops each). Now batchToAffinePair uses a single
batch inversion and reuses the Z⁻¹ values for both tables.
Saves ~270 field ops per mul/mulDoubleG call (~12% of ECDH cost).
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
Remove the sortedBy(receivedBytes) from relayListBuilder and
Nip65RelayListViewModel.clear() so relays keep their order as
stored in the Nostr event. This makes drag-and-drop reordering
meaningful since the saved order is now preserved on reload.
https://claude.ai/code/session_01RVM5kEJGrCaJTaP3GmVHDd
When items swap during drag, the composable gets a new index value.
Using pointerInput(index) caused the gesture scope to restart, killing
the in-progress drag and leaving the UI stuck. Fix by using
rememberUpdatedState for the index so the pointerInput scope stays
alive across recompositions while always reading the current index.
https://claude.ai/code/session_01RVM5kEJGrCaJTaP3GmVHDd
Update KDoc and file headers across Secp256k1.kt, Point.kt, FieldP.kt,
and U256.kt with:
- Accurate benchmark numbers (well-warmed: verify 4.4x, sign 1.5x,
pubCreate 2.2x, ECDH 3.9x, compress 2x FASTER)
- Detailed comparison with C libsecp256k1 architecture choices
- Explanation of why certain C optimizations don't port to JVM:
* Lazy reduction: 4x64 limbs have no headroom (C's 5x52 has 12 bits)
* safegcd: slower on JVM due to 128-bit arithmetic overhead
* WINDOW_G=15: cache pressure from heap-allocated objects (w=12 optimal)
- Document effective-affine technique and batch inversion
- Increase all benchmark warmup/iterations for stable measurements
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
Tested WINDOW_G=15 (matching C libsecp256k1): 5.6x slower than native.
WINDOW_G=12 is faster at 4.3x because the 8192-entry table (1MB) at
w=15 causes cache pressure on JVM — heap-allocated AffinePoint objects
are scattered in memory, unlike C's contiguous compile-time .rodata.
WINDOW_G=12 (1024 entries, ~128KB) fits comfortably in L2 cache.
Increased verify benchmark warmup to 200+500 for stable measurements
(first call builds the lazy table).
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
The safegcd (Bernstein-Yang divsteps) algorithm is faster than Fermat
in C due to native 128-bit integer support, but on JVM the 128-bit
arithmetic overhead via multiplyHigh + carry tracking in the inner
loop (12 rounds × matrix multiply on 5 limbs) is slower than the
Fermat addition chain (255 sqr + 15 mul of optimized field ops).
Benchmark showed 8.3x vs native (was 5.0x with Fermat), confirming
that the per-operation constant factor matters more than algorithmic
complexity for this problem size on JVM.
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg