diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e0ad264..bdfa08ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/nostr-java-core/src/main/java/nostr/crypto/Point.java b/nostr-java-core/src/main/java/nostr/crypto/Point.java index bae1c018..e9973f55 100644 --- a/nostr-java-core/src/main/java/nostr/crypto/Point.java +++ b/nostr-java-core/src/main/java/nostr/crypto/Point.java @@ -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; /** @@ -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 pair; /** @@ -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() { diff --git a/nostr-java-core/src/main/java/nostr/crypto/schnorr/Schnorr.java b/nostr-java-core/src/main/java/nostr/crypto/schnorr/Schnorr.java index e94879ae..ae2519b5 100644 --- a/nostr-java-core/src/main/java/nostr/crypto/schnorr/Schnorr.java +++ b/nostr-java-core/src/main/java/nostr/crypto/schnorr/Schnorr.java @@ -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) { @@ -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; @@ -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) { @@ -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; } /** diff --git a/nostr-java-core/src/test/java/nostr/crypto/PointTest.java b/nostr-java-core/src/test/java/nostr/crypto/PointTest.java index 4c835af8..fb2b00da 100644 --- a/nostr-java-core/src/test/java/nostr/crypto/PointTest.java +++ b/nostr-java-core/src/test/java/nostr/crypto/PointTest.java @@ -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 { @@ -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()); + } +} diff --git a/nostr-java-core/src/test/java/nostr/crypto/schnorr/SchnorrTest.java b/nostr-java-core/src/test/java/nostr/crypto/schnorr/SchnorrTest.java index 114a4cf9..5d7f2062 100644 --- a/nostr-java-core/src/test/java/nostr/crypto/schnorr/SchnorrTest.java +++ b/nostr-java-core/src/test/java/nostr/crypto/schnorr/SchnorrTest.java @@ -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); + } +} diff --git a/nostr-java-event/src/main/java/nostr/event/filter/EventFilter.java b/nostr-java-event/src/main/java/nostr/event/filter/EventFilter.java index 45769423..0f126f39 100644 --- a/nostr-java-event/src/main/java/nostr/event/filter/EventFilter.java +++ b/nostr-java-event/src/main/java/nostr/event/filter/EventFilter.java @@ -8,6 +8,7 @@ import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; +import nostr.event.BaseTag; import nostr.event.impl.GenericEvent; import nostr.event.json.EventJsonMapper; import nostr.event.tag.GenericTag; @@ -15,9 +16,11 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.Predicate; /** @@ -54,37 +57,47 @@ public static Builder builder() { } public Predicate toPredicate() { - Predicate predicate = e -> true; + Set idSet = new HashSet<>(ids); + Set authorSet = new HashSet<>(authors); + Set kindSet = new HashSet<>(kinds); + Map> tagSets = new HashMap<>(); + tagFilters.forEach((code, values) -> tagSets.put(code, new HashSet<>(values))); + + return e -> { + if (!idSet.isEmpty() && !idSet.contains(e.getId())) { + return false; + } + if (!authorSet.isEmpty() && !authorSet.contains(e.getPubKey().toHexString())) { + return false; + } + if (!kindSet.isEmpty() && !kindSet.contains(e.getKind())) { + return false; + } + if (since != null && !(e.getCreatedAt() != null && e.getCreatedAt() > since)) { + return false; + } + if (until != null && !(e.getCreatedAt() != null && e.getCreatedAt() < until)) { + return false; + } + for (Map.Entry> entry : tagSets.entrySet()) { + if (!hasTagValue(e, entry.getKey(), entry.getValue())) { + return false; + } + } + return true; + }; + } - if (!ids.isEmpty()) { - predicate = predicate.and(e -> ids.contains(e.getId())); - } - if (!authors.isEmpty()) { - predicate = predicate.and(e -> authors.contains(e.getPubKey().toHexString())); - } - if (!kinds.isEmpty()) { - predicate = predicate.and(e -> kinds.contains(e.getKind())); - } - if (since != null) { - predicate = predicate.and(e -> e.getCreatedAt() != null && e.getCreatedAt() > since); - } - if (until != null) { - predicate = predicate.and(e -> e.getCreatedAt() != null && e.getCreatedAt() < until); - } - if (!tagFilters.isEmpty()) { - for (Map.Entry> entry : tagFilters.entrySet()) { - String tagCode = entry.getKey(); - List values = entry.getValue(); - predicate = predicate.and(e -> - e.getTags().stream() - .filter(GenericTag.class::isInstance) - .map(GenericTag.class::cast) - .filter(t -> t.getCode().equals(tagCode)) - .anyMatch(t -> !t.getParams().isEmpty() && values.contains(t.getParams().get(0)))); + private static boolean hasTagValue(GenericEvent e, String code, Set values) { + for (BaseTag tag : e.getTags()) { + if (tag instanceof GenericTag t + && t.getCode().equals(code) + && !t.getParams().isEmpty() + && values.contains(t.getParams().get(0))) { + return true; } } - - return predicate; + return false; } /** diff --git a/nostr-java-event/src/main/java/nostr/event/serializer/EventSerializer.java b/nostr-java-event/src/main/java/nostr/event/serializer/EventSerializer.java index 616970e5..f3dcce87 100644 --- a/nostr-java-event/src/main/java/nostr/event/serializer/EventSerializer.java +++ b/nostr-java-event/src/main/java/nostr/event/serializer/EventSerializer.java @@ -1,8 +1,7 @@ package nostr.event.serializer; -import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; import lombok.NonNull; import nostr.base.PublicKey; import nostr.event.BaseTag; @@ -10,6 +9,8 @@ import nostr.util.NostrException; import nostr.util.NostrUtil; +import java.io.IOException; +import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.time.Instant; @@ -108,18 +109,25 @@ public static String serialize( @NonNull String content) throws NostrException { - var arrayNode = JsonNodeFactory.instance.arrayNode(); - try { - arrayNode.add(0); // Protocol version - arrayNode.add(pubKey.toString()); - arrayNode.add(createdAt); - arrayNode.add(kind); - arrayNode.add(MAPPER.valueToTree(tags)); - arrayNode.add(content); - - return MAPPER.writeValueAsString(arrayNode); - } catch (JsonProcessingException e) { + var out = new StringWriter(128 + content.length()); + try (JsonGenerator gen = MAPPER.getFactory().createGenerator(out)) { + gen.setCodec(MAPPER); + gen.writeStartArray(); + gen.writeNumber(0); // Protocol version + gen.writeString(pubKey.toString()); + gen.writeNumber(createdAt); + gen.writeNumber(kind); + gen.writeStartArray(); + for (BaseTag tag : tags) { + gen.writeObject(tag); + } + gen.writeEndArray(); + gen.writeString(content); + gen.writeEndArray(); + } + return out.toString(); + } catch (IOException e) { throw new NostrException("Failed to serialize event: " + e.getMessage(), e); } }