Skip to content
Merged
16 changes: 15 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,23 @@ The format is inspired by Keep a Changelog, and this project adheres to semantic

## [Unreleased]

### Fixed
### Changed
- Performance: secp256k1 arithmetic in `Point` now runs on BouncyCastle's custom curve
implementation instead of `BigInteger` affine double-and-add. `Schnorr.sign` drops from about
30 ms to about 0.3 ms, `Schnorr.verify` from about 14 ms to about 0.15 ms and public key
derivation from about 6 ms to about 0.08 ms on the reference machine. Outputs are
byte-identical, checked against the BIP-340 test vectors.
- Performance: `Schnorr.verify` computes `s*G - e*P` with one simultaneous two-scalar
multiplication (`Point.mulSum`), and `Schnorr.sign` reuses the public key point it already
holds in its self-check.
- Performance: `EventSerializer` streams the NIP-01 array straight to a `JsonGenerator`
(byte-identical output), and `EventFilter.toPredicate()` evaluates in a single pass over hash
sets.

### Fixed
- Upgrade Testcontainers to 1.21.4 so Docker integration tests work with Docker Engine 29+ (minimum API 1.40) on ubuntu-26.04 runners.
- `Schnorr.verify` now returns `false` instead of throwing a `NullPointerException` when the
verification point is the point at infinity.

## [2.4.3] - 2026-11-25

Expand Down
64 changes: 37 additions & 27 deletions nostr-java-core/src/main/java/nostr/crypto/Point.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
import nostr.util.NostrUtil;

import java.math.BigInteger;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.ec.CustomNamedCurves;
import org.bouncycastle.math.ec.ECAlgorithms;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.math.ec.FixedPointCombMultiplier;
import org.bouncycastle.math.ec.FixedPointUtil;
import java.security.NoSuchAlgorithmException;

/**
Expand All @@ -27,6 +34,15 @@ public class Point {
new BigInteger("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16));

private static final BigInteger BI_TWO = BigInteger.valueOf(2);
private static final X9ECParameters BC_PARAMS = CustomNamedCurves.getByName("secp256k1");
private static final ECCurve BC_CURVE = BC_PARAMS.getCurve();
private static final ECPoint BC_G = BC_PARAMS.getG();
private static final FixedPointCombMultiplier G_MULTIPLIER = new FixedPointCombMultiplier();

static {
FixedPointUtil.precompute(BC_G);
}

private final Pair<BigInteger, BigInteger> pair;

/**
Expand Down Expand Up @@ -103,40 +119,34 @@ public static Point add(Point P1, Point P2) {
if (P2 == null || P2.isInfinite()) {
return P1;
}
if (P1.getX().equals(P2.getX()) && !P1.getY().equals(P2.getY())) {
return infinityPoint();
}
return fromBc(toBc(P1).add(toBc(P2)));
}

BigInteger lam;
if (P1.equals(P2)) {
BigInteger base = P2.getY().multiply(BI_TWO);
lam =
(BigInteger.valueOf(3L)
.multiply(P1.getX())
.multiply(P1.getX())
.multiply(base.modPow(p.subtract(BI_TWO), p)))
.mod(p);
} else {
BigInteger base = P2.getX().subtract(P1.getX());
lam = ((P2.getY().subtract(P1.getY())).multiply(base.modPow(p.subtract(BI_TWO), p))).mod(p);
public static Point mul(Point P, BigInteger n) {
if (n.signum() == 0) {
return null;
}

BigInteger x3 = (lam.multiply(lam).subtract(P1.getX()).subtract(P2.getX())).mod(p);
return new Point(x3, lam.multiply(P1.getX().subtract(x3)).subtract(P1.getY()).mod(p));
ECPoint r = P.equals(G) ? G_MULTIPLIER.multiply(BC_G, n) : toBc(P).multiply(n);
return fromBc(r);
}

public static Point mul(Point P, BigInteger n) {
/** Returns {@code a*P + b*Q} using a simultaneous two-scalar multiplication. */
public static Point mulSum(Point P, BigInteger a, Point Q, BigInteger b) {
ECPoint p1 = P.equals(G) ? BC_G : toBc(P);
ECPoint q1 = Q.equals(G) ? BC_G : toBc(Q);
return fromBc(ECAlgorithms.sumOfTwoMultiplies(p1, a, q1, b));
}

Point R = null;
private static ECPoint toBc(Point P) {
return BC_CURVE.createPoint(P.getX(), P.getY());
}

for (int i = 0; i < 256; i++) {
if (n.shiftRight(i).and(BigInteger.ONE).compareTo(BigInteger.ZERO) > 0) {
R = add(R, P);
}
P = add(P, P);
private static Point fromBc(ECPoint r) {
if (r.isInfinity()) {
return infinityPoint();
}

return R;
r = r.normalize();
return new Point(r.getAffineXCoord().toBigInteger(), r.getAffineYCoord().toBigInteger());
}

public boolean hasEvenY() {
Expand Down
48 changes: 24 additions & 24 deletions nostr-java-core/src/main/java/nostr/crypto/schnorr/Schnorr.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,17 @@ public static byte[] sign(byte[] msg, byte[] secKey, byte[] auxRand) throws Schn
if (!P.hasEvenY()) {
secKey0 = Point.getn().subtract(secKey0);
}
int len = NostrUtil.bytesFromBigInteger(secKey0).length + P.toBytes().length + msg.length;
byte[] buf = new byte[len];
byte[] t =
NostrUtil.xor(
NostrUtil.bytesFromBigInteger(secKey0), taggedHashUnchecked("BIP0340/aux", auxRand));
byte[] pBytes = P.toBytes();
byte[] t = NostrUtil.xor(NostrUtil.bytesFromBigInteger(secKey0), taggedHashUnchecked("BIP0340/aux", auxRand));

if (t == null) {
throw new RuntimeException("Unexpected error. Null array");
}

byte[] buf = new byte[t.length + pBytes.length + msg.length];
System.arraycopy(t, 0, buf, 0, t.length);
System.arraycopy(P.toBytes(), 0, buf, t.length, P.toBytes().length);
System.arraycopy(msg, 0, buf, t.length + P.toBytes().length, msg.length);
System.arraycopy(pBytes, 0, buf, t.length, pBytes.length);
System.arraycopy(msg, 0, buf, t.length + pBytes.length, msg.length);
BigInteger k0 =
NostrUtil.bigIntFromBytes(taggedHashUnchecked("BIP0340/nonce", buf)).mod(Point.getn());
if (k0.compareTo(BigInteger.ZERO) == 0) {
Expand All @@ -70,24 +68,21 @@ public static byte[] sign(byte[] msg, byte[] secKey, byte[] auxRand) throws Schn
} else {
k = k0;
}
len = R.toBytes().length + P.toBytes().length + msg.length;
buf = new byte[len];
System.arraycopy(R.toBytes(), 0, buf, 0, R.toBytes().length);
System.arraycopy(P.toBytes(), 0, buf, R.toBytes().length, P.toBytes().length);
System.arraycopy(msg, 0, buf, R.toBytes().length + P.toBytes().length, msg.length);
byte[] rBytes = R.toBytes();
buf = new byte[rBytes.length + pBytes.length + msg.length];
System.arraycopy(rBytes, 0, buf, 0, rBytes.length);
System.arraycopy(pBytes, 0, buf, rBytes.length, pBytes.length);
System.arraycopy(msg, 0, buf, rBytes.length + pBytes.length, msg.length);
BigInteger e =
NostrUtil.bigIntFromBytes(taggedHashUnchecked("BIP0340/challenge", buf)).mod(Point.getn());
BigInteger kes = k.add(e.multiply(secKey0)).mod(Point.getn());
len = R.toBytes().length + NostrUtil.bytesFromBigInteger(kes).length;
byte[] sig = new byte[len];
System.arraycopy(R.toBytes(), 0, sig, 0, R.toBytes().length);
System.arraycopy(
NostrUtil.bytesFromBigInteger(kes),
0,
sig,
R.toBytes().length,
NostrUtil.bytesFromBigInteger(kes).length);
if (!verify(msg, P.toBytes(), sig)) {
byte[] kesBytes = NostrUtil.bytesFromBigInteger(kes);
byte[] sig = new byte[rBytes.length + kesBytes.length];
System.arraycopy(rBytes, 0, sig, 0, rBytes.length);
System.arraycopy(kesBytes, 0, sig, rBytes.length, kesBytes.length);
// The public key point is already known, so the self-check skips lifting it again.
Point pEven = P.hasEvenY() ? P : new Point(P.getX(), Point.getp().subtract(P.getY()));
if (!verify(msg, pBytes, pEven, sig)) {
throw new SchnorrException("The signature does not pass verification.");
}
return sig;
Expand Down Expand Up @@ -119,6 +114,11 @@ public static boolean verify(byte[] msg, byte[] pubkey, byte[] sig) throws Schno
if (P == null) {
return false;
}
return verify(msg, pubkey, P, sig);
}

private static boolean verify(byte[] msg, byte[] pubkey, Point P, byte[] sig)
throws SchnorrException {
BigInteger r = NostrUtil.bigIntFromBytes(Arrays.copyOfRange(sig, 0, 32));
BigInteger s = NostrUtil.bigIntFromBytes(Arrays.copyOfRange(sig, 32, 64));
if (r.compareTo(Point.getp()) >= 0 || s.compareTo(Point.getn()) >= 0) {
Expand All @@ -131,8 +131,8 @@ public static boolean verify(byte[] msg, byte[] pubkey, byte[] sig) throws Schno
System.arraycopy(msg, 0, buf, 32 + pubkey.length, msg.length);
BigInteger e =
NostrUtil.bigIntFromBytes(taggedHashUnchecked("BIP0340/challenge", buf)).mod(Point.getn());
Point R = Point.add(Point.mul(Point.getG(), s), Point.mul(P, Point.getn().subtract(e)));
return R != null && R.hasEvenY() && R.getX().compareTo(r) == 0;
Point R = Point.mulSum(Point.getG(), s, P, Point.getn().subtract(e));
return R != null && !R.isInfinite() && R.hasEvenY() && R.getX().compareTo(r) == 0;
}

/**
Expand Down
61 changes: 60 additions & 1 deletion nostr-java-core/src/test/java/nostr/crypto/PointTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

import java.math.BigInteger;

import nostr.util.NostrUtil;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

class PointTest {
Expand All @@ -25,5 +28,61 @@ void infinityPointIsInfinite() {
Point inf = Point.infinityPoint();
assertTrue(inf.isInfinite());
}
}

// Known value: x-coordinate of 2G on secp256k1.
@Test
void mulMatchesKnownMultiplesOfG() {
assertSamePoint(Point.G, Point.mul(Point.G, BigInteger.ONE));
Point twoG = Point.mul(Point.G, BigInteger.TWO);
assertEquals(
"c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5",
NostrUtil.bytesToHex(NostrUtil.bytesFromBigInteger(twoG.getX())));
assertSamePoint(twoG, Point.add(Point.G, Point.G));
}

// The group order times G is the point at infinity; a zero scalar yields no point.
@Test
void mulByOrderIsInfinityAndByZeroIsNull() {
assertTrue(Point.mul(Point.G, Point.getn()).isInfinite());
assertNull(Point.mul(Point.G, BigInteger.ZERO));
}

// The simultaneous multiplication must equal two multiplications plus an addition.
@Test
void mulSumEqualsSeparateMultiplications() {
Point q = Point.mul(Point.G, new BigInteger("123456789012345678901234567890"));
BigInteger a = new BigInteger("987654321098765432109876543210987654321");
BigInteger b = Point.getn().subtract(BigInteger.valueOf(77));
assertSamePoint(
Point.add(Point.mul(Point.G, a), Point.mul(q, b)), Point.mulSum(Point.G, a, q, b));
assertSamePoint(Point.add(Point.mul(q, a), Point.mul(q, b)), Point.mulSum(q, a, q, b));
}

// liftX keeps the even y, rejects out-of-range x, and rejects x with no curve point.
@Test
void liftXReturnsEvenYPointsOnTheCurveAndRejectsTheRest() {
assertSamePoint(Point.G, Point.liftX(NostrUtil.bytesFromBigInteger(Point.G.getX())));
assertNull(Point.liftX(NostrUtil.bytesFromBigInteger(Point.getp())));
int lifted = 0;
int rejected = 0;
for (int i = 1; i <= 40; i++) {
Point lift = Point.liftX(NostrUtil.bytesFromBigInteger(BigInteger.valueOf(i)));
if (lift == null) {
rejected++;
continue;
}
lifted++;
assertTrue(lift.hasEvenY());
BigInteger x = lift.getX();
BigInteger rhs = x.pow(3).add(BigInteger.valueOf(7)).mod(Point.getp());
assertEquals(rhs, lift.getY().pow(2).mod(Point.getp()));
}
assertTrue(lifted > 0 && rejected > 0);
}

// Point defines only equals(Point), an overload, so compare coordinates explicitly.
private static void assertSamePoint(Point expected, Point actual) {
assertEquals(expected.getX(), actual.getX());
assertEquals(expected.getY(), actual.getY());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,52 @@ void verifyRejectsInvalidLengths() throws Exception {
assertThrows(SchnorrException.class, () -> Schnorr.verify(msg, new byte[31], sig));
assertThrows(SchnorrException.class, () -> Schnorr.verify(msg, pub, new byte[63]));
}
}

// Official BIP-340 test vectors (bip-0340/test-vectors.csv), indices 0 and 1.
@Test
void matchesBip340SigningVectors() throws Exception {
assertBip340Vector(
"0000000000000000000000000000000000000000000000000000000000000003",
"F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9",
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000000",
"E907831F80848D1069A5371B402410364BDF1C5F8307B0084C55F1CE2DCA8215"
+ "25F66A4A85EA8B71E482A74F382D2CE5EBEEE8FDB2172F477DF4900D310536C0");
assertBip340Vector(
"B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF",
"DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659",
"0000000000000000000000000000000000000000000000000000000000000001",
"243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89",
"6896BD60EEAE296DB48A229FF71DFE071BDE413E6D43F917DC8DCF8C78DE3341"
+ "8906D11AC976ABCCB20B091292BFF4EA897EFCB639EA871CFA95F6DE339E4B0A");
}

// BIP-340 vector 5: the public key is not a point on the curve, so verification must fail.
@Test
void verifyRejectsPublicKeyNotOnCurve() throws Exception {
byte[] pub =
hex("EEFDEA4CDB677750A420FEE807EACF21EB9898AE79B9768766E4FAA04A2D4A34");
byte[] msg =
hex("243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89");
byte[] sig =
hex(
"6CFF5C3BA86C69EA4B7376F31A9BCB4F74C1976089B2D9963DA2E5543E177769"
+ "69E89B4C5564D00349106B8497785DD7D1D713A8AE82B32FA79D5F7FC407D39B");
assertFalse(Schnorr.verify(msg, pub, sig));
}

private static void assertBip340Vector(
String secKey, String pubKey, String aux, String msg, String sig) throws Exception {
byte[] sk = hex(secKey);
byte[] m = hex(msg);
assertEquals(pubKey.toLowerCase(), NostrUtil.bytesToHex(Schnorr.genPubKey(sk)));
byte[] signature = Schnorr.sign(m, sk, hex(aux));
assertEquals(sig.toLowerCase(), NostrUtil.bytesToHex(signature));
assertTrue(Schnorr.verify(m, hex(pubKey), signature));
}

// BIP-340 vectors use upper-case hex, which NostrUtil's validator rejects.
private static byte[] hex(String s) {
return java.util.HexFormat.of().parseHex(s);
}
}
Loading