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
Replace Fermat's little theorem (a^(p-2), 255 sqr + 15 mul) with the
safegcd divsteps algorithm for field element inversion. This processes
62 divsteps per batch using a 2×2 transition matrix applied to
full-precision values via 128-bit arithmetic (multiplyHigh).
12 rounds × 62 steps = 744 total divsteps (≥741 needed for 256 bits).
Uses 5×62-bit signed limb representation for intermediate values and
Montgomery-style correction (precomputed p^{-1} mod 2^62) for the
modular reduction in updateDE.
The old Fermat chain is preserved as FieldP.invFermat for reference.
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
When accepting an incoming WebRTC call via the notification's Accept
button, CallActivity now checks for RECORD_AUDIO and CAMERA permissions
before proceeding. If permissions are missing, the system permission
dialog is shown and the call is accepted only after permissions are
granted. This prevents the crash that occurred when accepting calls
from the notification without prior permission grants.
https://claude.ai/code/session_0193KQShzBh4puYh74dHgSbE
Set userScrollEnabled = !isDragging on all LazyColumns that host
draggable relay items so the scroll gesture doesn't fight the drag
gesture. In AllRelayListScreen, scroll is disabled when any of the
12 category drag states is active.
https://claude.ai/code/session_01RVM5kEJGrCaJTaP3GmVHDd
Replace the single-item Column approach with RelayDragState that works
within itemsIndexed. Each relay item remains a separate lazy item for
better performance with large lists. The drag handle icon on each row
captures drag gestures while the item modifier applies visual feedback
(elevation, scale, translation).
https://claude.ai/code/session_01RVM5kEJGrCaJTaP3GmVHDd
Add DraggableRelayList composable with gesture-based drag-and-drop,
following the same pattern used in ReactionsSettingsScreen. Each relay
category (DM, NIP65 home/notif, search, blocked, trusted, local,
broadcast, indexer, proxy, private outbox, favorites) now shows a
drag handle and supports reordering via drag gestures.
https://claude.ai/code/session_01RVM5kEJGrCaJTaP3GmVHDd
- Increase WINDOW_G from 8 to 12 for mulDoubleG (verify): reduces
G-side additions from ~32 to ~22 per verification (saves ~110 field ops)
- Add batchToAffine using Montgomery's trick: 1 inversion + 3(n-1) muls
instead of n individual inversions. Critical for the 1024-entry table.
- Table size: 1024 entries × 64 bytes = ~128KB (lazy, built on first use)
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
The publish KeyPackage button was always active because the app didn't
track whether a key package had already been published. This adds:
- hasActiveKeyPackages() to KeyPackageRotationManager and MarmotManager
- hasPublishedKeyPackage() to Account, checking both in-memory bundles
and the local cache for existing kind:30443 events
- Own key package filter in MarmotSubscriptionManager and the EOSE
manager so previously published key packages are downloaded from
relays on app restart
- UI feedback: primary-colored key icon when published, contextual
empty-state message, and a spinner during publishing
https://claude.ai/code/session_01BVe7aSEWd2KLi5Ks6RZkcc
- Add ECPoint.toAffineX that computes only x = X/Z² (saves 2M vs full
toAffine which also computes Y/Z³)
- Use toAffineX in ecdhXOnly since only the x-coordinate is needed
- Add ecdhXOnly benchmark measuring the actual Nostr ECDH production
path (Secp256k1Instance.pubKeyTweakMulCompact delegates to ecdhXOnly)
- Fix ktlint KDoc-inside-class-body violations
The old benchmark measured pubKeyTweakMul(02||x, key) which pays for:
array allocation, compressed key parsing (sqrt), full toAffine, and
re-serialization. ecdhXOnly avoids the array overhead and serialization.
https://claude.ai/code/session_01BhU63WUe9AhikZxRdw3Lpg
Replace the raw OutlinedTextField + IconButton Row with
ThinPaddingTextField, ThinSendButton, EditFieldBorder, and
EditFieldModifier to match the private DM and channel chat layouts.
https://claude.ai/code/session_013dhfy18dfuSYN8khXiLLBb